AC_PROG_CC_STDC: fold into AC_PROG_CC, removing C11 macro
[autoconf.git] / doc / autoconf.texi
blob86b31ee9b33b968757a79ad52f59ad40639e4e29
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{]}
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}
27 @end macro
29 @c @dvarv(ARG, DEFAULT-VAR)
30 @c ------------------------
31 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
32 @c around DEFAULT-VAR.
33 @macro dvarv{varname, default}
34 @r{[}@var{\varname\} = @var{\default\}@r{]}@c
35 @end macro
37 @c Handling the indexes with Texinfo yields several different problems.
39 @c Because we want to drop out the AC_ part of the macro names in the
40 @c printed manual, but not in the other outputs, we need a layer above
41 @c the usual @acindex{} etc.  That's why we first define indexes such as
42 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
43 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
44 @c So use something more regular ``acx''.  Then you finish with a printed
45 @c index saying ``index is not existent''.  Of course: you ought to use
46 @c two letters :(  So you use capitals.
48 @c Second, when defining a macro in the TeX world, following spaces are
49 @c eaten.  But then, since we embed @acxindex commands that use the end
50 @c of line as an end marker, the whole things wrecks itself.  So make
51 @c sure you do *force* an additional end of line, add a ``@c''.
53 @c Finally, you might want to get rid of TeX expansion, using --expand
54 @c with texi2dvi.  But then you wake up an old problem: we use macros
55 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
57 @c Define an environment variable index, for variables users may set
58 @c in their environment or on the configure command line.
59 @defcodeindex ev
60 @c Define an output variable index, for commonly AC_SUBST'ed variables.
61 @defcodeindex ov
62 @c Define a cache variable index, for variables matching *_cv_*.
63 @defcodeindex CA
64 @c Other shell variables not fitting the above categories should be
65 @c listed in the predefined vrindex, which we merge in the concept index.
66 @syncodeindex vr cp
67 @c Define a CPP preprocessor macro index, for #define'd strings.
68 @defcodeindex cv
69 @c Define an Autoconf macro index that @defmac doesn't write to.
70 @defcodeindex AC
71 @c Define an Autotest macro index that @defmac doesn't write to.
72 @defcodeindex AT
73 @c Define an M4sugar macro index that @defmac doesn't write to.
74 @defcodeindex MS
75 @c Define an index for *foreign* programs: `mv' etc.  Used for the
76 @c portability sections and so on.
77 @defindex pr
79 @c shortindexflag
80 @c --------------
81 @c Shall we factor AC_ out of the Autoconf macro index etc.?
82 @iftex
83 @set shortindexflag
84 @end iftex
86 @c @acindex{MACRO}
87 @c ---------------
88 @c Registering an AC_\MACRO\.
89 @ifset shortindexflag
90 @macro acindex{macro}
91 @ACindex \macro\
93 @end macro
94 @end ifset
95 @ifclear shortindexflag
96 @macro acindex{macro}
97 @ACindex AC_\macro\
98 @end macro
99 @end ifclear
101 @c @ahindex{MACRO}
102 @c ---------------
103 @c Registering an AH_\MACRO\.
104 @macro ahindex{macro}
105 @ACindex AH_\macro\
107 @end macro
109 @c @asindex{MACRO}
110 @c ---------------
111 @c Registering an AS_\MACRO\.
112 @ifset shortindexflag
113 @macro asindex{macro}
114 @MSindex \macro\
116 @end macro
117 @end ifset
118 @ifclear shortindexflag
119 @macro asindex{macro}
120 @MSindex AS_\macro\
121 @end macro
122 @end ifclear
124 @c @atindex{MACRO}
125 @c ---------------
126 @c Registering an AT_\MACRO\.
127 @ifset shortindexflag
128 @macro atindex{macro}
129 @ATindex \macro\
131 @end macro
132 @end ifset
133 @ifclear shortindexflag
134 @macro atindex{macro}
135 @ATindex AT_\macro\
136 @end macro
137 @end ifclear
139 @c @auindex{MACRO}
140 @c ---------------
141 @c Registering an AU_\MACRO\.
142 @macro auindex{macro}
143 @ACindex AU_\macro\
145 @end macro
147 @c @hdrindex{MACRO}
148 @c ----------------
149 @c Indexing a header.
150 @macro hdrindex{macro}
151 @prindex @file{\macro\}
153 @end macro
155 @c @msindex{MACRO}
156 @c ---------------
157 @c Registering an m4_\MACRO\.
158 @ifset shortindexflag
159 @macro msindex{macro}
160 @MSindex \macro\
162 @end macro
163 @end ifset
164 @ifclear shortindexflag
165 @macro msindex{macro}
166 @MSindex m4_\macro\
167 @end macro
168 @end ifclear
171 @c @caindex{VARIABLE}
172 @c ------------------
173 @c Registering an ac_cv_\VARIABLE\ cache variable.
174 @ifset shortindexflag
175 @macro caindex{macro}
176 @CAindex \macro\
177 @end macro
178 @end ifset
179 @ifclear shortindexflag
180 @macro caindex{macro}
181 @CAindex ac_cv_\macro\
182 @end macro
183 @end ifclear
185 @c Define an index for functions: `alloca' etc.  Used for the
186 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
187 @c since `@defmac' goes into it => we'd get all the macros too.
189 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
191 @c   ! No room for a new @write .
192 @c   l.112 @defcodeindex fu
194 @c   so don't define yet another one :(  Just put some tags before each
195 @c   @prindex which is actually a @funindex.
197 @c   @defcodeindex fu
200 @c   @c Put the programs and functions into their own index.
201 @c   @syncodeindex fu pr
203 @comment %**end of header
204 @comment ========================================================
206 @copying
208 This manual (@value{UPDATED}) is for GNU Autoconf
209 (version @value{VERSION}),
210 a package for creating scripts to configure source code packages using
211 templates and an M4 macro package.
213 Copyright @copyright{} 1992-1996, 1998-2012 Free Software Foundation,
214 Inc.
216 @quotation
217 Permission is granted to copy, distribute and/or modify this document
218 under the terms of the GNU Free Documentation License,
219 Version 1.3 or any later version published by the Free Software
220 Foundation; with no Invariant Sections, no Front-Cover texts, and
221 no Back-Cover Texts.  A copy of the license is included in the section
222 entitled ``GNU Free Documentation License.''
223 @end quotation
224 @end copying
228 @dircategory Software development
229 @direntry
230 * Autoconf: (autoconf).         Create source code configuration scripts.
231 @end direntry
233 @dircategory Individual utilities
234 @direntry
235 * autoscan: (autoconf)autoscan Invocation.
236                                 Semi-automatic @file{configure.ac} writing
237 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
238 * autoconf-invocation: (autoconf)autoconf Invocation.
239                                 How to create configuration scripts
240 * autoreconf: (autoconf)autoreconf Invocation.
241                                 Remaking multiple @command{configure} scripts
242 * autoheader: (autoconf)autoheader Invocation.
243                                 How to create configuration templates
244 * autom4te: (autoconf)autom4te Invocation.
245                                 The Autoconf executables backbone
246 * configure: (autoconf)configure Invocation.    Configuring a package.
247 * autoupdate: (autoconf)autoupdate Invocation.
248                                 Automatic update of @file{configure.ac}
249 * config.status: (autoconf)config.status Invocation. Recreating configurations.
250 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
251 @end direntry
253 @titlepage
254 @title Autoconf
255 @subtitle Creating Automatic Configuration Scripts
256 @subtitle for version @value{VERSION}, @value{UPDATED}
257 @author David MacKenzie
258 @author Ben Elliston
259 @author Akim Demaille
260 @page
261 @vskip 0pt plus 1filll
262 @insertcopying
263 @end titlepage
265 @contents
268 @ifnottex
269 @node Top
270 @top Autoconf
271 @insertcopying
272 @end ifnottex
274 @c The master menu, created with texinfo-master-menu, goes here.
276 @menu
277 * Introduction::                Autoconf's purpose, strengths, and weaknesses
278 * The GNU Build System::        A set of tools for portable software packages
279 * Making configure Scripts::    How to organize and produce Autoconf scripts
280 * Setup::                       Initialization and output
281 * Existing Tests::              Macros that check for particular features
282 * Writing Tests::               How to write new feature checks
283 * Results::                     What to do with results from feature checks
284 * Programming in M4::           Layers on top of which Autoconf is written
285 * Programming in M4sh::         Shell portability layer
286 * Writing Autoconf Macros::     Adding new macros to Autoconf
287 * Portable Shell::              Shell script portability pitfalls
288 * Portable Make::               Makefile portability pitfalls
289 * Portable C and C++::          C and C++ portability pitfalls
290 * Manual Configuration::        Selecting features that can't be guessed
291 * Site Configuration::          Local defaults for @command{configure}
292 * Running configure Scripts::   How to use the Autoconf output
293 * config.status Invocation::    Recreating a configuration
294 * Obsolete Constructs::         Kept for backward compatibility
295 * Using Autotest::              Creating portable test suites
296 * FAQ::                         Frequent Autoconf Questions, with answers
297 * History::                     History of Autoconf
298 * GNU Free Documentation License::  License for copying this manual
299 * Indices::                     Indices of symbols, concepts, etc.
301 @detailmenu
302  --- The Detailed Node Listing ---
304 The GNU Build System
306 * Automake::                    Escaping makefile hell
307 * Gnulib::                      The GNU portability library
308 * Libtool::                     Building libraries portably
309 * Pointers::                    More info on the GNU build system
311 Making @command{configure} Scripts
313 * Writing Autoconf Input::      What to put in an Autoconf input file
314 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
315 * ifnames Invocation::          Listing the conditionals in source code
316 * autoconf Invocation::         How to create configuration scripts
317 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
319 Writing @file{configure.ac}
321 * Shell Script Compiler::       Autoconf as solution of a problem
322 * Autoconf Language::           Programming in Autoconf
323 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
325 Initialization and Output Files
327 * Initializing configure::      Option processing etc.
328 * Versioning::                  Dealing with Autoconf versions
329 * Notices::                     Copyright, version numbers in @command{configure}
330 * Input::                       Where Autoconf should find files
331 * Output::                      Outputting results from the configuration
332 * Configuration Actions::       Preparing the output based on results
333 * Configuration Files::         Creating output files
334 * Makefile Substitutions::      Using output variables in makefiles
335 * Configuration Headers::       Creating a configuration header file
336 * Configuration Commands::      Running arbitrary instantiation commands
337 * Configuration Links::         Links depending on the configuration
338 * Subdirectories::              Configuring independent packages together
339 * Default Prefix::              Changing the default installation prefix
341 Substitutions in Makefiles
343 * Preset Output Variables::     Output variables that are always set
344 * Installation Directory Variables::  Other preset output variables
345 * Changed Directory Variables::  Warnings about @file{datarootdir}
346 * Build Directories::           Supporting multiple concurrent compiles
347 * Automatic Remaking::          Makefile rules for configuring
349 Configuration Header Files
351 * Header Templates::            Input for the configuration headers
352 * autoheader Invocation::       How to create configuration templates
353 * Autoheader Macros::           How to specify CPP templates
355 Existing Tests
357 * Common Behavior::             Macros' standard schemes
358 * Alternative Programs::        Selecting between alternative programs
359 * Files::                       Checking for the existence of files
360 * Libraries::                   Library archives that might be missing
361 * Library Functions::           C library functions that might be missing
362 * Header Files::                Header files that might be missing
363 * Declarations::                Declarations that may be missing
364 * Structures::                  Structures or members that might be missing
365 * Types::                       Types that might be missing
366 * Compilers and Preprocessors::  Checking for compiling programs
367 * System Services::             Operating system services
368 * Posix Variants::              Special kludges for specific Posix variants
369 * Erlang Libraries::            Checking for the existence of Erlang libraries
371 Common Behavior
373 * Standard Symbols::            Symbols defined by the macros
374 * Default Includes::            Includes used by the generic macros
376 Alternative Programs
378 * Particular Programs::         Special handling to find certain programs
379 * Generic Programs::            How to find other programs
381 Library Functions
383 * Function Portability::        Pitfalls with usual functions
384 * Particular Functions::        Special handling to find certain functions
385 * Generic Functions::           How to find other functions
387 Header Files
389 * Header Portability::          Collected knowledge on common headers
390 * Particular Headers::          Special handling to find certain headers
391 * Generic Headers::             How to find other headers
393 Declarations
395 * Particular Declarations::     Macros to check for certain declarations
396 * Generic Declarations::        How to find other declarations
398 Structures
400 * Particular Structures::       Macros to check for certain structure members
401 * Generic Structures::          How to find other structure members
403 Types
405 * Particular Types::            Special handling to find certain types
406 * Generic Types::               How to find other types
408 Compilers and Preprocessors
410 * Specific Compiler Characteristics::  Some portability issues
411 * Generic Compiler Characteristics::  Language independent tests and features
412 * C Compiler::                  Checking its characteristics
413 * C++ Compiler::                Likewise
414 * Objective C Compiler::        Likewise
415 * Objective C++ Compiler::      Likewise
416 * Erlang Compiler and Interpreter::  Likewise
417 * Fortran Compiler::            Likewise
418 * Go Compiler::                 Likewise
420 Writing Tests
422 * Language Choice::             Selecting which language to use for testing
423 * Writing Test Programs::       Forging source files for compilers
424 * Running the Preprocessor::    Detecting preprocessor symbols
425 * Running the Compiler::        Detecting language or header features
426 * Running the Linker::          Detecting library features
427 * Runtime::                     Testing for runtime features
428 * Systemology::                 A zoology of operating systems
429 * Multiple Cases::              Tests for several possible values
431 Writing Test Programs
433 * Guidelines::                  General rules for writing test programs
434 * Test Functions::              Avoiding pitfalls in test programs
435 * Generating Sources::          Source program boilerplate
437 Results of Tests
439 * Defining Symbols::            Defining C preprocessor symbols
440 * Setting Output Variables::    Replacing variables in output files
441 * Special Chars in Variables::  Characters to beware of in variables
442 * Caching Results::             Speeding up subsequent @command{configure} runs
443 * Printing Messages::           Notifying @command{configure} users
445 Caching Results
447 * Cache Variable Names::        Shell variables used in caches
448 * Cache Files::                 Files @command{configure} uses for caching
449 * Cache Checkpointing::         Loading and saving the cache file
451 Programming in M4
453 * M4 Quotation::                Protecting macros from unwanted expansion
454 * Using autom4te::              The Autoconf executables backbone
455 * Programming in M4sugar::      Convenient pure M4 macros
456 * Debugging via autom4te::      Figuring out what M4 was doing
458 M4 Quotation
460 * Active Characters::           Characters that change the behavior of M4
461 * One Macro Call::              Quotation and one macro call
462 * Quoting and Parameters::      M4 vs. shell parameters
463 * Quotation and Nested Macros::  Macros calling macros
464 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
465 * Quadrigraphs::                Another way to escape special characters
466 * Balancing Parentheses::       Dealing with unbalanced parentheses
467 * Quotation Rule Of Thumb::     One parenthesis, one quote
469 Using @command{autom4te}
471 * autom4te Invocation::         A GNU M4 wrapper
472 * Customizing autom4te::        Customizing the Autoconf package
474 Programming in M4sugar
476 * Redefined M4 Macros::         M4 builtins changed in M4sugar
477 * Diagnostic Macros::           Diagnostic messages from M4sugar
478 * Diversion support::           Diversions in M4sugar
479 * Conditional constructs::      Conditions in M4
480 * Looping constructs::          Iteration in M4
481 * Evaluation Macros::           More quotation and evaluation control
482 * Text processing Macros::      String manipulation in M4
483 * Number processing Macros::    Arithmetic computation in M4
484 * Set manipulation Macros::     Set manipulation in M4
485 * Forbidden Patterns::          Catching unexpanded macros
487 Programming in M4sh
489 * Common Shell Constructs::     Portability layer for common shell constructs
490 * Polymorphic Variables::       Support for indirect variable names
491 * Initialization Macros::       Macros to establish a sane shell environment
492 * File Descriptor Macros::      File descriptor macros for input and output
494 Writing Autoconf Macros
496 * Macro Definitions::           Basic format of an Autoconf macro
497 * Macro Names::                 What to call your new macros
498 * Reporting Messages::          Notifying @command{autoconf} users
499 * Dependencies Between Macros::  What to do when macros depend on other macros
500 * Obsoleting Macros::           Warning about old ways of doing things
501 * Coding Style::                Writing Autoconf macros @`a la Autoconf
503 Dependencies Between Macros
505 * Prerequisite Macros::         Ensuring required information
506 * Suggested Ordering::          Warning about possible ordering problems
507 * One-Shot Macros::             Ensuring a macro is called only once
509 Portable Shell Programming
511 * Shellology::                  A zoology of shells
512 * Invoking the Shell::          Invoking the shell as a command
513 * Here-Documents::              Quirks and tricks
514 * File Descriptors::            FDs and redirections
515 * Signal Handling::             Shells, signals, and headaches
516 * File System Conventions::     File names
517 * Shell Pattern Matching::      Pattern matching
518 * Shell Substitutions::         Variable and command expansions
519 * Assignments::                 Varying side effects of assignments
520 * Parentheses::                 Parentheses in shell scripts
521 * Slashes::                     Slashes in shell scripts
522 * Special Shell Variables::     Variables you should not change
523 * Shell Functions::             What to look out for if you use them
524 * Limitations of Builtins::     Portable use of not so portable /bin/sh
525 * Limitations of Usual Tools::  Portable use of portable tools
527 Portable Make Programming
529 * $< in Ordinary Make Rules::   $< in ordinary rules
530 * Failure in Make Rules::       Failing portably in rules
531 * Special Chars in Names::      Special Characters in Macro Names
532 * Backslash-Newline-Empty::     Empty lines after backslash-newline
533 * Backslash-Newline Comments::  Spanning comments across line boundaries
534 * Long Lines in Makefiles::     Line length limitations
535 * Macros and Submakes::         @code{make macro=value} and submakes
536 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
537 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
538 * Parallel Make::               Parallel @command{make} quirks
539 * Comments in Make Rules::      Other problems with Make comments
540 * Newlines in Make Rules::      Using literal newlines in rules
541 * Comments in Make Macros::     Other problems with Make comments in macros
542 * Trailing whitespace in Make Macros::  Macro substitution problems
543 * Command-line Macros and whitespace::  Whitespace trimming of values
544 * obj/ and Make::               Don't name a subdirectory @file{obj}
545 * make -k Status::              Exit status of @samp{make -k}
546 * VPATH and Make::              @code{VPATH} woes
547 * Single Suffix Rules::         Single suffix rules and separated dependencies
548 * Timestamps and Make::         Subsecond timestamp resolution
550 @code{VPATH} and Make
552 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
553 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
554 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
555 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
556 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
557 * Make Target Lookup::          More details about @code{VPATH} lookup
559 Portable C and C++ Programming
561 * Varieties of Unportability::  How to make your programs unportable
562 * Integer Overflow::            When integers get too large
563 * Preprocessor Arithmetic::     @code{#if} expression problems
564 * Null Pointers::               Properties of null pointers
565 * Buffer Overruns::             Subscript errors and the like
566 * Volatile Objects::            @code{volatile} and signals
567 * Floating Point Portability::  Portable floating-point arithmetic
568 * Exiting Portably::            Exiting and the exit status
570 Integer Overflow
572 * Integer Overflow Basics::     Why integer overflow is a problem
573 * Signed Overflow Examples::    Examples of code assuming wraparound
574 * Optimization and Wraparound::  Optimizations that break uses of wraparound
575 * Signed Overflow Advice::      Practical advice for signed overflow issues
576 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
578 Manual Configuration
580 * Specifying Target Triplets::  Specifying target triplets
581 * Canonicalizing::              Getting the canonical system type
582 * Using System Type::           What to do with the system type
584 Site Configuration
586 * Help Formatting::             Customizing @samp{configure --help}
587 * External Software::           Working with other optional software
588 * Package Options::             Selecting optional features
589 * Pretty Help Strings::         Formatting help string
590 * Option Checking::             Controlling checking of @command{configure} options
591 * Site Details::                Configuring site details
592 * Transforming Names::          Changing program names when installing
593 * Site Defaults::               Giving @command{configure} local defaults
595 Transforming Program Names When Installing
597 * Transformation Options::      @command{configure} options to transform names
598 * Transformation Examples::     Sample uses of transforming names
599 * Transformation Rules::        Makefile uses of transforming names
601 Running @command{configure} Scripts
603 * Basic Installation::          Instructions for typical cases
604 * Compilers and Options::       Selecting compilers and optimization
605 * Multiple Architectures::      Compiling for multiple architectures at once
606 * Installation Names::          Installing in different directories
607 * Optional Features::           Selecting optional features
608 * Particular Systems::          Particular systems
609 * System Type::                 Specifying the system type
610 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
611 * Defining Variables::          Specifying the compiler etc.
612 * configure Invocation::        Changing how @command{configure} runs
614 Obsolete Constructs
616 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
617 * acconfig Header::             Additional entries in @file{config.h.in}
618 * autoupdate Invocation::       Automatic update of @file{configure.ac}
619 * Obsolete Macros::             Backward compatibility macros
620 * Autoconf 1::                  Tips for upgrading your files
621 * Autoconf 2.13::               Some fresher tips
623 Upgrading From Version 1
625 * Changed File Names::          Files you might rename
626 * Changed Makefiles::           New things to put in @file{Makefile.in}
627 * Changed Macros::              Macro calls you might replace
628 * Changed Results::             Changes in how to check test results
629 * Changed Macro Writing::       Better ways to write your own macros
631 Upgrading From Version 2.13
633 * Changed Quotation::           Broken code which used to work
634 * New Macros::                  Interaction with foreign macros
635 * Hosts and Cross-Compilation::  Bugward compatibility kludges
636 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
637 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
639 Generating Test Suites with Autotest
641 * Using an Autotest Test Suite::  Autotest and the user
642 * Writing Testsuites::          Autotest macros
643 * testsuite Invocation::        Running @command{testsuite} scripts
644 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
646 Using an Autotest Test Suite
648 * testsuite Scripts::           The concepts of Autotest
649 * Autotest Logs::               Their contents
651 Frequent Autoconf Questions, with answers
653 * Distributing::                Distributing @command{configure} scripts
654 * Why GNU M4::                  Why not use the standard M4?
655 * Bootstrapping::               Autoconf and GNU M4 require each other?
656 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
657 * Defining Directories::        Passing @code{datadir} to program
658 * Autom4te Cache::              What is it?  Can I remove it?
659 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
660 * Expanded Before Required::    Expanded Before Required
661 * Debugging::                   Debugging @command{configure} scripts
663 History of Autoconf
665 * Genesis::                     Prehistory and naming of @command{configure}
666 * Exodus::                      The plagues of M4 and Perl
667 * Leviticus::                   The priestly code of portability arrives
668 * Numbers::                     Growth and contributors
669 * Deuteronomy::                 Approaching the promises of easy configuration
671 Indices
673 * Environment Variable Index::  Index of environment variables used
674 * Output Variable Index::       Index of variables set in output files
675 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
676 * Cache Variable Index::        Index of documented cache variables
677 * Autoconf Macro Index::        Index of Autoconf macros
678 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
679 * Autotest Macro Index::        Index of Autotest macros
680 * Program & Function Index::    Index of those with portability problems
681 * Concept Index::               General index
683 @end detailmenu
684 @end menu
686 @c ============================================================= Introduction.
688 @node Introduction
689 @chapter Introduction
690 @cindex Introduction
692 @flushright
693 A physicist, an engineer, and a computer scientist were discussing the
694 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
695 early in the Creation, God made Light; and you know, Maxwell's
696 equations, the dual nature of electromagnetic waves, the relativistic
697 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
698 before making Light, God split the Chaos into Land and Water; it takes a
699 hell of an engineer to handle that big amount of mud, and orderly
700 separation of solids from liquids@enddots{}'' The computer scientist
701 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
703 ---Anonymous
704 @end flushright
705 @c (via Franc,ois Pinard)
707 Autoconf is a tool for producing shell scripts that automatically
708 configure software source code packages to adapt to many kinds of
709 Posix-like systems.  The configuration scripts produced by Autoconf
710 are independent of Autoconf when they are run, so their users do not
711 need to have Autoconf.
713 The configuration scripts produced by Autoconf require no manual user
714 intervention when run; they do not normally even need an argument
715 specifying the system type.  Instead, they individually test for the
716 presence of each feature that the software package they are for might need.
717 (Before each check, they print a one-line message stating what they are
718 checking for, so the user doesn't get too bored while waiting for the
719 script to finish.)  As a result, they deal well with systems that are
720 hybrids or customized from the more common Posix variants.  There is
721 no need to maintain files that list the features supported by each
722 release of each variant of Posix.
724 For each software package that Autoconf is used with, it creates a
725 configuration script from a template file that lists the system features
726 that the package needs or can use.  After the shell code to recognize
727 and respond to a system feature has been written, Autoconf allows it to
728 be shared by many software packages that can use (or need) that feature.
729 If it later turns out that the shell code needs adjustment for some
730 reason, it needs to be changed in only one place; all of the
731 configuration scripts can be regenerated automatically to take advantage
732 of the updated code.
734 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
735 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
736 Those who do not understand Autoconf are condemned to reinvent it, poorly.
737 The primary goal of Autoconf is making the @emph{user's} life easier;
738 making the @emph{maintainer's} life easier is only a secondary goal.
739 Put another way, the primary goal is not to make the generation of
740 @file{configure} automatic for package maintainers (although patches
741 along that front are welcome, since package maintainers form the user
742 base of Autoconf); rather, the goal is to make @file{configure}
743 painless, portable, and predictable for the end user of each
744 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
745 successful at its goal --- most complaints to the Autoconf list are
746 about difficulties in writing Autoconf input, and not in the behavior of
747 the resulting @file{configure}.  Even packages that don't use Autoconf
748 will generally provide a @file{configure} script, and the most common
749 complaint about these alternative home-grown scripts is that they fail
750 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
751 standards, The GNU Coding Standards}) that users
752 have come to expect from Autoconf-generated @file{configure} scripts.
754 The Metaconfig package is similar in purpose to Autoconf, but the
755 scripts it produces require manual user intervention, which is quite
756 inconvenient when configuring large source trees.  Unlike Metaconfig
757 scripts, Autoconf scripts can support cross-compiling, if some care is
758 taken in writing them.
760 Autoconf does not solve all problems related to making portable
761 software packages---for a more complete solution, it should be used in
762 concert with other GNU build tools like Automake and
763 Libtool.  These other tools take on jobs like the creation of a
764 portable, recursive makefile with all of the standard targets,
765 linking of shared libraries, and so on.  @xref{The GNU Build System},
766 for more information.
768 Autoconf imposes some restrictions on the names of macros used with
769 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
771 Autoconf requires GNU M4 version 1.4.6 or later in order to
772 generate the scripts.  It uses features that some versions of M4,
773 including GNU M4 1.3, do not have.  Autoconf works better
774 with GNU M4 version 1.4.14 or later, though this is not
775 required.
777 @xref{Autoconf 1}, for information about upgrading from version 1.
778 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
779 for answers to some common questions about Autoconf.
781 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
782 Autoconf web page} for up-to-date information, details on the mailing
783 lists, pointers to a list of known bugs, etc.
785 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
786 list}.  Past suggestions are
787 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
789 Mail bug reports to @email{bug-autoconf@@gnu.org, the
790 Autoconf Bugs mailing list}.  Past bug reports are
791 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
793 If possible, first check that your bug is
794 not already solved in current development versions, and that it has not
795 been reported yet.  Be sure to include all the needed information and a
796 short @file{configure.ac} that demonstrates the problem.
798 Autoconf's development tree is accessible via @command{git}; see the
799 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
800 Summary} for details, or view
801 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
802 repository}.  Anonymous CVS access is also available, see
803 @file{README} for more details.  Patches relative to the
804 current @command{git} version can be sent for review to the
805 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
806 discussion on prior patches
807 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
808 archived}; and all commits are posted in the read-only
809 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
810 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
811 archived}.
813 Because of its mission, the Autoconf package itself
814 includes only a set of often-used
815 macros that have already demonstrated their usefulness.  Nevertheless,
816 if you wish to share your macros, or find existing ones, see the
817 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
818 Archive}, which is kindly run by @email{simons@@cryp.to,
819 Peter Simons}.
822 @c ================================================= The GNU Build System
824 @node The GNU Build System
825 @chapter The GNU Build System
826 @cindex GNU build system
828 Autoconf solves an important problem---reliable discovery of
829 system-specific build and runtime information---but this is only one
830 piece of the puzzle for the development of portable software.  To this
831 end, the GNU project has developed a suite of integrated
832 utilities to finish the job Autoconf started: the GNU build
833 system, whose most important components are Autoconf, Automake, and
834 Libtool.  In this chapter, we introduce you to those tools, point you
835 to sources of more information, and try to convince you to use the
836 entire GNU build system for your software.
838 @menu
839 * Automake::                    Escaping makefile hell
840 * Gnulib::                      The GNU portability library
841 * Libtool::                     Building libraries portably
842 * Pointers::                    More info on the GNU build system
843 @end menu
845 @node Automake
846 @section Automake
848 The ubiquity of @command{make} means that a makefile is almost the
849 only viable way to distribute automatic build rules for software, but
850 one quickly runs into its numerous limitations.  Its lack of
851 support for automatic dependency tracking, recursive builds in
852 subdirectories, reliable timestamps (e.g., for network file systems), and
853 so on, mean that developers must painfully (and often incorrectly)
854 reinvent the wheel for each project.  Portability is non-trivial, thanks
855 to the quirks of @command{make} on many systems.  On top of all this is the
856 manual labor required to implement the many standard targets that users
857 have come to expect (@code{make install}, @code{make distclean},
858 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
859 you also have to insert repetitive code in your @file{Makefile.in} to
860 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
861 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
862 @cindex Automake
864 Automake allows you to specify your build needs in a @file{Makefile.am}
865 file with a vastly simpler and more powerful syntax than that of a plain
866 makefile, and then generates a portable @file{Makefile.in} for
867 use with Autoconf.  For example, the @file{Makefile.am} to build and
868 install a simple ``Hello world'' program might look like:
870 @example
871 bin_PROGRAMS = hello
872 hello_SOURCES = hello.c
873 @end example
875 @noindent
876 The resulting @file{Makefile.in} (~400 lines) automatically supports all
877 the standard targets, the substitutions provided by Autoconf, automatic
878 dependency tracking, @code{VPATH} building, and so on.  @command{make}
879 builds the @code{hello} program, and @code{make install} installs it
880 in @file{/usr/local/bin} (or whatever prefix was given to
881 @command{configure}, if not @file{/usr/local}).
883 The benefits of Automake increase for larger packages (especially ones
884 with subdirectories), but even for small programs the added convenience
885 and portability can be substantial.  And that's not all@enddots{}
887 @node Gnulib
888 @section Gnulib
890 GNU software has a well-deserved reputation for running on
891 many different types of systems.  While our primary goal is to write
892 software for the GNU system, many users and developers have
893 been introduced to us through the systems that they were already using.
895 @cindex Gnulib
896 Gnulib is a central location for common GNU code, intended to
897 be shared among free software packages.  Its components are typically
898 shared at the source level, rather than being a library that gets built,
899 installed, and linked against.  The idea is to copy files from Gnulib
900 into your own source tree.  There is no distribution tarball; developers
901 should just grab source modules from the repository.  The source files
902 are available online, under various licenses, mostly GNU
903 GPL or GNU LGPL.
905 Gnulib modules typically contain C source code along with Autoconf
906 macros used to configure the source code.  For example, the Gnulib
907 @code{stdalign} module implements a @file{stdalign.h} header that nearly
908 conforms to C11, even on old-fashioned hosts that lack @file{stdalign.h}.
909 This module contains a source file for the replacement header, along
910 with an Autoconf macro that arranges to use the replacement header on
911 old-fashioned systems.
913 @node Libtool
914 @section Libtool
916 Often, one wants to build not only programs, but libraries, so that
917 other programs can benefit from the fruits of your labor.  Ideally, one
918 would like to produce @emph{shared} (dynamically linked) libraries,
919 which can be used by multiple programs without duplication on disk or in
920 memory and can be updated independently of the linked programs.
921 Producing shared libraries portably, however, is the stuff of
922 nightmares---each system has its own incompatible tools, compiler flags,
923 and magic incantations.  Fortunately, GNU provides a solution:
924 @dfn{Libtool}.
925 @cindex Libtool
927 Libtool handles all the requirements of building shared libraries for
928 you, and at this time seems to be the @emph{only} way to do so with any
929 portability.  It also handles many other headaches, such as: the
930 interaction of Make rules with the variable suffixes of
931 shared libraries, linking reliably with shared libraries before they are
932 installed by the superuser, and supplying a consistent versioning system
933 (so that different versions of a library can be installed or upgraded
934 without breaking binary compatibility).  Although Libtool, like
935 Autoconf, can be used without Automake, it is most simply utilized in
936 conjunction with Automake---there, Libtool is used automatically
937 whenever shared libraries are needed, and you need not know its syntax.
939 @node Pointers
940 @section Pointers
942 Developers who are used to the simplicity of @command{make} for small
943 projects on a single system might be daunted at the prospect of
944 learning to use Automake and Autoconf.  As your software is
945 distributed to more and more users, however, you otherwise
946 quickly find yourself putting lots of effort into reinventing the
947 services that the GNU build tools provide, and making the
948 same mistakes that they once made and overcame.  (Besides, since
949 you're already learning Autoconf, Automake is a piece of cake.)
951 There are a number of places that you can go to for more information on
952 the GNU build tools.
954 @itemize @minus
956 @item Web
958 The project home pages for
959 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
960 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
961 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
962 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
964 @item Automake Manual
966 @xref{Top, , Automake, automake, GNU Automake}, for more
967 information on Automake.
969 @item Books
971 The book @cite{GNU Autoconf, Automake and
972 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
973 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
974 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
975 build environment.  You can also find
976 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
978 @end itemize
980 @c ================================================= Making configure Scripts.
982 @node Making configure Scripts
983 @chapter Making @command{configure} Scripts
984 @cindex @file{aclocal.m4}
985 @cindex @command{configure}
987 The configuration scripts that Autoconf produces are by convention
988 called @command{configure}.  When run, @command{configure} creates several
989 files, replacing configuration parameters in them with appropriate
990 values.  The files that @command{configure} creates are:
992 @itemize @minus
993 @item
994 one or more @file{Makefile} files, usually one in each subdirectory of the
995 package (@pxref{Makefile Substitutions});
997 @item
998 optionally, a C header file, the name of which is configurable,
999 containing @code{#define} directives (@pxref{Configuration Headers});
1001 @item
1002 a shell script called @file{config.status} that, when run, recreates
1003 the files listed above (@pxref{config.status Invocation});
1005 @item
1006 an optional shell script normally called @file{config.cache}
1007 (created when using @samp{configure --config-cache}) that
1008 saves the results of running many of the tests (@pxref{Cache Files});
1010 @item
1011 a file called @file{config.log} containing any messages produced by
1012 compilers, to help debugging if @command{configure} makes a mistake.
1013 @end itemize
1015 @cindex @file{configure.ac}
1016 To create a @command{configure} script with Autoconf, you need
1017 to write an Autoconf input file @file{configure.ac} and run
1018 @command{autoconf} on it.  If you write your own feature tests to
1019 supplement those that come with Autoconf, you might also write files
1020 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1021 file to contain @code{#define} directives, you might also run
1022 @command{autoheader}, and you can distribute the generated file
1023 @file{config.h.in} with the package.
1025 Here is a diagram showing how the files that can be used in
1026 configuration are produced.  Programs that are executed are suffixed by
1027 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1028 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1029 macro files (by reading @file{autoconf.m4}).
1031 @noindent
1032 Files used in preparing a software package for distribution, when using
1033 just Autoconf:
1034 @example
1035 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1037 @group
1038 configure.ac --.
1039                |   .------> autoconf* -----> configure
1040 [aclocal.m4] --+---+
1041                |   `-----> [autoheader*] --> [config.h.in]
1042 [acsite.m4] ---'
1043 @end group
1045 Makefile.in
1046 @end example
1048 @noindent
1049 Additionally, if you use Automake, the following additional productions
1050 come into play:
1052 @example
1053 @group
1054 [acinclude.m4] --.
1055                  |
1056 [local macros] --+--> aclocal* --> aclocal.m4
1057                  |
1058 configure.ac ----'
1059 @end group
1061 @group
1062 configure.ac --.
1063                +--> automake* --> Makefile.in
1064 Makefile.am ---'
1065 @end group
1066 @end example
1068 @noindent
1069 Files used in configuring a software package:
1070 @example
1071 @group
1072                        .-------------> [config.cache]
1073 configure* ------------+-------------> config.log
1074                        |
1075 [config.h.in] -.       v            .-> [config.h] -.
1076                +--> config.status* -+               +--> make*
1077 Makefile.in ---'                    `-> Makefile ---'
1078 @end group
1079 @end example
1081 @menu
1082 * Writing Autoconf Input::      What to put in an Autoconf input file
1083 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1084 * ifnames Invocation::          Listing the conditionals in source code
1085 * autoconf Invocation::         How to create configuration scripts
1086 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1087 @end menu
1089 @node Writing Autoconf Input
1090 @section Writing @file{configure.ac}
1092 To produce a @command{configure} script for a software package, create a
1093 file called @file{configure.ac} that contains invocations of the
1094 Autoconf macros that test the system features your package needs or can
1095 use.  Autoconf macros already exist to check for many features; see
1096 @ref{Existing Tests}, for their descriptions.  For most other features,
1097 you can use Autoconf template macros to produce custom checks; see
1098 @ref{Writing Tests}, for information about them.  For especially tricky
1099 or specialized features, @file{configure.ac} might need to contain some
1100 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1101 Programming}.  The @command{autoscan} program can give you a good start
1102 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1103 information).
1105 @cindex @file{configure.in}
1106 Previous versions of Autoconf promoted the name @file{configure.in},
1107 which is somewhat ambiguous (the tool needed to process this file is not
1108 described by its extension), and introduces a slight confusion with
1109 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1110 processed by @command{configure}'').  Using @file{configure.ac} is now
1111 preferred, while the use of @file{configure.in} will cause warnings
1112 from @command{autoconf}.
1114 @menu
1115 * Shell Script Compiler::       Autoconf as solution of a problem
1116 * Autoconf Language::           Programming in Autoconf
1117 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1118 @end menu
1120 @node Shell Script Compiler
1121 @subsection A Shell Script Compiler
1123 Just as for any other computer language, in order to properly program
1124 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1125 the language tries to address and @emph{how} it does so.
1127 The problem Autoconf addresses is that the world is a mess.  After all,
1128 you are using Autoconf in order to have your package compile easily on
1129 all sorts of different systems, some of them being extremely hostile.
1130 Autoconf itself bears the price for these differences: @command{configure}
1131 must run on all those systems, and thus @command{configure} must limit itself
1132 to their lowest common denominator of features.
1134 Naturally, you might then think of shell scripts; who needs
1135 @command{autoconf}?  A set of properly written shell functions is enough to
1136 make it easy to write @command{configure} scripts by hand.  Sigh!
1137 Unfortunately, even in 2008, where shells without any function support are
1138 far and few between, there are pitfalls to avoid when making use of them.
1139 Also, finding a Bourne shell that accepts shell functions is not trivial,
1140 even though there is almost always one on interesting porting targets.
1142 So, what is really needed is some kind of compiler, @command{autoconf},
1143 that takes an Autoconf program, @file{configure.ac}, and transforms it
1144 into a portable shell script, @command{configure}.
1146 How does @command{autoconf} perform this task?
1148 There are two obvious possibilities: creating a brand new language or
1149 extending an existing one.  The former option is attractive: all
1150 sorts of optimizations could easily be implemented in the compiler and
1151 many rigorous checks could be performed on the Autoconf program
1152 (e.g., rejecting any non-portable construct).  Alternatively, you can
1153 extend an existing language, such as the @code{sh} (Bourne shell)
1154 language.
1156 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1157 therefore most convenient to implement @command{autoconf} as a macro
1158 expander: a program that repeatedly performs @dfn{macro expansions} on
1159 text input, replacing macro calls with macro bodies and producing a pure
1160 @code{sh} script in the end.  Instead of implementing a dedicated
1161 Autoconf macro expander, it is natural to use an existing
1162 general-purpose macro language, such as M4, and implement the extensions
1163 as a set of M4 macros.
1166 @node Autoconf Language
1167 @subsection The Autoconf Language
1168 @cindex quotation
1170 The Autoconf language differs from many other computer
1171 languages because it treats actual code the same as plain text.  Whereas
1172 in C, for instance, data and instructions have different syntactic
1173 status, in Autoconf their status is rigorously the same.  Therefore, we
1174 need a means to distinguish literal strings from text to be expanded:
1175 quotation.
1177 When calling macros that take arguments, there must not be any white
1178 space between the macro name and the open parenthesis.
1180 @example
1181 AC_INIT ([oops], [1.0]) # incorrect
1182 AC_INIT([hello], [1.0]) # good
1183 @end example
1185 Arguments should
1186 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1187 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1188 unless they are quoted.  You should always quote an argument that
1189 might contain a macro name, comma, parenthesis, or a leading blank or
1190 newline.  This rule applies recursively for every macro
1191 call, including macros called from other macros.  For more details on
1192 quoting rules, see @ref{Programming in M4}.
1194 For instance:
1196 @example
1197 AC_CHECK_HEADER([stdio.h],
1198                 [AC_DEFINE([HAVE_STDIO_H], [1],
1199                    [Define to 1 if you have <stdio.h>.])],
1200                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1201 @end example
1203 @noindent
1204 is quoted properly.  You may safely simplify its quotation to:
1206 @example
1207 AC_CHECK_HEADER([stdio.h],
1208                 [AC_DEFINE([HAVE_STDIO_H], 1,
1209                    [Define to 1 if you have <stdio.h>.])],
1210                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1211 @end example
1213 @noindent
1214 because @samp{1} cannot contain a macro call.  Here, the argument of
1215 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1216 interpreted as an argument separator.  Also, the second and third arguments
1217 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1218 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1219 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1220 if you unwisely defined a macro with a name like @samp{Define} or
1221 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1222 would keep the quotes, but many Autoconf users find such precautions
1223 annoying, and would rewrite the example as follows:
1225 @example
1226 AC_CHECK_HEADER(stdio.h,
1227                 [AC_DEFINE(HAVE_STDIO_H, 1,
1228                    [Define to 1 if you have <stdio.h>.])],
1229                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1230 @end example
1232 @noindent
1233 This is safe, so long as you adopt good naming conventions and do not
1234 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1235 @samp{h}.  Though it is also safe here to omit the quotes around
1236 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1237 message strings are more likely to inadvertently contain commas.
1239 The following example is wrong and dangerous, as it is underquoted:
1241 @example
1242 AC_CHECK_HEADER(stdio.h,
1243                 AC_DEFINE(HAVE_STDIO_H, 1,
1244                    Define to 1 if you have <stdio.h>.),
1245                 AC_MSG_ERROR([sorry, can't do anything for you]))
1246 @end example
1248 In other cases, you may have to use text that also resembles a macro
1249 call.  You must quote that text even when it is not passed as a macro
1250 argument.  For example, these two approaches in @file{configure.ac}
1251 (quoting just the potential problems, or quoting the entire line) will
1252 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1254 @example
1255 echo "Hard rock was here!  --[AC_DC]"
1256 [echo "Hard rock was here!  --AC_DC"]
1257 @end example
1259 @noindent
1260 which results in this text in @file{configure}:
1262 @example
1263 echo "Hard rock was here!  --AC_DC"
1264 echo "Hard rock was here!  --AC_DC"
1265 @end example
1267 @noindent
1268 When you use the same text in a macro argument, you must therefore have
1269 an extra quotation level (since one is stripped away by the macro
1270 substitution).  In general, then, it is a good idea to @emph{use double
1271 quoting for all literal string arguments}, either around just the
1272 problematic portions, or over the entire argument:
1274 @example
1275 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1276 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1277 @end example
1279 However, the above example triggers a warning about a possibly
1280 unexpanded macro when running @command{autoconf}, because it collides
1281 with the namespace of macros reserved for the Autoconf language.  To be
1282 really safe, you can use additional escaping (either a quadrigraph, or
1283 creative shell constructs) to silence that particular warning:
1285 @example
1286 echo "Hard rock was here!  --AC""_DC"
1287 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1288 @end example
1290 You are now able to understand one of the constructs of Autoconf that
1291 has been continually misunderstood@enddots{}  The rule of thumb is that
1292 @emph{whenever you expect macro expansion, expect quote expansion};
1293 i.e., expect one level of quotes to be lost.  For instance:
1295 @example
1296 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1297  [AC_MSG_ERROR([you lose])])
1298 @end example
1300 @noindent
1301 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1302 @samp{char b[10];} and is expanded once, which results in
1303 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1304 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1305 in Autoconf's past to
1306 address this issue via the M4 @code{changequote} primitive, but do not
1307 use it!)  Let's take a closer look: the author meant the first argument
1308 to be understood as a literal, and therefore it must be quoted twice;
1309 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1310 once so that it is only expanded after the rest of the body of
1311 @code{AC_COMPILE_IFELSE} is in place:
1313 @example
1314 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1315   [AC_MSG_ERROR([you lose])])
1316 @end example
1318 @noindent
1319 Voil@`a, you actually produce @samp{char b[10];} this time!
1321 On the other hand, descriptions (e.g., the last parameter of
1322 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1323 are subject to line breaking, for example---and should not be double quoted.
1324 Even if these descriptions are short and are not actually broken, double
1325 quoting them yields weird results.
1327 Some macros take optional arguments, which this documentation represents
1328 as @ovar{arg} (not to be confused with the quote characters).  You may
1329 just leave them empty, or use @samp{[]} to make the emptiness of the
1330 argument explicit, or you may simply omit the trailing commas.  The
1331 three lines below are equivalent:
1333 @example
1334 AC_CHECK_HEADERS([stdio.h], [], [], [])
1335 AC_CHECK_HEADERS([stdio.h],,,)
1336 AC_CHECK_HEADERS([stdio.h])
1337 @end example
1339 It is best to put each macro call on its own line in
1340 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1341 rely on the newline after the macro call to terminate the commands.
1342 This approach makes the generated @command{configure} script a little
1343 easier to read by not inserting lots of blank lines.  It is generally
1344 safe to set shell variables on the same line as a macro call, because
1345 the shell allows assignments without intervening newlines.
1347 You can include comments in @file{configure.ac} files by starting them
1348 with the @samp{#}.  For example, it is helpful to begin
1349 @file{configure.ac} files with a line like this:
1351 @example
1352 # Process this file with autoconf to produce a configure script.
1353 @end example
1355 @node Autoconf Input Layout
1356 @subsection Standard @file{configure.ac} Layout
1358 The order in which @file{configure.ac} calls the Autoconf macros is not
1359 important, with a few exceptions.  Every @file{configure.ac} must
1360 contain a call to @code{AC_INIT} before the checks, and a call to
1361 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1362 rely on other macros having been called first, because they check
1363 previously set values of some variables to decide what to do.  These
1364 macros are noted in the individual descriptions (@pxref{Existing
1365 Tests}), and they also warn you when @command{configure} is created if they
1366 are called out of order.
1368 To encourage consistency, here is a suggested order for calling the
1369 Autoconf macros.  Generally speaking, the things near the end of this
1370 list are those that could depend on things earlier in it.  For example,
1371 library functions could be affected by types and libraries.
1373 @display
1374 @group
1375 Autoconf requirements
1376 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1377 information on the package
1378 checks for programs
1379 checks for libraries
1380 checks for header files
1381 checks for types
1382 checks for structures
1383 checks for compiler characteristics
1384 checks for library functions
1385 checks for system services
1386 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1387 @code{AC_OUTPUT}
1388 @end group
1389 @end display
1392 @node autoscan Invocation
1393 @section Using @command{autoscan} to Create @file{configure.ac}
1394 @cindex @command{autoscan}
1396 The @command{autoscan} program can help you create and/or maintain a
1397 @file{configure.ac} file for a software package.  @command{autoscan}
1398 examines source files in the directory tree rooted at a directory given
1399 as a command line argument, or the current directory if none is given.
1400 It searches the source files for common portability problems and creates
1401 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1402 for that package, and checks a possibly existing @file{configure.ac} for
1403 completeness.
1405 When using @command{autoscan} to create a @file{configure.ac}, you
1406 should manually examine @file{configure.scan} before renaming it to
1407 @file{configure.ac}; it probably needs some adjustments.
1408 Occasionally, @command{autoscan} outputs a macro in the wrong order
1409 relative to another macro, so that @command{autoconf} produces a warning;
1410 you need to move such macros manually.  Also, if you want the package to
1411 use a configuration header file, you must add a call to
1412 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1413 also have to change or add some @code{#if} directives to your program in
1414 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1415 information about a program that can help with that job).
1417 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1418 consider adding its suggestions.  The file @file{autoscan.log}
1419 contains detailed information on why a macro is requested.
1421 @command{autoscan} uses several data files (installed along with Autoconf)
1422 to determine which macros to output when it finds particular symbols in
1423 a package's source files.  These data files all have the same format:
1424 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1425 output if that symbol is encountered.  Lines starting with @samp{#} are
1426 comments.
1428 @command{autoscan} accepts the following options:
1430 @table @option
1431 @item --help
1432 @itemx -h
1433 Print a summary of the command line options and exit.
1435 @item --version
1436 @itemx -V
1437 Print the version number of Autoconf and exit.
1439 @item --verbose
1440 @itemx -v
1441 Print the names of the files it examines and the potentially interesting
1442 symbols it finds in them.  This output can be voluminous.
1444 @item --debug
1445 @itemx -d
1446 Don't remove temporary files.
1448 @item --include=@var{dir}
1449 @itemx -I @var{dir}
1450 Append @var{dir} to the include path.  Multiple invocations accumulate.
1452 @item --prepend-include=@var{dir}
1453 @itemx -B @var{dir}
1454 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1455 @end table
1457 @node ifnames Invocation
1458 @section Using @command{ifnames} to List Conditionals
1459 @cindex @command{ifnames}
1461 @command{ifnames} can help you write @file{configure.ac} for a software
1462 package.  It prints the identifiers that the package already uses in C
1463 preprocessor conditionals.  If a package has already been set up to have
1464 some portability, @command{ifnames} can thus help you figure out what its
1465 @command{configure} needs to check for.  It may help fill in some gaps in a
1466 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1467 Invocation}).
1469 @command{ifnames} scans all of the C source files named on the command line
1470 (or the standard input, if none are given) and writes to the standard
1471 output a sorted list of all the identifiers that appear in those files
1472 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1473 directives.  It prints each identifier on a line, followed by a
1474 space-separated list of the files in which that identifier occurs.
1476 @noindent
1477 @command{ifnames} accepts the following options:
1479 @table @option
1480 @item --help
1481 @itemx -h
1482 Print a summary of the command line options and exit.
1484 @item --version
1485 @itemx -V
1486 Print the version number of Autoconf and exit.
1487 @end table
1489 @node autoconf Invocation
1490 @section Using @command{autoconf} to Create @command{configure}
1491 @cindex @command{autoconf}
1493 To create @command{configure} from @file{configure.ac}, run the
1494 @command{autoconf} program with no arguments.  @command{autoconf} processes
1495 @file{configure.ac} with the M4 macro processor, using the
1496 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1497 file instead of @file{configure.ac} and writes the configuration script
1498 to the standard output instead of to @command{configure}.  If you give
1499 @command{autoconf} the argument @option{-}, it reads from the standard
1500 input instead of @file{configure.ac} and writes the configuration script
1501 to the standard output.
1503 The Autoconf macros are defined in several files.  Some of the files are
1504 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1505 looks for the optional file @file{acsite.m4} in the directory that
1506 contains the distributed Autoconf macro files, and for the optional file
1507 @file{aclocal.m4} in the current directory.  Those files can contain
1508 your site's or the package's own Autoconf macro definitions
1509 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1510 defined in more than one of the files that @command{autoconf} reads, the
1511 last definition it reads overrides the earlier ones.
1513 @command{autoconf} accepts the following options:
1515 @table @option
1516 @item --help
1517 @itemx -h
1518 Print a summary of the command line options and exit.
1520 @item --version
1521 @itemx -V
1522 Print the version number of Autoconf and exit.
1524 @item --verbose
1525 @itemx -v
1526 Report processing steps.
1528 @item --debug
1529 @itemx -d
1530 Don't remove the temporary files.
1532 @item --force
1533 @itemx -f
1534 Remake @file{configure} even if newer than its input files.
1536 @item --include=@var{dir}
1537 @itemx -I @var{dir}
1538 Append @var{dir} to the include path.  Multiple invocations accumulate.
1540 @item --prepend-include=@var{dir}
1541 @itemx -B @var{dir}
1542 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1544 @item --output=@var{file}
1545 @itemx -o @var{file}
1546 Save output (script or trace) to @var{file}.  The file @option{-} stands
1547 for the standard output.
1549 @item --warnings=@var{category}
1550 @itemx -W @var{category}
1551 @evindex WARNINGS
1552 Report the warnings related to @var{category} (which can actually be a
1553 comma separated list).  @xref{Reporting Messages}, macro
1554 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1555 values include:
1557 @table @samp
1558 @item all
1559 report all the warnings
1561 @item none
1562 report none
1564 @item error
1565 treats warnings as errors
1567 @item no-@var{category}
1568 disable warnings falling into @var{category}
1569 @end table
1571 Warnings about @samp{syntax} are enabled by default, and the environment
1572 variable @env{WARNINGS}, a comma separated list of categories, is
1573 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1574 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1575 disable the defaults and @env{WARNINGS}, and then
1576 enable warnings about obsolete constructs, use @option{-W
1577 none,obsolete}.
1579 @cindex Back trace
1580 @cindex Macro invocation stack
1581 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1582 displays a back trace for errors, but not for warnings; if you want
1583 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1584 examples.
1586 @item --trace=@var{macro}[:@var{format}]
1587 @itemx -t @var{macro}[:@var{format}]
1588 Do not create the @command{configure} script, but list the calls to
1589 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1590 arguments can be used to list several macros.  Multiple @option{--trace}
1591 arguments for a single macro are not cumulative; instead, you should
1592 just make @var{format} as long as needed.
1594 The @var{format} is a regular string, with newlines if desired, and
1595 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1596 @ref{autom4te Invocation}, for details on the @var{format}.
1598 @item --initialization
1599 @itemx -i
1600 By default, @option{--trace} does not trace the initialization of the
1601 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1602 results in a noticeable speedup, but can be disabled by this option.
1603 @end table
1606 It is often necessary to check the content of a @file{configure.ac}
1607 file, but parsing it yourself is extremely fragile and error-prone.  It
1608 is suggested that you rely upon @option{--trace} to scan
1609 @file{configure.ac}.  For instance, to find the list of variables that
1610 are substituted, use:
1612 @example
1613 @group
1614 $ @kbd{autoconf -t AC_SUBST}
1615 configure.ac:2:AC_SUBST:ECHO_C
1616 configure.ac:2:AC_SUBST:ECHO_N
1617 configure.ac:2:AC_SUBST:ECHO_T
1618 @i{More traces deleted}
1619 @end group
1620 @end example
1622 @noindent
1623 The example below highlights the difference between @samp{$@@},
1624 @samp{$*}, and @samp{$%}.
1626 @example
1627 @group
1628 $ @kbd{cat configure.ac}
1629 AC_DEFINE(This, is, [an
1630 [example]])
1631 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1632 *: $*
1633 %: $%'
1634 @@: [This],[is],[an
1635 [example]]
1636 *: This,is,an
1637 [example]
1638 %: This:is:an [example]
1639 @end group
1640 @end example
1642 @noindent
1643 The @var{format} gives you a lot of freedom:
1645 @example
1646 @group
1647 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1648 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1649 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1650 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1651 @i{More traces deleted}
1652 @end group
1653 @end example
1655 @noindent
1656 A long @var{separator} can be used to improve the readability of complex
1657 structures, and to ease their parsing (for instance when no single
1658 character is suitable as a separator):
1660 @example
1661 @group
1662 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1663 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1664 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1665 AUTOMAKE|:::::|automake|:::::|$missing_dir
1666 @i{More traces deleted}
1667 @end group
1668 @end example
1670 @node autoreconf Invocation
1671 @section Using @command{autoreconf} to Update @command{configure} Scripts
1672 @cindex @command{autoreconf}
1674 Installing the various components of the GNU Build System can be
1675 tedious: running @command{autopoint} for Gettext, @command{automake} for
1676 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1677 because some tools such as @command{automake} have been updated on your
1678 system, or because some of the sources such as @file{configure.ac} have
1679 been updated, or finally, simply in order to install the GNU Build
1680 System in a fresh tree.
1682 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1683 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1684 @command{autopoint} (when appropriate) repeatedly to update the
1685 GNU Build System in the specified directories and their
1686 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1687 those files that are older than their sources.  The environment variables
1688 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1689 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1690 may be used to override the invocation of the respective tools.
1692 If you install a new version of some tool, you can make
1693 @command{autoreconf} remake @emph{all} of the files by giving it the
1694 @option{--force} option.
1696 @xref{Automatic Remaking}, for Make rules to automatically
1697 rebuild @command{configure} scripts when their source files change.  That
1698 method handles the timestamps of configuration header templates
1699 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1700 @option{--localdir=@var{dir}}.
1702 @cindex Gettext
1703 @cindex @command{autopoint}
1704 Gettext supplies the @command{autopoint} command to add translation
1705 infrastructure to a source package.  If you use @command{autopoint},
1706 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1707 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1708 Invocation, , Invoking the @code{autopoint} Program, gettext,
1709 GNU @code{gettext} utilities}, for further details.
1711 @noindent
1712 @command{autoreconf} accepts the following options:
1714 @table @option
1715 @item --help
1716 @itemx -h
1717 Print a summary of the command line options and exit.
1719 @item --version
1720 @itemx -V
1721 Print the version number of Autoconf and exit.
1723 @item --verbose
1724 @itemx -v
1725 Print the name of each directory @command{autoreconf} examines and the
1726 commands it runs.  If given two or more times, pass @option{--verbose}
1727 to subordinate tools that support it.
1729 @item --debug
1730 @itemx -d
1731 Don't remove the temporary files.
1733 @item --force
1734 @itemx -f
1735 Remake even @file{configure} scripts and configuration headers that are
1736 newer than their input files (@file{configure.ac} and, if present,
1737 @file{aclocal.m4}).
1739 @item --install
1740 @itemx -i
1741 Install the missing auxiliary files in the package.  By default, files
1742 are copied; this can be changed with @option{--symlink}.
1744 If deemed appropriate, this option triggers calls to
1745 @samp{automake --add-missing},
1746 @samp{libtoolize}, @samp{autopoint}, etc.
1748 @item --no-recursive
1749 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1750 macro @code{AC_CONFIG_SUBDIRS}).
1752 @item --symlink
1753 @itemx -s
1754 When used with @option{--install}, install symbolic links to the missing
1755 auxiliary files instead of copying them.
1757 @item --make
1758 @itemx -m
1759 When the directories were configured, update the configuration by
1760 running @samp{./config.status --recheck && ./config.status}, and then
1761 run @samp{make}.
1763 @item --include=@var{dir}
1764 @itemx -I @var{dir}
1765 Append @var{dir} to the include path.  Multiple invocations accumulate.
1766 Passed on to @command{aclocal}, @command{autoconf} and
1767 @command{autoheader} internally.
1769 @item --prepend-include=@var{dir}
1770 @itemx -B @var{dir}
1771 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1772 Passed on to @command{autoconf} and @command{autoheader} internally.
1774 @item --warnings=@var{category}
1775 @itemx -W @var{category}
1776 @evindex WARNINGS
1777 Report the warnings related to @var{category} (which can actually be a
1778 comma separated list).
1780 @table @samp
1781 @item cross
1782 related to cross compilation issues.
1784 @item obsolete
1785 report the uses of obsolete constructs.
1787 @item portability
1788 portability issues
1790 @item syntax
1791 dubious syntactic constructs.
1793 @item all
1794 report all the warnings
1796 @item none
1797 report none
1799 @item error
1800 treats warnings as errors
1802 @item no-@var{category}
1803 disable warnings falling into @var{category}
1804 @end table
1806 Warnings about @samp{syntax} are enabled by default, and the environment
1807 variable @env{WARNINGS}, a comma separated list of categories, is
1808 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1809 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1810 disable the defaults and @env{WARNINGS}, and then
1811 enable warnings about obsolete constructs, use @option{-W
1812 none,obsolete}.
1813 @end table
1815 If you want @command{autoreconf} to pass flags that are not listed here
1816 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1817 Due to a limitation in the Autoconf implementation these flags currently
1818 must be set on a single line in @file{Makefile.am}, without any
1819 backslash-newlines.
1821 @c ========================================= Initialization and Output Files.
1823 @node Setup
1824 @chapter Initialization and Output Files
1826 Autoconf-generated @command{configure} scripts need some information about
1827 how to initialize, such as how to find the package's source files and
1828 about the output files to produce.  The following sections describe the
1829 initialization and the creation of output files.
1831 @menu
1832 * Initializing configure::      Option processing etc.
1833 * Versioning::                  Dealing with Autoconf versions
1834 * Notices::                     Copyright, version numbers in @command{configure}
1835 * Input::                       Where Autoconf should find files
1836 * Output::                      Outputting results from the configuration
1837 * Configuration Actions::       Preparing the output based on results
1838 * Configuration Files::         Creating output files
1839 * Makefile Substitutions::      Using output variables in makefiles
1840 * Configuration Headers::       Creating a configuration header file
1841 * Configuration Commands::      Running arbitrary instantiation commands
1842 * Configuration Links::         Links depending on the configuration
1843 * Subdirectories::              Configuring independent packages together
1844 * Default Prefix::              Changing the default installation prefix
1845 @end menu
1847 @node Initializing configure
1848 @section Initializing @command{configure}
1850 Every @command{configure} script must call @code{AC_INIT} before doing
1851 anything else that produces output.  Calls to silent macros, such as
1852 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1853 are generally used via @file{aclocal.m4}, since that is implicitly
1854 included before the start of @file{configure.ac}.  The only other
1855 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1857 @anchor{AC_INIT}
1858 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1859   @ovar{tarname}, @ovar{url})
1860 @acindex{INIT}
1861 Process any command-line arguments and perform initialization
1862 and verification.
1864 Set the name of the @var{package} and its @var{version}.  These are
1865 typically used in @option{--version} support, including that of
1866 @command{configure}.  The optional argument @var{bug-report} should be
1867 the email to which users should send bug reports.  The package
1868 @var{tarname} differs from @var{package}: the latter designates the full
1869 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1870 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1871 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1872 other than alphanumerics and underscores are changed to @samp{-}.  If
1873 provided, @var{url} should be the home page for the package.
1875 The arguments of @code{AC_INIT} must be static, i.e., there should not
1876 be any shell computation, quotes, or newlines, but they can be computed
1877 by M4.  This is because the package information strings are expanded at
1878 M4 time into several contexts, and must give the same text at shell time
1879 whether used in single-quoted strings, double-quoted strings, quoted
1880 here-documents, or unquoted here-documents.  It is permissible to use
1881 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1882 that changes with every commit to a version control system (in fact,
1883 Autoconf does just that, for all builds of the development tree made
1884 between releases).
1886 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1887 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1888 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1890 @table @asis
1891 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1892 @acindex{PACKAGE_NAME}
1893 @ovindex PACKAGE_NAME
1894 @cvindex PACKAGE_NAME
1895 Exactly @var{package}.
1897 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1898 @acindex{PACKAGE_TARNAME}
1899 @ovindex PACKAGE_TARNAME
1900 @cvindex PACKAGE_TARNAME
1901 Exactly @var{tarname}, possibly generated from @var{package}.
1903 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1904 @acindex{PACKAGE_VERSION}
1905 @ovindex PACKAGE_VERSION
1906 @cvindex PACKAGE_VERSION
1907 Exactly @var{version}.
1909 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1910 @acindex{PACKAGE_STRING}
1911 @ovindex PACKAGE_STRING
1912 @cvindex PACKAGE_STRING
1913 Exactly @samp{@var{package} @var{version}}.
1915 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1916 @acindex{PACKAGE_BUGREPORT}
1917 @ovindex PACKAGE_BUGREPORT
1918 @cvindex PACKAGE_BUGREPORT
1919 Exactly @var{bug-report}, if one was provided.  Typically an email
1920 address, or URL to a bug management web page.
1922 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1923 @acindex{PACKAGE_URL}
1924 @ovindex PACKAGE_URL
1925 @cvindex PACKAGE_URL
1926 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1927 @var{package} begins with @samp{GNU }, then this defaults to
1928 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1929 assumed.
1930 @end table
1931 @end defmac
1933 If your @command{configure} script does its own option processing, it
1934 should inspect @samp{$@@} or @samp{$*} immediately after calling
1935 @code{AC_INIT}, because other Autoconf macros liberally use the
1936 @command{set} command to process strings, and this has the side effect
1937 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1938 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1939 implement your own option processing.  @xref{Site Configuration}.
1941 @node Versioning
1942 @section Dealing with Autoconf versions
1943 @cindex Autoconf version
1944 @cindex version, Autoconf
1946 The following optional macros can be used to help choose the minimum
1947 version of Autoconf that can successfully compile a given
1948 @file{configure.ac}.
1950 @defmac AC_PREREQ (@var{version})
1951 @acindex{PREREQ}
1952 @cindex Version
1953 Ensure that a recent enough version of Autoconf is being used.  If the
1954 version of Autoconf being used to create @command{configure} is
1955 earlier than @var{version}, print an error message to the standard
1956 error output and exit with failure (exit status is 63).  For example:
1958 @example
1959 AC_PREREQ([@value{VERSION}])
1960 @end example
1962 This macro may be used before @code{AC_INIT}.
1963 @end defmac
1965 @defmac AC_AUTOCONF_VERSION
1966 @acindex{AUTOCONF_VERSION}
1967 This macro was introduced in Autoconf 2.62.  It identifies the version
1968 of Autoconf that is currently parsing the input file, in a format
1969 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1970 other words, for this release of Autoconf, its value is
1971 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1972 conditional fallbacks based on when a feature was added to Autoconf,
1973 rather than using @code{AC_PREREQ} to require the newer version of
1974 Autoconf.  However, remember that the Autoconf philosophy favors feature
1975 checks over version checks.
1977 You should not expand this macro directly; use
1978 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1979 users might
1980 have a beta version of Autoconf installed, with arbitrary letters
1981 included in its version string.  This means it is possible for the
1982 version string to contain the name of a defined macro, such that
1983 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1984 macro during rescanning, and change the version string to be different
1985 than what you intended to check.
1986 @end defmac
1988 @node Notices
1989 @section Notices in @command{configure}
1990 @cindex Notices in @command{configure}
1992 The following macros manage version numbers for @command{configure}
1993 scripts.  Using them is optional.
1995 @defmac AC_COPYRIGHT (@var{copyright-notice})
1996 @acindex{COPYRIGHT}
1997 @cindex Copyright Notice
1998 State that, in addition to the Free Software Foundation's copyright on
1999 the Autoconf macros, parts of your @command{configure} are covered by the
2000 @var{copyright-notice}.
2002 The @var{copyright-notice} shows up in both the head of
2003 @command{configure} and in @samp{configure --version}.
2004 @end defmac
2007 @defmac AC_REVISION (@var{revision-info})
2008 @acindex{REVISION}
2009 @cindex Revision
2010 Copy revision stamp @var{revision-info} into the @command{configure}
2011 script, with any dollar signs or double-quotes removed.  This macro lets
2012 you put a revision stamp from @file{configure.ac} into @command{configure}
2013 without RCS or CVS changing it when you check in
2014 @command{configure}.  That way, you can determine easily which revision of
2015 @file{configure.ac} a particular @command{configure} corresponds to.
2017 For example, this line in @file{configure.ac}:
2019 @c The @w prevents RCS from changing the example in the manual.
2020 @example
2021 AC_REVISION([@w{$}Revision: 1.30 $])
2022 @end example
2024 @noindent
2025 produces this in @command{configure}:
2027 @example
2028 #!/bin/sh
2029 # From configure.ac Revision: 1.30
2030 @end example
2031 @end defmac
2034 @node Input
2035 @section Finding @command{configure} Input
2037 @anchor{AC_CONFIG_SRCDIR}
2038 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2039 @acindex{CONFIG_SRCDIR}
2040 @var{unique-file-in-source-dir} is some file that is in the package's
2041 source directory; @command{configure} checks for this file's existence to
2042 make sure that the directory that it is told contains the source code in
2043 fact does.  Occasionally people accidentally specify the wrong directory
2044 with @option{--srcdir}; this is a safety check.  @xref{configure
2045 Invocation}, for more information.
2046 @end defmac
2049 @c FIXME: Remove definitively once --install explained.
2051 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2052 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2053 @c to split the macros in several files.  In this case, Autoconf must be
2054 @c told which files to load, and in which order.
2056 @c @defmac AC_INCLUDE (@var{file}@dots{})
2057 @c @acindex{INCLUDE}
2058 @c @c FIXME: There is no longer shell globbing.
2059 @c Read the macro definitions that appear in the listed files.  A list of
2060 @c space-separated file names or shell globbing patterns is expected.  The
2061 @c files are read in the order they're listed.
2063 @c Because the order of definition of macros is important (only the last
2064 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2065 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2066 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2067 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2068 @c the latter case, non-macro lines from included files may end up in the
2069 @c @file{configure} script, whereas in the former case, they'd be discarded
2070 @c just like any text that appear before @code{AC_INIT}.
2071 @c @end defmac
2073 Packages that do manual configuration or use the @command{install} program
2074 might need to tell @command{configure} where to find some other shell
2075 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2076 it looks are correct for most cases.
2078 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2079 @acindex{CONFIG_AUX_DIR}
2080 Use the auxiliary build tools (e.g., @file{install-sh},
2081 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2082 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2083 These are auxiliary files used in configuration.  @var{dir} can be
2084 either absolute or relative to @file{@var{srcdir}}.  The default is
2085 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2086 @file{@var{srcdir}/../..}, whichever is the first that contains
2087 @file{install-sh}.  The other files are not checked for, so that using
2088 @code{AC_PROG_INSTALL} does not automatically require distributing the
2089 other auxiliary files.  It checks for @file{install.sh} also, but that
2090 name is obsolete because some @command{make} have a rule that creates
2091 @file{install} from it if there is no makefile.
2093 The auxiliary directory is commonly named @file{build-aux}.
2094 If you need portability to DOS variants, do not name the
2095 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2096 @end defmac
2098 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2099 @acindex{REQUIRE_AUX_FILE}
2100 Declares that @var{file} is expected in the directory defined above.  In
2101 Autoconf proper, this macro does nothing: its sole purpose is to be
2102 traced by third-party tools to produce a list of expected auxiliary
2103 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2104 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2105 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2106 @end defmac
2108 Similarly, packages that use @command{aclocal} should declare where
2109 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2111 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2112 @acindex{CONFIG_MACRO_DIR}
2113 Specify @var{dir} as the location of additional local Autoconf macros.
2114 This macro is intended for use by future versions of commands like
2115 @command{autoreconf} that trace macro calls.  It should be called
2116 directly from @file{configure.ac} so that tools that install macros for
2117 @command{aclocal} can find the macros' declarations.
2119 Note that if you use @command{aclocal} from Automake to generate
2120 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2121 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2122 the Autoconf implementation of @command{autoreconf}, these include
2123 directives currently must be set on a single line in @file{Makefile.am},
2124 without any backslash-newlines.
2125 @end defmac
2128 @node Output
2129 @section Outputting Files
2130 @cindex Outputting files
2132 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2133 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2134 @file{config.status}, which in turn creates the makefiles and any
2135 other files resulting from configuration.  This is the only required
2136 macro besides @code{AC_INIT} (@pxref{Input}).
2138 @anchor{AC_OUTPUT}
2139 @defmac AC_OUTPUT
2140 @acindex{OUTPUT}
2141 @cindex Instantiation
2142 Generate @file{config.status} and launch it.  Call this macro once, at
2143 the end of @file{configure.ac}.
2145 @file{config.status} performs all the configuration actions: all the
2146 output files (see @ref{Configuration Files}, macro
2147 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2148 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2149 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2150 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2151 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2152 are honored.
2154 The location of your @code{AC_OUTPUT} invocation is the exact point
2155 where configuration actions are taken: any code afterwards is
2156 executed by @command{configure} once @command{config.status} was run.  If
2157 you want to bind actions to @command{config.status} itself
2158 (independently of whether @command{configure} is being run), see
2159 @ref{Configuration Commands, , Running Arbitrary Configuration
2160 Commands}.
2161 @end defmac
2163 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2164 @xref{Obsolete Macros}, for a description of the arguments that
2165 @code{AC_OUTPUT} used to support.
2168 If you run @command{make} in subdirectories, you should run it using the
2169 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2170 @code{MAKE} to the name of the @command{make} program plus any options it
2171 was given.  (But many do not include in it the values of any variables
2172 set on the command line, so those are not passed on automatically.)
2173 Some old versions of @command{make} do not set this variable.  The
2174 following macro allows you to use it even with those versions.
2176 @anchor{AC_PROG_MAKE_SET}
2177 @defmac AC_PROG_MAKE_SET
2178 @acindex{PROG_MAKE_SET}
2179 @ovindex SET_MAKE
2180 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2181 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2182 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2183 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2184 @code{SET_MAKE}.
2185 @end defmac
2187 If you use this macro, place a line like this in each @file{Makefile.in}
2188 that runs @command{MAKE} on other directories:
2190 @example
2191 @@SET_MAKE@@
2192 @end example
2196 @node Configuration Actions
2197 @section Performing Configuration Actions
2198 @cindex Configuration actions
2200 @file{configure} is designed so that it appears to do everything itself,
2201 but there is actually a hidden slave: @file{config.status}.
2202 @file{configure} is in charge of examining your system, but it is
2203 @file{config.status} that actually takes the proper actions based on the
2204 results of @file{configure}.  The most typical task of
2205 @file{config.status} is to @emph{instantiate} files.
2207 @acindex{CONFIG_@var{ITEMS}}
2208 This section describes the common behavior of the four standard
2209 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2210 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2211 have this prototype:
2213 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2214 @c awful.
2215 @example
2216 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2217 @end example
2219 @noindent
2220 where the arguments are:
2222 @table @var
2223 @item tag@dots{}
2224 A blank-or-newline-separated list of tags, which are typically the names of
2225 the files to instantiate.
2227 You are encouraged to use literals as @var{tags}.  In particular, you
2228 should avoid
2230 @example
2231 @dots{} && my_foos="$my_foos fooo"
2232 @dots{} && my_foos="$my_foos foooo"
2233 AC_CONFIG_@var{ITEMS}([$my_foos])
2234 @end example
2236 @noindent
2237 and use this instead:
2239 @example
2240 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2241 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2242 @end example
2244 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2245 special @var{tag} values: they may have the form @samp{@var{output}} or
2246 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2247 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2249 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2250 for example, asks for
2251 the creation of the file @file{Makefile} that contains the expansion of the
2252 output variables in the concatenation of @file{boiler/top.mk} and
2253 @file{boiler/bot.mk}.
2255 The special value @samp{-} might be used to denote the standard output
2256 when used in @var{output}, or the standard input when used in the
2257 @var{inputs}.  You most probably don't need to use this in
2258 @file{configure.ac}, but it is convenient when using the command line
2259 interface of @file{./config.status}, see @ref{config.status Invocation},
2260 for more details.
2262 The @var{inputs} may be absolute or relative file names.  In the latter
2263 case they are first looked for in the build tree, and then in the source
2264 tree.  Input files should be text files, and a line length below 2000
2265 bytes should be safe.
2267 @item commands
2268 Shell commands output literally into @file{config.status}, and
2269 associated with a tag that the user can use to tell @file{config.status}
2270 which commands to run.  The commands are run each time a @var{tag}
2271 request is given to @file{config.status}, typically each time the file
2272 @file{@var{tag}} is created.
2274 The variables set during the execution of @command{configure} are
2275 @emph{not} available here: you first need to set them via the
2276 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2278 @table @code
2279 @item srcdir
2280 @vrindex srcdir
2281 The name of the top source directory, assuming that the working
2282 directory is the top build directory.  This
2283 is what the @command{configure} option @option{--srcdir} sets.
2285 @item ac_top_srcdir
2286 @vrindex ac_top_srcdir
2287 The name of the top source directory, assuming that the working
2288 directory is the current build directory.
2290 @item ac_top_build_prefix
2291 @vrindex ac_top_build_prefix
2292 The name of the top build directory, assuming that the working
2293 directory is the current build directory.
2294 It can be empty, or else ends with a slash, so that you may concatenate
2297 @item ac_srcdir
2298 @vrindex ac_srcdir
2299 The name of the corresponding source directory, assuming that the
2300 working directory is the current build directory.
2302 @item tmp
2303 @vrindex tmp
2304 The name of a temporary directory within the build tree, which you
2305 can use if you need to create additional temporary files.  The
2306 directory is cleaned up when @command{config.status} is done or
2307 interrupted.  Please use package-specific file name prefixes to
2308 avoid clashing with files that @command{config.status} may use
2309 internally.
2310 @end table
2312 @noindent
2313 The @dfn{current} directory refers to the directory (or
2314 pseudo-directory) containing the input part of @var{tags}.  For
2315 instance, running
2317 @example
2318 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2319 @end example
2321 @noindent
2322  with @option{--srcdir=../package} produces the following values:
2324 @example
2325 # Argument of --srcdir
2326 srcdir='../package'
2327 # Reversing deep/dir
2328 ac_top_build_prefix='../../'
2329 # Concatenation of $ac_top_build_prefix and srcdir
2330 ac_top_srcdir='../../../package'
2331 # Concatenation of $ac_top_srcdir and deep/dir
2332 ac_srcdir='../../../package/deep/dir'
2333 @end example
2335 @noindent
2336 independently of @samp{in/in.in}.
2338 @item init-cmds
2339 Shell commands output @emph{unquoted} near the beginning of
2340 @file{config.status}, and executed each time @file{config.status} runs
2341 (regardless of the tag).  Because they are unquoted, for example,
2342 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2343 is typically used by @file{configure} to give @file{config.status} some
2344 variables it needs to run the @var{commands}.
2346 You should be extremely cautious in your variable names: all the
2347 @var{init-cmds} share the same name space and may overwrite each other
2348 in unpredictable ways.  Sorry@enddots{}
2349 @end table
2351 All these macros can be called multiple times, with different
2352 @var{tag} values, of course!
2355 @node Configuration Files
2356 @section Creating Configuration Files
2357 @cindex Creating configuration files
2358 @cindex Configuration file creation
2360 Be sure to read the previous section, @ref{Configuration Actions}.
2362 @anchor{AC_CONFIG_FILES}
2363 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2364 @acindex{CONFIG_FILES}
2365 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2366 file (by default @file{@var{file}.in}), substituting the output variable
2367 values.
2368 @c Before we used to have this feature, which was later rejected
2369 @c because it complicates the writing of makefiles:
2370 @c If the file would be unchanged, it is left untouched, to preserve
2371 @c timestamp.
2372 This macro is one of the instantiating macros; see @ref{Configuration
2373 Actions}.  @xref{Makefile Substitutions}, for more information on using
2374 output variables.  @xref{Setting Output Variables}, for more information
2375 on creating them.  This macro creates the directory that the file is in
2376 if it doesn't exist.  Usually, makefiles are created this way,
2377 but other files, such as @file{.gdbinit}, can be specified as well.
2379 Typical calls to @code{AC_CONFIG_FILES} look like this:
2381 @example
2382 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2383 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2384 @end example
2386 You can override an input file name by appending to @var{file} a
2387 colon-separated list of input files.  Examples:
2389 @example
2390 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2391                 [lib/Makefile:boiler/lib.mk])
2392 @end example
2394 @noindent
2395 Doing this allows you to keep your file names acceptable to
2396 DOS variants, or
2397 to prepend and/or append boilerplate to the file.
2398 @end defmac
2402 @node Makefile Substitutions
2403 @section Substitutions in Makefiles
2404 @cindex Substitutions in makefiles
2405 @cindex Makefile substitutions
2407 Each subdirectory in a distribution that contains something to be
2408 compiled or installed should come with a file @file{Makefile.in}, from
2409 which @command{configure} creates a file @file{Makefile} in that directory.
2410 To create @file{Makefile}, @command{configure} performs a simple variable
2411 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2412 @file{Makefile.in} with the value that @command{configure} has determined
2413 for that variable.  Variables that are substituted into output files in
2414 this way are called @dfn{output variables}.  They are ordinary shell
2415 variables that are set in @command{configure}.  To make @command{configure}
2416 substitute a particular variable into the output files, the macro
2417 @code{AC_SUBST} must be called with that variable name as an argument.
2418 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2419 left unchanged.  @xref{Setting Output Variables}, for more information
2420 on creating output variables with @code{AC_SUBST}.
2422 A software package that uses a @command{configure} script should be
2423 distributed with a file @file{Makefile.in}, but no makefile; that
2424 way, the user has to properly configure the package for the local system
2425 before compiling it.
2427 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2428 GNU Coding Standards}, for more information on what to put in
2429 makefiles.
2431 @menu
2432 * Preset Output Variables::     Output variables that are always set
2433 * Installation Directory Variables::  Other preset output variables
2434 * Changed Directory Variables::  Warnings about @file{datarootdir}
2435 * Build Directories::           Supporting multiple concurrent compiles
2436 * Automatic Remaking::          Makefile rules for configuring
2437 @end menu
2439 @node Preset Output Variables
2440 @subsection Preset Output Variables
2441 @cindex Output variables
2443 Some output variables are preset by the Autoconf macros.  Some of the
2444 Autoconf macros set additional output variables, which are mentioned in
2445 the descriptions for those macros.  @xref{Output Variable Index}, for a
2446 complete list of output variables.  @xref{Installation Directory
2447 Variables}, for the list of the preset ones related to installation
2448 directories.  Below are listed the other preset ones, many of which are
2449 precious variables (@pxref{Setting Output Variables},
2450 @code{AC_ARG_VAR}).
2452 The preset variables which are available during @file{config.status}
2453 (@pxref{Configuration Actions}) may also be used during
2454 @command{configure} tests.  For example, it is permissible to reference
2455 @samp{$srcdir} when constructing a list of directories to pass via
2456 option @option{-I} during a compiler feature check.  When used in this
2457 manner, coupled with the fact that @command{configure} is always run
2458 from the top build directory, it is sufficient to use just
2459 @samp{$srcdir} instead of @samp{$top_srcdir}.
2461 @c Just say no to ASCII sorting!  We're humans, not computers.
2462 @c These variables are listed as they would be in a dictionary:
2463 @c actor
2464 @c Actress
2465 @c actress
2467 @defvar CFLAGS
2468 @evindex CFLAGS
2469 @ovindex CFLAGS
2470 Debugging and optimization options for the C compiler.  If it is not set
2471 in the environment when @command{configure} runs, the default value is set
2472 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2473 uses this variable when compiling or linking programs to test for C features.
2475 If a compiler option affects only the behavior of the preprocessor
2476 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2477 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2478 it should be put into @code{LDFLAGS} instead.  If it
2479 affects only the compiler proper, @code{CFLAGS} is the natural home for
2480 it.  If an option affects multiple phases of the compiler, though,
2481 matters get tricky.  One approach to put such options directly into
2482 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2483 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2485 However, remember that some @file{Makefile} variables are reserved by
2486 the GNU Coding Standards for the use of the ``user''---the person
2487 building the package.  For instance, @code{CFLAGS} is one such variable.
2489 Sometimes package developers are tempted to set user variables such as
2490 @code{CFLAGS} because it appears to make their job easier.  However, the
2491 package itself should never set a user variable, particularly not to
2492 include switches that are required for proper compilation of the
2493 package.  Since these variables are documented as being for the package
2494 builder, that person rightfully expects to be able to override any of
2495 these variables at build time.  If the package developer needs to add
2496 switches without interfering with the user, the proper way to do that is
2497 to introduce an additional variable.  Automake makes this easy by
2498 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2499 automake, GNU Automake}), but the concept is the same even if
2500 Automake is not used.
2501 @end defvar
2503 @defvar configure_input
2504 @ovindex configure_input
2505 A comment saying that the file was generated automatically by
2506 @command{configure} and giving the name of the input file.
2507 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2508 of every makefile it creates.  For other files, you should
2509 reference this variable in a comment at the top of each input file.  For
2510 example, an input shell script should begin like this:
2512 @example
2513 #!/bin/sh
2514 # @@configure_input@@
2515 @end example
2517 @noindent
2518 The presence of that line also reminds people editing the file that it
2519 needs to be processed by @command{configure} in order to be used.
2520 @end defvar
2522 @defvar CPPFLAGS
2523 @evindex CPPFLAGS
2524 @ovindex CPPFLAGS
2525 Preprocessor options for the C, C++, Objective C, and Objective C++
2526 preprocessors and compilers.  If
2527 it is not set in the environment when @command{configure} runs, the default
2528 value is empty.  @command{configure} uses this variable when preprocessing
2529 or compiling programs to test for C, C++, Objective C, and Objective C++
2530 features.
2532 This variable's contents should contain options like @option{-I},
2533 @option{-D}, and @option{-U} that affect only the behavior of the
2534 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2535 can do if an option affects other phases of the compiler as well.
2537 Currently, @command{configure} always links as part of a single
2538 invocation of the compiler that also preprocesses and compiles, so it
2539 uses this variable also when linking programs.  However, it is unwise to
2540 depend on this behavior because the GNU Coding Standards do
2541 not require it and many packages do not use @code{CPPFLAGS} when linking
2542 programs.
2544 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2545 might run into.
2546 @end defvar
2548 @defvar CXXFLAGS
2549 @evindex CXXFLAGS
2550 @ovindex CXXFLAGS
2551 Debugging and optimization options for the C++ compiler.  It acts like
2552 @code{CFLAGS}, but for C++ instead of C.
2553 @end defvar
2555 @defvar DEFS
2556 @ovindex DEFS
2557 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2558 is called, @command{configure} replaces @samp{@@DEFS@@} with
2559 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2560 variable is not defined while @command{configure} is performing its tests,
2561 only when creating the output files.  @xref{Setting Output Variables}, for
2562 how to check the results of previous tests.
2563 @end defvar
2565 @defvar ECHO_C
2566 @defvarx ECHO_N
2567 @defvarx ECHO_T
2568 @ovindex ECHO_C
2569 @ovindex ECHO_N
2570 @ovindex ECHO_T
2571 How does one suppress the trailing newline from @command{echo} for
2572 question-answer message pairs?  These variables provide a way:
2574 @example
2575 echo $ECHO_N "And the winner is... $ECHO_C"
2576 sleep 100000000000
2577 echo "$@{ECHO_T@}dead."
2578 @end example
2580 @noindent
2581 Some old and uncommon @command{echo} implementations offer no means to
2582 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2583 want to use it.
2584 @end defvar
2586 @defvar ERLCFLAGS
2587 @evindex ERLCFLAGS
2588 @ovindex ERLCFLAGS
2589 Debugging and optimization options for the Erlang compiler.  If it is not set
2590 in the environment when @command{configure} runs, the default value is empty.
2591 @command{configure} uses this variable when compiling
2592 programs to test for Erlang features.
2593 @end defvar
2595 @defvar FCFLAGS
2596 @evindex FCFLAGS
2597 @ovindex FCFLAGS
2598 Debugging and optimization options for the Fortran compiler.  If it
2599 is not set in the environment when @command{configure} runs, the default
2600 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2601 @command{configure} uses this variable when compiling or linking
2602 programs to test for Fortran features.
2603 @end defvar
2605 @defvar FFLAGS
2606 @evindex FFLAGS
2607 @ovindex FFLAGS
2608 Debugging and optimization options for the Fortran 77 compiler.  If it
2609 is not set in the environment when @command{configure} runs, the default
2610 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2611 @command{configure} uses this variable when compiling or linking
2612 programs to test for Fortran 77 features.
2613 @end defvar
2615 @defvar LDFLAGS
2616 @evindex LDFLAGS
2617 @ovindex LDFLAGS
2618 Options for the linker.  If it is not set
2619 in the environment when @command{configure} runs, the default value is empty.
2620 @command{configure} uses this variable when linking programs to test for
2621 C, C++, Objective C, Objective C++, Fortran, and Go features.
2623 This variable's contents should contain options like @option{-s} and
2624 @option{-L} that affect only the behavior of the linker.  Please see the
2625 explanation of @code{CFLAGS} for what you can do if an option also
2626 affects other phases of the compiler.
2628 Don't use this variable to pass library names
2629 (@option{-l}) to the linker; use @code{LIBS} instead.
2630 @end defvar
2632 @defvar LIBS
2633 @evindex LIBS
2634 @ovindex LIBS
2635 @option{-l} options to pass to the linker.  The default value is empty,
2636 but some Autoconf macros may prepend extra libraries to this variable if
2637 those libraries are found and provide necessary functions, see
2638 @ref{Libraries}.  @command{configure} uses this variable when linking
2639 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2640 features.
2641 @end defvar
2643 @defvar OBJCFLAGS
2644 @evindex OBJCFLAGS
2645 @ovindex OBJCFLAGS
2646 Debugging and optimization options for the Objective C compiler.  It
2647 acts like @code{CFLAGS}, but for Objective C instead of C.
2648 @end defvar
2650 @defvar OBJCXXFLAGS
2651 @evindex OBJCXXFLAGS
2652 @ovindex OBJCXXFLAGS
2653 Debugging and optimization options for the Objective C++ compiler.  It
2654 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2655 @end defvar
2657 @defvar GOFLAGS
2658 @evindex GOFLAGS
2659 @ovindex GOFLAGS
2660 Debugging and optimization options for the Go compiler.  It acts like
2661 @code{CFLAGS}, but for Go instead of C.
2662 @end defvar
2664 @defvar builddir
2665 @ovindex builddir
2666 Rigorously equal to @samp{.}.  Added for symmetry only.
2667 @end defvar
2669 @defvar abs_builddir
2670 @ovindex abs_builddir
2671 Absolute name of @code{builddir}.
2672 @end defvar
2674 @defvar top_builddir
2675 @ovindex top_builddir
2676 The relative name of the top level of the current build tree.  In the
2677 top-level directory, this is the same as @code{builddir}.
2678 @end defvar
2680 @defvar top_build_prefix
2681 @ovindex top_build_prefix
2682 The relative name of the top level of the current build tree with final
2683 slash if nonempty.  This is the same as @code{top_builddir}, except that
2684 it contains zero or more runs of @code{../}, so it should not be
2685 appended with a slash for concatenation.  This helps for @command{make}
2686 implementations that otherwise do not treat @file{./file} and @file{file}
2687 as equal in the toplevel build directory.
2688 @end defvar
2690 @defvar abs_top_builddir
2691 @ovindex abs_top_builddir
2692 Absolute name of @code{top_builddir}.
2693 @end defvar
2695 @defvar srcdir
2696 @ovindex srcdir
2697 The name of the directory that contains the source code for
2698 that makefile.
2699 @end defvar
2701 @defvar abs_srcdir
2702 @ovindex abs_srcdir
2703 Absolute name of @code{srcdir}.
2704 @end defvar
2706 @defvar top_srcdir
2707 @ovindex top_srcdir
2708 The name of the top-level source code directory for the
2709 package.  In the top-level directory, this is the same as @code{srcdir}.
2710 @end defvar
2712 @defvar abs_top_srcdir
2713 @ovindex abs_top_srcdir
2714 Absolute name of @code{top_srcdir}.
2715 @end defvar
2717 @node Installation Directory Variables
2718 @subsection Installation Directory Variables
2719 @cindex Installation directories
2720 @cindex Directories, installation
2722 The following variables specify the directories for
2723 package installation, see @ref{Directory Variables, , Variables for
2724 Installation Directories, standards, The GNU Coding
2725 Standards}, for more information.  Each variable corresponds to an
2726 argument of @command{configure}; trailing slashes are stripped so that
2727 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2728 between directory names.  See the end of this section for
2729 details on when and how to use these variables.
2731 @defvar bindir
2732 @ovindex bindir
2733 The directory for installing executables that users run.
2734 @end defvar
2736 @defvar datadir
2737 @ovindex datadir
2738 The directory for installing idiosyncratic read-only
2739 architecture-independent data.
2740 @end defvar
2742 @defvar datarootdir
2743 @ovindex datarootdir
2744 The root of the directory tree for read-only architecture-independent
2745 data files.
2746 @end defvar
2748 @defvar docdir
2749 @ovindex docdir
2750 The directory for installing documentation files (other than Info and
2751 man).
2752 @end defvar
2754 @defvar dvidir
2755 @ovindex dvidir
2756 The directory for installing documentation files in DVI format.
2757 @end defvar
2759 @defvar exec_prefix
2760 @ovindex exec_prefix
2761 The installation prefix for architecture-dependent files.  By default
2762 it's the same as @code{prefix}.  You should avoid installing anything
2763 directly to @code{exec_prefix}.  However, the default value for
2764 directories containing architecture-dependent files should be relative
2765 to @code{exec_prefix}.
2766 @end defvar
2768 @defvar htmldir
2769 @ovindex htmldir
2770 The directory for installing HTML documentation.
2771 @end defvar
2773 @defvar includedir
2774 @ovindex includedir
2775 The directory for installing C header files.
2776 @end defvar
2778 @defvar infodir
2779 @ovindex infodir
2780 The directory for installing documentation in Info format.
2781 @end defvar
2783 @defvar libdir
2784 @ovindex libdir
2785 The directory for installing object code libraries.
2786 @end defvar
2788 @defvar libexecdir
2789 @ovindex libexecdir
2790 The directory for installing executables that other programs run.
2791 @end defvar
2793 @defvar localedir
2794 @ovindex localedir
2795 The directory for installing locale-dependent but
2796 architecture-independent data, such as message catalogs.  This directory
2797 usually has a subdirectory per locale.
2798 @end defvar
2800 @defvar localstatedir
2801 @ovindex localstatedir
2802 The directory for installing modifiable single-machine data.
2803 @end defvar
2805 @defvar mandir
2806 @ovindex mandir
2807 The top-level directory for installing documentation in man format.
2808 @end defvar
2810 @defvar oldincludedir
2811 @ovindex oldincludedir
2812 The directory for installing C header files for non-GCC compilers.
2813 @end defvar
2815 @defvar pdfdir
2816 @ovindex pdfdir
2817 The directory for installing PDF documentation.
2818 @end defvar
2820 @defvar prefix
2821 @ovindex prefix
2822 The common installation prefix for all files.  If @code{exec_prefix}
2823 is defined to a different value, @code{prefix} is used only for
2824 architecture-independent files.
2825 @end defvar
2827 @defvar psdir
2828 @ovindex psdir
2829 The directory for installing PostScript documentation.
2830 @end defvar
2832 @defvar sbindir
2833 @ovindex sbindir
2834 The directory for installing executables that system
2835 administrators run.
2836 @end defvar
2838 @defvar sharedstatedir
2839 @ovindex sharedstatedir
2840 The directory for installing modifiable architecture-independent data.
2841 @end defvar
2843 @defvar sysconfdir
2844 @ovindex sysconfdir
2845 The directory for installing read-only single-machine data.
2846 @end defvar
2849 Most of these variables have values that rely on @code{prefix} or
2850 @code{exec_prefix}.  It is deliberate that the directory output
2851 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2852 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2853 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2855 This behavior is mandated by the GNU Coding Standards, so that when
2856 the user runs:
2858 @table @samp
2859 @item make
2860 she can still specify a different prefix from the one specified to
2861 @command{configure}, in which case, if needed, the package should hard
2862 code dependencies corresponding to the make-specified prefix.
2864 @item make install
2865 she can specify a different installation location, in which case the
2866 package @emph{must} still depend on the location which was compiled in
2867 (i.e., never recompile when @samp{make install} is run).  This is an
2868 extremely important feature, as many people may decide to install all
2869 the files of a package grouped together, and then install links from
2870 the final locations to there.
2871 @end table
2873 In order to support these features, it is essential that
2874 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2875 so that its value can be expanded based
2876 on the current value of @code{prefix}.
2878 A corollary is that you should not use these variables except in
2879 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2880 in @file{configure} and hard-coding it in makefiles using
2881 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2882 you should add
2883 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2884 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2886 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2887 @code{bindir} and friends in your shell scripts and other files; instead,
2888 let @command{make} manage their replacement.  For instance Autoconf
2889 ships templates of its shell scripts ending with @samp{.in}, and uses a
2890 makefile snippet similar to the following to build scripts like
2891 @command{autoheader} and @command{autom4te}:
2893 @example
2894 @group
2895 edit = sed \
2896         -e 's|@@bindir[@@]|$(bindir)|g' \
2897         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2898         -e 's|@@prefix[@@]|$(prefix)|g'
2899 @end group
2901 @group
2902 autoheader autom4te: Makefile
2903         rm -f $@@ $@@.tmp
2904         srcdir=''; \
2905           test -f ./$@@.in || srcdir=$(srcdir)/; \
2906           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2907 @c $$ restore font-lock
2908         chmod +x $@@.tmp
2909         chmod a-w $@@.tmp
2910         mv $@@.tmp $@@
2911 @end group
2913 @group
2914 autoheader: $(srcdir)/autoheader.in
2915 autom4te: $(srcdir)/autom4te.in
2916 @end group
2917 @end example
2919 Some details are noteworthy:
2921 @table @asis
2922 @item @samp{@@bindir[@@]}
2923 The brackets prevent @command{configure} from replacing
2924 @samp{@@bindir@@} in the Sed expression itself.
2925 Brackets are preferable to a backslash here, since
2926 Posix says @samp{\@@} is not portable.
2928 @item @samp{$(bindir)}
2929 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2930 instead.
2932 @item @samp{$(pkgdatadir)}
2933 The example takes advantage of the variable @samp{$(pkgdatadir)}
2934 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2936 @item @samp{/}
2937 Don't use @samp{/} in the Sed expressions that replace file names since
2938 most likely the
2939 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2940 Use a shell metacharacter instead, such as @samp{|}.
2942 @item special characters
2943 File names, file name components, and the value of @code{VPATH} should
2944 not contain shell metacharacters or white
2945 space.  @xref{Special Chars in Variables}.
2947 @item dependency on @file{Makefile}
2948 Since @code{edit} uses values that depend on the configuration specific
2949 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2950 the output depends on @file{Makefile}, not @file{configure.ac}.
2952 @item @samp{$@@}
2953 The main rule is generic, and uses @samp{$@@} extensively to
2954 avoid the need for multiple copies of the rule.
2956 @item Separated dependencies and single suffix rules
2957 You can't use them!  The above snippet cannot be (portably) rewritten
2960 @example
2961 autoconf autoheader: Makefile
2962 @group
2963 .in:
2964         rm -f $@@ $@@.tmp
2965         $(edit) $< >$@@.tmp
2966         chmod +x $@@.tmp
2967         mv $@@.tmp $@@
2968 @end group
2969 @end example
2971 @xref{Single Suffix Rules}, for details.
2973 @item @samp{$(srcdir)}
2974 Be sure to specify the name of the source directory,
2975 otherwise the package won't support separated builds.
2976 @end table
2978 For the more specific installation of Erlang libraries, the following variables
2979 are defined:
2981 @defvar ERLANG_INSTALL_LIB_DIR
2982 @ovindex ERLANG_INSTALL_LIB_DIR
2983 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2984 The common parent directory of Erlang library installation directories.
2985 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2986 macro in @file{configure.ac}.
2987 @end defvar
2989 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2990 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2991 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2992 The installation directory for Erlang library @var{library}.
2993 This variable is set by using the
2994 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2995 macro in @file{configure.ac}.
2996 @end defvar
2998 @xref{Erlang Libraries}, for details.
3001 @node Changed Directory Variables
3002 @subsection Changed Directory Variables
3003 @cindex @file{datarootdir}
3005 In Autoconf 2.60, the set of directory variables has changed, and the
3006 defaults of some variables have been adjusted
3007 (@pxref{Installation Directory Variables}) to changes in the
3008 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3009 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3010 upgrading from an earlier Autoconf version, you may need to adjust your files
3011 to ensure that the directory variables are substituted correctly
3012 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3013 in place.  For example, in a @file{Makefile.in}, adding
3015 @example
3016 datarootdir = @@datarootdir@@
3017 @end example
3019 @noindent
3020 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3021 it will add this for you.
3023 To help with the transition, Autoconf warns about files that seem to use
3024 @code{datarootdir} without defining it.  In some cases, it then expands
3025 the value of @code{$datarootdir} in substitutions of the directory
3026 variables.  The following example shows such a warning:
3028 @example
3029 $ @kbd{cat configure.ac}
3030 AC_INIT
3031 AC_CONFIG_FILES([Makefile])
3032 AC_OUTPUT
3033 $ @kbd{cat Makefile.in}
3034 prefix = @@prefix@@
3035 datadir = @@datadir@@
3036 $ @kbd{autoconf}
3037 $ @kbd{configure}
3038 configure: creating ./config.status
3039 config.status: creating Makefile
3040 config.status: WARNING:
3041                Makefile.in seems to ignore the --datarootdir setting
3042 $ @kbd{cat Makefile}
3043 prefix = /usr/local
3044 datadir = $@{prefix@}/share
3045 @end example
3047 Usually one can easily change the file to accommodate both older and newer
3048 Autoconf releases:
3050 @example
3051 $ @kbd{cat Makefile.in}
3052 prefix = @@prefix@@
3053 datarootdir = @@datarootdir@@
3054 datadir = @@datadir@@
3055 $ @kbd{configure}
3056 configure: creating ./config.status
3057 config.status: creating Makefile
3058 $ @kbd{cat Makefile}
3059 prefix = /usr/local
3060 datarootdir = $@{prefix@}/share
3061 datadir = $@{datarootdir@}
3062 @end example
3064 @acindex{DATAROOTDIR_CHECKED}
3065 In some cases, however, the checks may not be able to detect that a suitable
3066 initialization of @code{datarootdir} is in place, or they may fail to detect
3067 that such an initialization is necessary in the output file.  If, after
3068 auditing your package, there are still spurious @file{configure} warnings about
3069 @code{datarootdir}, you may add the line
3071 @example
3072 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3073 @end example
3075 @noindent
3076 to your @file{configure.ac} to disable the warnings.  This is an exception
3077 to the usual rule that you should not define a macro whose name begins with
3078 @code{AC_} (@pxref{Macro Names}).
3082 @node Build Directories
3083 @subsection Build Directories
3084 @cindex Build directories
3085 @cindex Directories, build
3087 You can support compiling a software package for several architectures
3088 simultaneously from the same copy of the source code.  The object files
3089 for each architecture are kept in their own directory.
3091 To support doing this, @command{make} uses the @code{VPATH} variable to
3092 find the files that are in the source directory.  GNU Make
3093 can do this.  Most other recent @command{make} programs can do this as
3094 well, though they may have difficulties and it is often simpler to
3095 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3096 @command{make} programs do not support @code{VPATH}; when using them, the
3097 source code must be in the same directory as the object files.
3099 If you are using GNU Automake, the remaining details in this
3100 section are already covered for you, based on the contents of your
3101 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3102 supporting @code{VPATH} requires the following in your
3103 @file{Makefile.in}:
3105 @example
3106 srcdir = @@srcdir@@
3107 VPATH = @@srcdir@@
3108 @end example
3110 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3111 listed in VPATH}.
3113 @command{configure} substitutes the correct value for @code{srcdir} when
3114 it produces @file{Makefile}.
3116 Do not use the @command{make} variable @code{$<}, which expands to the
3117 file name of the file in the source directory (found with @code{VPATH}),
3118 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3119 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3120 versions of @command{make} do not set @code{$<} in explicit rules; they
3121 expand it to an empty value.
3123 Instead, Make command lines should always refer to source
3124 files by prefixing them with @samp{$(srcdir)/}.  For example:
3126 @example
3127 time.info: time.texinfo
3128         $(MAKEINFO) '$(srcdir)/time.texinfo'
3129 @end example
3131 @node Automatic Remaking
3132 @subsection Automatic Remaking
3133 @cindex Automatic remaking
3134 @cindex Remaking automatically
3136 You can put rules like the following in the top-level @file{Makefile.in}
3137 for a package to automatically update the configuration information when
3138 you change the configuration files.  This example includes all of the
3139 optional files, such as @file{aclocal.m4} and those related to
3140 configuration header files.  Omit from the @file{Makefile.in} rules for
3141 any of these files that your package does not use.
3143 The @samp{$(srcdir)/} prefix is included because of limitations in the
3144 @code{VPATH} mechanism.
3146 The @file{stamp-} files are necessary because the timestamps of
3147 @file{config.h.in} and @file{config.h} are not changed if remaking
3148 them does not change their contents.  This feature avoids unnecessary
3149 recompilation.  You should include the file @file{stamp-h.in} in your
3150 package's distribution, so that @command{make} considers
3151 @file{config.h.in} up to date.  Don't use @command{touch}
3152 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3153 @command{echo} (using
3154 @command{date} would cause needless differences, hence CVS
3155 conflicts, etc.).
3157 @example
3158 @group
3159 $(srcdir)/configure: configure.ac aclocal.m4
3160         cd '$(srcdir)' && autoconf
3162 # autoheader might not change config.h.in, so touch a stamp file.
3163 $(srcdir)/config.h.in: stamp-h.in
3164 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3165         cd '$(srcdir)' && autoheader
3166         echo timestamp > '$(srcdir)/stamp-h.in'
3168 config.h: stamp-h
3169 stamp-h: config.h.in config.status
3170         ./config.status
3172 Makefile: Makefile.in config.status
3173         ./config.status
3175 config.status: configure
3176         ./config.status --recheck
3177 @end group
3178 @end example
3180 @noindent
3181 (Be careful if you copy these lines directly into your makefile, as you
3182 need to convert the indented lines to start with the tab character.)
3184 In addition, you should use
3186 @example
3187 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3188 @end example
3190 @noindent
3191 so @file{config.status} ensures that @file{config.h} is considered up to
3192 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3194 @xref{config.status Invocation}, for more examples of handling
3195 configuration-related dependencies.
3197 @node Configuration Headers
3198 @section Configuration Header Files
3199 @cindex Configuration Header
3200 @cindex @file{config.h}
3202 When a package contains more than a few tests that define C preprocessor
3203 symbols, the command lines to pass @option{-D} options to the compiler
3204 can get quite long.  This causes two problems.  One is that the
3205 @command{make} output is hard to visually scan for errors.  More
3206 seriously, the command lines can exceed the length limits of some
3207 operating systems.  As an alternative to passing @option{-D} options to
3208 the compiler, @command{configure} scripts can create a C header file
3209 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3210 macro selects this kind of output.  Though it can be called anywhere
3211 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3212 it right after @code{AC_INIT}.
3214 The package should @samp{#include} the configuration header file before
3215 any other header files, to prevent inconsistencies in declarations (for
3216 example, if it redefines @code{const}).
3218 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3219 option (or @option{-I..}; whichever directory contains @file{config.h}).
3220 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3221 the directory of the currently read file, i.e., the source directory, not
3222 the build directory.
3224 With the appropriate @option{-I} option, you can use
3225 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3226 because in the rare case when the source directory contains another
3227 @file{config.h}, the build directory should be searched first.
3230 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3231 @acindex{CONFIG_HEADERS}
3232 @cvindex HAVE_CONFIG_H
3233 This macro is one of the instantiating macros; see @ref{Configuration
3234 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3235 blank-or-newline-separated list @var{header} containing C preprocessor
3236 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3237 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3238 The usual name for @var{header} is @file{config.h}.
3240 If @var{header} already exists and its contents are identical to what
3241 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3242 making some changes in the configuration without needlessly causing
3243 object files that depend on the header file to be recompiled.
3245 Usually the input file is named @file{@var{header}.in}; however, you can
3246 override the input file name by appending to @var{header} a
3247 colon-separated list of input files.  For example, you might need to make
3248 the input file name acceptable to DOS variants:
3250 @example
3251 AC_CONFIG_HEADERS([config.h:config.hin])
3252 @end example
3254 @end defmac
3256 @defmac AH_HEADER
3257 @ahindex{HEADER}
3258 This macro is defined as the name of the first declared config header
3259 and undefined if no config headers have been declared up to this point.
3260 A third-party macro may, for example, require use of a config header
3261 without invoking AC_CONFIG_HEADERS twice, like this:
3263 @example
3264 AC_CONFIG_COMMANDS_PRE(
3265         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3266 @end example
3268 @end defmac
3270 @xref{Configuration Actions}, for more details on @var{header}.
3272 @menu
3273 * Header Templates::            Input for the configuration headers
3274 * autoheader Invocation::       How to create configuration templates
3275 * Autoheader Macros::           How to specify CPP templates
3276 @end menu
3278 @node Header Templates
3279 @subsection Configuration Header Templates
3280 @cindex Configuration Header Template
3281 @cindex Header templates
3282 @cindex @file{config.h.in}
3284 Your distribution should contain a template file that looks as you want
3285 the final header file to look, including comments, with @code{#undef}
3286 statements which are used as hooks.  For example, suppose your
3287 @file{configure.ac} makes these calls:
3289 @example
3290 AC_CONFIG_HEADERS([conf.h])
3291 AC_CHECK_HEADERS([unistd.h])
3292 @end example
3294 @noindent
3295 Then you could have code like the following in @file{conf.h.in}.
3296 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3297 to 1, if and only if the system has @file{unistd.h}.
3299 @example
3300 @group
3301 /* Define as 1 if you have unistd.h.  */
3302 #undef HAVE_UNISTD_H
3303 @end group
3304 @end example
3306 The format of the template file is stricter than what the C preprocessor
3307 is required to accept.  A directive line should contain only whitespace,
3308 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3309 instead of @samp{#undef}, or of comments on the same line as
3310 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3311 once.  Other preprocessor lines, such as @samp{#ifdef} or
3312 @samp{#include}, are copied verbatim from the template into the
3313 generated header.
3315 Since it is a tedious task to keep a template header up to date, you may
3316 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3318 During the instantiation of the header, each @samp{#undef} line in the
3319 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3320 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3321 been executed during the @command{configure} run, the @samp{#undef} line is
3322 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3323 on many systems, it can be implicitly defined by the compiler, and
3324 undefining it in the header would then break compilation of subsequent
3325 headers.)
3327 Currently, @emph{all} remaining @samp{#undef} lines in the header
3328 template are commented out, whether or not there was a corresponding
3329 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3330 for future releases of Autoconf.
3332 Generally speaking, since you should not use @samp{#define}, and you
3333 cannot guarantee whether a @samp{#undef} directive in the header
3334 template will be converted to a @samp{#define} or commented out in the
3335 generated header file, the template file cannot be used for conditional
3336 definition effects.  Consequently, if you need to use the construct
3338 @example
3339 @group
3340 #ifdef THIS
3341 # define THAT
3342 #endif
3343 @end group
3344 @end example
3346 @noindent
3347 you must place it outside of the template.
3348 If you absolutely need to hook it to the config header itself, please put
3349 the directives to a separate file, and @samp{#include} that file from the
3350 config header template.  If you are using @command{autoheader}, you would
3351 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3354 @node autoheader Invocation
3355 @subsection Using @command{autoheader} to Create @file{config.h.in}
3356 @cindex @command{autoheader}
3358 The @command{autoheader} program can create a template file of C
3359 @samp{#define} statements for @command{configure} to use.
3360 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3361 @file{configure} sources to determine the name of the template.
3362 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3363 input file name, @command{autoheader} uses the first one.)
3365 It is recommended that only one input file is used.  If you want to append
3366 a boilerplate code, it is preferable to use
3367 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3368 File @file{conf_post.h} is not processed during the configuration then,
3369 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3370 prepend a boilerplate code.
3372 In order to do its job, @command{autoheader} needs you to document all
3373 of the symbols that you might use.  Typically this is done via an
3374 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3375 is a literal symbol and whose third argument describes the symbol
3376 (@pxref{Defining Symbols}).  Alternatively, you can use
3377 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3378 suitable input file for a subsequent configuration header file.
3379 Symbols defined by Autoconf's builtin tests are already documented properly;
3380 you need to document only those that you
3381 define yourself.
3383 You might wonder why @command{autoheader} is needed: after all, why
3384 would @command{configure} need to ``patch'' a @file{config.h.in} to
3385 produce a @file{config.h} instead of just creating @file{config.h} from
3386 scratch?  Well, when everything rocks, the answer is just that we are
3387 wasting our time maintaining @command{autoheader}: generating
3388 @file{config.h} directly is all that is needed.  When things go wrong,
3389 however, you'll be thankful for the existence of @command{autoheader}.
3391 The fact that the symbols are documented is important in order to
3392 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3393 well-defined list of symbols that should be defined (or not) is
3394 also important for people who are porting packages to environments where
3395 @command{configure} cannot be run: they just have to @emph{fill in the
3396 blanks}.
3398 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3400 If you give @command{autoheader} an argument, it uses that file instead
3401 of @file{configure.ac} and writes the header file to the standard output
3402 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3403 argument of @option{-}, it reads the standard input instead of
3404 @file{configure.ac} and writes the header file to the standard output.
3406 @command{autoheader} accepts the following options:
3408 @table @option
3409 @item --help
3410 @itemx -h
3411 Print a summary of the command line options and exit.
3413 @item --version
3414 @itemx -V
3415 Print the version number of Autoconf and exit.
3417 @item --verbose
3418 @itemx -v
3419 Report processing steps.
3421 @item --debug
3422 @itemx -d
3423 Don't remove the temporary files.
3425 @item --force
3426 @itemx -f
3427 Remake the template file even if newer than its input files.
3429 @item --include=@var{dir}
3430 @itemx -I @var{dir}
3431 Append @var{dir} to the include path.  Multiple invocations accumulate.
3433 @item --prepend-include=@var{dir}
3434 @itemx -B @var{dir}
3435 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3437 @item --warnings=@var{category}
3438 @itemx -W @var{category}
3439 @evindex WARNINGS
3440 Report the warnings related to @var{category} (which can actually be a
3441 comma separated list).  Current categories include:
3443 @table @samp
3444 @item obsolete
3445 report the uses of obsolete constructs
3447 @item all
3448 report all the warnings
3450 @item none
3451 report none
3453 @item error
3454 treats warnings as errors
3456 @item no-@var{category}
3457 disable warnings falling into @var{category}
3458 @end table
3460 @end table
3464 @node Autoheader Macros
3465 @subsection Autoheader Macros
3466 @cindex Autoheader macros
3468 @command{autoheader} scans @file{configure.ac} and figures out which C
3469 preprocessor symbols it might define.  It knows how to generate
3470 templates for symbols defined by @code{AC_CHECK_HEADERS},
3471 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3472 symbol, you must define a template for it.  If there are missing
3473 templates, @command{autoheader} fails with an error message.
3475 The template for a @var{symbol} is created
3476 by @command{autoheader} from
3477 the @var{description} argument to an @code{AC_DEFINE};
3478 see @ref{Defining Symbols}.
3480 For special needs, you can use the following macros.
3483 @defmac AH_TEMPLATE (@var{key}, @var{description})
3484 @ahindex{TEMPLATE}
3485 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3486 generates standard templates just like @code{AC_DEFINE} when a
3487 @var{description} is given.
3489 For example:
3491 @example
3492 AH_TEMPLATE([CRAY_STACKSEG_END],
3493             [Define to one of _getb67, GETB67, getb67
3494              for Cray-2 and Cray-YMP systems.  This
3495              function is required for alloca.c support
3496              on those systems.])
3497 @end example
3499 @noindent
3500 generates the following template, with the description properly
3501 justified.
3503 @example
3504 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3505    Cray-YMP systems.  This function is required for alloca.c
3506    support on those systems.  */
3507 #undef CRAY_STACKSEG_END
3508 @end example
3509 @end defmac
3512 @defmac AH_VERBATIM (@var{key}, @var{template})
3513 @ahindex{VERBATIM}
3514 Tell @command{autoheader} to include the @var{template} as-is in the header
3515 template file.  This @var{template} is associated with the @var{key},
3516 which is used to sort all the different templates and guarantee their
3517 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3518 @end defmac
3521 @defmac AH_TOP (@var{text})
3522 @ahindex{TOP}
3523 Include @var{text} at the top of the header template file.
3524 @end defmac
3527 @defmac AH_BOTTOM (@var{text})
3528 @ahindex{BOTTOM}
3529 Include @var{text} at the bottom of the header template file.
3530 @end defmac
3533 Please note that @var{text} gets included ``verbatim'' to the template file,
3534 not to the resulting config header, so it can easily get mangled when the
3535 template is processed.  There is rarely a need for something other than
3537 @example
3538 AH_BOTTOM([#include <custom.h>])
3539 @end example
3543 @node Configuration Commands
3544 @section Running Arbitrary Configuration Commands
3545 @cindex Configuration commands
3546 @cindex Commands for configuration
3548 You can execute arbitrary commands before, during, and after
3549 @file{config.status} is run.  The three following macros accumulate the
3550 commands to run when they are called multiple times.
3551 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3552 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3554 @anchor{AC_CONFIG_COMMANDS}
3555 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3556 @acindex{CONFIG_COMMANDS}
3557 Specify additional shell commands to run at the end of
3558 @file{config.status}, and shell commands to initialize any variables
3559 from @command{configure}.  Associate the commands with @var{tag}.
3560 Since typically the @var{cmds} create a file, @var{tag} should
3561 naturally be the name of that file.  If needed, the directory hosting
3562 @var{tag} is created.  This macro is one of the instantiating macros;
3563 see @ref{Configuration Actions}.
3565 Here is an unrealistic example:
3566 @example
3567 fubar=42
3568 AC_CONFIG_COMMANDS([fubar],
3569                    [echo this is extra $fubar, and so on.],
3570                    [fubar=$fubar])
3571 @end example
3573 Here is a better one:
3574 @example
3575 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3576 @end example
3577 @end defmac
3579 The following two macros look similar, but in fact they are not of the same
3580 breed: they are executed directly by @file{configure}, so you cannot use
3581 @file{config.status} to rerun them.
3583 @c Yet it is good to leave them here.  The user sees them together and
3584 @c decides which best fits their needs.
3586 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3587 @acindex{CONFIG_COMMANDS_PRE}
3588 Execute the @var{cmds} right before creating @file{config.status}.
3590 This macro presents the last opportunity to call @code{AC_SUBST},
3591 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3592 @end defmac
3594 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3595 @acindex{CONFIG_COMMANDS_POST}
3596 Execute the @var{cmds} right after creating @file{config.status}.
3597 @end defmac
3602 @node Configuration Links
3603 @section Creating Configuration Links
3604 @cindex Configuration links
3605 @cindex Links for configuration
3607 You may find it convenient to create links whose destinations depend upon
3608 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3609 creation of relative symbolic links can be delicate when the package is
3610 built in a directory different from the source directory.
3612 @anchor{AC_CONFIG_LINKS}
3613 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3614   @ovar{init-cmds})
3615 @acindex{CONFIG_LINKS}
3616 @cindex Links
3617 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3618 the corresponding link name @var{dest}.  Makes a symbolic link if
3619 possible, otherwise a hard link if possible, otherwise a copy.  The
3620 @var{dest} and @var{source} names should be relative to the top level
3621 source or build directory.  This macro is one of the instantiating
3622 macros; see @ref{Configuration Actions}.
3624 For example, this call:
3626 @example
3627 AC_CONFIG_LINKS([host.h:config/$machine.h
3628                 object.h:config/$obj_format.h])
3629 @end example
3631 @noindent
3632 creates in the current directory @file{host.h} as a link to
3633 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3634 link to @file{@var{srcdir}/config/$obj_format.h}.
3636 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3637 impossible for @samp{config.status} to guess the links to establish.
3639 One can then run:
3640 @example
3641 ./config.status host.h object.h
3642 @end example
3643 @noindent
3644 to create the links.
3645 @end defmac
3649 @node Subdirectories
3650 @section Configuring Other Packages in Subdirectories
3651 @cindex Configure subdirectories
3652 @cindex Subdirectory configure
3654 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3655 makefiles in subdirectories.  However, @command{configure} scripts
3656 that control more than one independent package can use
3657 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3658 packages in subdirectories.
3660 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3661 @acindex{CONFIG_SUBDIRS}
3662 @ovindex subdirs
3663 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3664 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3665 be a literal, i.e., please do not use:
3667 @example
3668 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3669 if test "x$package_foo_enabled" = xyes; then
3670   my_subdirs="$my_subdirs foo"
3672 AC_CONFIG_SUBDIRS([$my_subdirs])
3673 @end example
3675 @noindent
3676 because this prevents @samp{./configure --help=recursive} from
3677 displaying the options of the package @code{foo}.  Instead, you should
3678 write:
3680 @example
3681 if test "x$package_foo_enabled" = xyes; then
3682   AC_CONFIG_SUBDIRS([foo])
3684 @end example
3686 If a given @var{dir} is not found at @command{configure} run time, a
3687 warning is reported; if the subdirectory is optional, write:
3689 @example
3690 if test -d "$srcdir/foo"; then
3691   AC_CONFIG_SUBDIRS([foo])
3693 @end example
3695 @c NB: Yes, below we mean configure.in, not configure.ac.
3696 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3697 of @command{configure}.  This is for packages that might use a
3698 non-Autoconf script @command{Configure}, which can't be called through a
3699 wrapper @command{configure} since it would be the same file on
3700 case-insensitive file systems.  Likewise, if a @var{dir} contains
3701 @file{configure.in} but no @command{configure}, the Cygnus
3702 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3704 The subdirectory @command{configure} scripts are given the same command
3705 line options that were given to this @command{configure} script, with minor
3706 changes if needed, which include:
3708 @itemize @minus
3709 @item
3710 adjusting a relative name for the cache file;
3712 @item
3713 adjusting a relative name for the source directory;
3715 @item
3716 propagating the current value of @code{$prefix}, including if it was
3717 defaulted, and if the default values of the top level and of the subdirectory
3718 @file{configure} differ.
3719 @end itemize
3721 This macro also sets the output variable @code{subdirs} to the list of
3722 directories @samp{@var{dir} @dots{}}.  Make rules can use
3723 this variable to determine which subdirectories to recurse into.
3725 This macro may be called multiple times.
3726 @end defmac
3728 @node Default Prefix
3729 @section Default Prefix
3730 @cindex Install prefix
3731 @cindex Prefix for install
3733 By default, @command{configure} sets the prefix for files it installs to
3734 @file{/usr/local}.  The user of @command{configure} can select a different
3735 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3736 There are two ways to change the default: when creating
3737 @command{configure}, and when running it.
3739 Some software packages might want to install in a directory other than
3740 @file{/usr/local} by default.  To accomplish that, use the
3741 @code{AC_PREFIX_DEFAULT} macro.
3743 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3744 @acindex{PREFIX_DEFAULT}
3745 Set the default installation prefix to @var{prefix} instead of
3746 @file{/usr/local}.
3747 @end defmac
3749 It may be convenient for users to have @command{configure} guess the
3750 installation prefix from the location of a related program that they
3751 have already installed.  If you wish to do that, you can call
3752 @code{AC_PREFIX_PROGRAM}.
3754 @anchor{AC_PREFIX_PROGRAM}
3755 @defmac AC_PREFIX_PROGRAM (@var{program})
3756 @acindex{PREFIX_PROGRAM}
3757 If the user did not specify an installation prefix (using the
3758 @option{--prefix} option), guess a value for it by looking for
3759 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3760 is found, set the prefix to the parent of the directory containing
3761 @var{program}, else default the prefix as described above
3762 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3763 @var{program} is @code{gcc} and the @env{PATH} contains
3764 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3765 @end defmac
3769 @c ======================================================== Existing tests
3771 @node Existing Tests
3772 @chapter Existing Tests
3774 These macros test for particular system features that packages might
3775 need or want to use.  If you need to test for a kind of feature that
3776 none of these macros check for, you can probably do it by calling
3777 primitive test macros with appropriate arguments (@pxref{Writing
3778 Tests}).
3780 These tests print messages telling the user which feature they're
3781 checking for, and what they find.  They cache their results for future
3782 @command{configure} runs (@pxref{Caching Results}).
3784 Some of these macros set output variables.  @xref{Makefile
3785 Substitutions}, for how to get their values.  The phrase ``define
3786 @var{name}'' is used below as a shorthand to mean ``define the C
3787 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3788 Symbols}, for how to get those symbol definitions into your program.
3790 @menu
3791 * Common Behavior::             Macros' standard schemes
3792 * Alternative Programs::        Selecting between alternative programs
3793 * Files::                       Checking for the existence of files
3794 * Libraries::                   Library archives that might be missing
3795 * Library Functions::           C library functions that might be missing
3796 * Header Files::                Header files that might be missing
3797 * Declarations::                Declarations that may be missing
3798 * Structures::                  Structures or members that might be missing
3799 * Types::                       Types that might be missing
3800 * Compilers and Preprocessors::  Checking for compiling programs
3801 * System Services::             Operating system services
3802 * Posix Variants::              Special kludges for specific Posix variants
3803 * Erlang Libraries::            Checking for the existence of Erlang libraries
3804 @end menu
3806 @node Common Behavior
3807 @section Common Behavior
3808 @cindex Common autoconf behavior
3810 Much effort has been expended to make Autoconf easy to learn.  The most
3811 obvious way to reach this goal is simply to enforce standard interfaces
3812 and behaviors, avoiding exceptions as much as possible.  Because of
3813 history and inertia, unfortunately, there are still too many exceptions
3814 in Autoconf; nevertheless, this section describes some of the common
3815 rules.
3817 @menu
3818 * Standard Symbols::            Symbols defined by the macros
3819 * Default Includes::            Includes used by the generic macros
3820 @end menu
3822 @node Standard Symbols
3823 @subsection Standard Symbols
3824 @cindex Standard symbols
3826 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3827 their test transform their @var{argument} values to a standard alphabet.
3828 First, @var{argument} is converted to upper case and any asterisks
3829 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3830 that are not alphanumeric are converted to underscores.
3832 For instance,
3834 @example
3835 AC_CHECK_TYPES([struct $Expensive*])
3836 @end example
3838 @noindent
3839 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3840 succeeds.
3843 @node Default Includes
3844 @subsection Default Includes
3845 @cindex Default includes
3846 @cindex Includes, default
3848 Several tests depend upon a set of header files.  Since these headers
3849 are not universally available, tests actually have to provide a set of
3850 protected includes, such as:
3852 @example
3853 @group
3854 #ifdef TIME_WITH_SYS_TIME
3855 # include <sys/time.h>
3856 # include <time.h>
3857 #else
3858 # ifdef HAVE_SYS_TIME_H
3859 #  include <sys/time.h>
3860 # else
3861 #  include <time.h>
3862 # endif
3863 #endif
3864 @end group
3865 @end example
3867 @noindent
3868 Unless you know exactly what you are doing, you should avoid using
3869 unconditional includes, and check the existence of the headers you
3870 include beforehand (@pxref{Header Files}).
3872 Most generic macros use the following macro to provide the default set
3873 of includes:
3875 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3876 @acindex{INCLUDES_DEFAULT}
3877 Expand to @var{include-directives} if defined, otherwise to:
3879 @example
3880 @group
3881 #include <stdio.h>
3882 #ifdef HAVE_SYS_TYPES_H
3883 # include <sys/types.h>
3884 #endif
3885 #ifdef HAVE_SYS_STAT_H
3886 # include <sys/stat.h>
3887 #endif
3888 #if defined STDC_HEADERS || defined HAVE_STDLIB_H
3889 # include <stdlib.h>
3890 #endif
3891 #include <stddef.h>
3892 #ifdef HAVE_STRING_H
3893 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3894 #  include <memory.h>
3895 # endif
3896 # include <string.h>
3897 #endif
3898 #ifdef HAVE_STRINGS_H
3899 # include <strings.h>
3900 #endif
3901 #ifdef HAVE_INTTYPES_H
3902 # include <inttypes.h>
3903 #endif
3904 #ifdef HAVE_STDINT_H
3905 # include <stdint.h>
3906 #endif
3907 #ifdef HAVE_UNISTD_H
3908 # include <unistd.h>
3909 #endif
3910 @end group
3911 @end example
3913 If the default includes are used, then check for the presence of these
3914 headers and their compatibility, i.e., you don't need to run
3915 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3917 These headers are checked for in the same order as they are included.
3918 For instance, on some systems @file{string.h} and @file{strings.h} both
3919 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3920 @code{HAVE_STRINGS_H}.
3921 @end defmac
3923 @node Alternative Programs
3924 @section Alternative Programs
3925 @cindex Programs, checking
3927 These macros check for the presence or behavior of particular programs.
3928 They are used to choose between several alternative programs and to
3929 decide what to do once one has been chosen.  If there is no macro
3930 specifically defined to check for a program you need, and you don't need
3931 to check for any special properties of it, then you can use one of the
3932 general program-check macros.
3934 @menu
3935 * Particular Programs::         Special handling to find certain programs
3936 * Generic Programs::            How to find other programs
3937 @end menu
3939 @node Particular Programs
3940 @subsection Particular Program Checks
3942 These macros check for particular programs---whether they exist, and
3943 in some cases whether they support certain features.
3945 @defmac AC_PROG_AWK
3946 @acindex{PROG_AWK}
3947 @ovindex AWK
3948 @caindex prog_AWK
3949 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3950 order, and set output variable @code{AWK} to the first one that is found.
3951 It tries @code{gawk} first because that is reported to be the
3952 best implementation.  The result can be overridden by setting the
3953 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3955 Using this macro is sufficient to avoid the pitfalls of traditional
3956 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3957 @end defmac
3959 @defmac AC_PROG_GREP
3960 @acindex{PROG_GREP}
3961 @ovindex GREP
3962 @caindex prog_GREP
3963 Look for the best available @code{grep} or @code{ggrep} that accepts the
3964 longest input lines possible, and that supports multiple @option{-e} options.
3965 Set the output variable @code{GREP} to whatever is chosen.
3966 @xref{grep, , Limitations of Usual Tools}, for more information about
3967 portability problems with the @command{grep} command family.  The result
3968 can be overridden by setting the @code{GREP} variable and is cached in the
3969 @code{ac_cv_path_GREP} variable.
3970 @end defmac
3972 @defmac AC_PROG_EGREP
3973 @acindex{PROG_EGREP}
3974 @ovindex EGREP
3975 @caindex prog_EGREP
3976 Check whether @code{$GREP -E} works, or else look for the best available
3977 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3978 Set the output variable @code{EGREP} to whatever is chosen.  The result
3979 can be overridden by setting the @code{EGREP} variable and is cached in the
3980 @code{ac_cv_path_EGREP} variable.
3981 @end defmac
3983 @defmac AC_PROG_FGREP
3984 @acindex{PROG_FGREP}
3985 @ovindex FGREP
3986 @caindex prog_FGREP
3987 Check whether @code{$GREP -F} works, or else look for the best available
3988 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3989 Set the output variable @code{FGREP} to whatever is chosen.  The result
3990 can be overridden by setting the @code{FGREP} variable and is cached in the
3991 @code{ac_cv_path_FGREP} variable.
3992 @end defmac
3994 @defmac AC_PROG_INSTALL
3995 @acindex{PROG_INSTALL}
3996 @ovindex INSTALL
3997 @ovindex INSTALL_PROGRAM
3998 @ovindex INSTALL_DATA
3999 @ovindex INSTALL_SCRIPT
4000 @caindex path_install
4001 Set output variable @code{INSTALL} to the name of a BSD-compatible
4002 @command{install} program, if one is found in the current @env{PATH}.
4003 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4004 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4005 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4006 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4007 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4009 @samp{@@INSTALL@@} is special, as its value may vary for different
4010 configuration files.
4012 This macro screens out various instances of @command{install} known not to
4013 work.  It prefers to find a C program rather than a shell script, for
4014 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4015 but that name is obsolete because some @command{make} programs have a rule
4016 that creates @file{install} from it if there is no makefile.  Further, this
4017 macro requires @command{install} to be able to install multiple files into a
4018 target directory in a single invocation.
4020 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4021 you use @code{AC_PROG_INSTALL}, you must include either
4022 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4023 @command{configure} produces an error message saying it can't find
4024 them---even if the system you're on has a good @command{install} program.
4025 This check is a safety measure to prevent you from accidentally leaving
4026 that file out, which would prevent your package from installing on
4027 systems that don't have a BSD-compatible @command{install} program.
4029 If you need to use your own installation program because it has features
4030 not found in standard @command{install} programs, there is no reason to use
4031 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4032 @file{Makefile.in} files.
4034 The result of the test can be overridden by setting the variable
4035 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4036 @end defmac
4038 @defmac AC_PROG_MKDIR_P
4039 @acindex{PROG_MKDIR_P}
4040 @ovindex MKDIR_P
4041 @caindex path_mkdir
4042 Set output variable @code{MKDIR_P} to a program that ensures that for
4043 each argument, a directory named by this argument exists, creating it
4044 and its parent directories if needed, and without race conditions when
4045 two instances of the program attempt to make the same directory at
4046 nearly the same time.
4048 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4049 falls back on invoking @command{install-sh} with the @option{-d} option,
4050 so your package should
4051 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4052 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4053 is vulnerable to race conditions, so if you want to support parallel
4054 installs from
4055 different packages into the same directory you need to make sure you
4056 have an up-to-date @file{install-sh}.  In particular, be careful about
4057 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4059 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4060 in M4sh}), but it sets an output variable intended for use in other
4061 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4062 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4063 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4064 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4065 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4066 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4067 Finally, @code{AS_MKDIR_P} does not check for race condition
4068 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4070 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4071 configuration files.
4073 The result of the test can be overridden by setting the variable
4074 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4075 @end defmac
4077 @anchor{AC_PROG_LEX}
4078 @defmac AC_PROG_LEX
4079 @acindex{PROG_LEX}
4080 @ovindex LEX
4081 @ovindex LEXLIB
4082 @cvindex YYTEXT_POINTER
4083 @ovindex LEX_OUTPUT_ROOT
4084 @caindex prog_LEX
4085 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4086 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4087 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4088 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4089 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4090 alongside the source @file{file.l}, this default allows users without a
4091 lexer generator to still build the package even if the timestamp for
4092 @file{file.l} is inadvertently changed.
4094 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4095 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4096 the base of the file name that the lexer generates; usually
4097 @file{lex.yy}, but sometimes something else.  These results vary
4098 according to whether @code{lex} or @code{flex} is being used.
4100 You are encouraged to use Flex in your sources, since it is both more
4101 pleasant to use than plain Lex and the C source it produces is portable.
4102 In order to ensure portability, however, you must either provide a
4103 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4104 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4105 statement in the scanner's source.  Once this done, the scanner is
4106 portable (unless @emph{you} felt free to use nonportable constructs) and
4107 does not depend on any library.  In this case, and in this case only, it
4108 is suggested that you use this Autoconf snippet:
4110 @example
4111 AC_PROG_LEX
4112 if test "x$LEX" != xflex; then
4113   LEX="$SHELL $missing_dir/missing flex"
4114   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4115   AC_SUBST([LEXLIB], [''])
4117 @end example
4119 The shell script @command{missing} can be found in the Automake
4120 distribution.
4122 Remember that the user may have supplied an alternate location in
4123 @env{LEX}, so if Flex is required, it is better to check that the user
4124 provided something sufficient by parsing the output of @samp{$LEX
4125 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4127 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4128 (indirectly) this macro twice, which causes an annoying but benign
4129 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4130 of Automake will fix this issue; meanwhile, just ignore this message.
4132 As part of running the test, this macro may delete any file in the
4133 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4135 The result of this test can be influenced by setting the variable
4136 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4137 @end defmac
4139 @anchor{AC_PROG_LN_S}
4140 @defmac AC_PROG_LN_S
4141 @acindex{PROG_LN_S}
4142 @ovindex LN_S
4143 If @samp{ln -s} works on the current file system (the operating system
4144 and file system support symbolic links), set the output variable
4145 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4146 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4148 If you make a link in a directory other than the current directory, its
4149 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4150 create links using @samp{$(LN_S)}, either find out which form is used
4151 and adjust the arguments, or always invoke @code{ln} in the directory
4152 where the link is to be created.
4154 In other words, it does not work to do:
4155 @example
4156 $(LN_S) foo /x/bar
4157 @end example
4159 Instead, do:
4161 @example
4162 (cd /x && $(LN_S) foo bar)
4163 @end example
4164 @end defmac
4166 @defmac AC_PROG_RANLIB
4167 @acindex{PROG_RANLIB}
4168 @ovindex RANLIB
4169 @c @caindex prog_RANLIB
4170 @c @caindex prog_ac_ct_RANLIB
4171 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4172 is found, and otherwise to @samp{:} (do nothing).
4173 @end defmac
4175 @defmac AC_PROG_SED
4176 @acindex{PROG_SED}
4177 @ovindex SED
4178 @caindex path_SED
4179 Set output variable @code{SED} to a Sed implementation that conforms to
4180 Posix and does not have arbitrary length limits.  Report an error if no
4181 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4182 information about portability problems with Sed.
4184 The result of this test can be overridden by setting the @code{SED} variable
4185 and is cached in the @code{ac_cv_path_SED} variable.
4186 @end defmac
4188 @defmac AC_PROG_YACC
4189 @acindex{PROG_YACC}
4190 @evindex YACC
4191 @evindex YFLAGS
4192 @ovindex YACC
4193 @caindex prog_YACC
4194 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4195 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4196 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4197 The result of this test can be influenced by setting the variable
4198 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4199 @end defmac
4201 @node Generic Programs
4202 @subsection Generic Program and File Checks
4204 These macros are used to find programs not covered by the ``particular''
4205 test macros.  If you need to check the behavior of a program as well as
4206 find out whether it is present, you have to write your own test for it
4207 (@pxref{Writing Tests}).  By default, these macros use the environment
4208 variable @env{PATH}.  If you need to check for a program that might not
4209 be in the user's @env{PATH}, you can pass a modified path to use
4210 instead, like this:
4212 @example
4213 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4214              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4215 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4216 @end example
4218 You are strongly encouraged to declare the @var{variable} passed to
4219 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4220 @code{AC_ARG_VAR}, for more details.
4222 @anchor{AC_CHECK_PROG}
4223 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4224   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4225   @ovar{reject})
4226 @acindex{CHECK_PROG}
4227 @caindex prog_@var{variable}
4228 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4229 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4230 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4231 absolute file name) even if it is the first found in the search path; in
4232 that case, set @var{variable} using the absolute file name of the
4233 @var{prog-to-check-for} found that is not @var{reject}.  If
4234 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4235 @var{variable}.  The result of this test can be overridden by setting the
4236 @var{variable} variable or the cache variable
4237 @code{ac_cv_prog_@var{variable}}.
4238 @end defmac
4240 @anchor{AC_CHECK_PROGS}
4241 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4242   @ovar{value-if-not-found}, @dvar{path, $PATH})
4243 @acindex{CHECK_PROGS}
4244 @caindex prog_@var{variable}
4245 Check for each program in the blank-separated list
4246 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4247 @var{variable} to the name of that program.  Otherwise, continue
4248 checking the next program in the list.  If none of the programs in the
4249 list are found, set @var{variable} to @var{value-if-not-found}; if
4250 @var{value-if-not-found} is not specified, the value of @var{variable}
4251 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4252 this test can be overridden by setting the @var{variable} variable or the
4253 cache variable @code{ac_cv_prog_@var{variable}}.
4254 @end defmac
4256 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4257   @ovar{value-if-not-found}, @dvar{path, $PATH})
4258 @acindex{CHECK_TARGET_TOOL}
4259 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4260 with a prefix of the target type as determined by
4261 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4262 If the tool cannot be found with a prefix, and if the build and target
4263 types are equal, then it is also searched for without a prefix.
4265 As noted in @ref{Specifying Target Triplets}, the
4266 target is rarely specified, because most of the time it is the same
4267 as the host: it is the type of system for which any compiler tool in
4268 the package produces code.  What this macro looks for is,
4269 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4270 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4271 uses to produce objects, archives or executables}.
4272 @end defmac
4274 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4275   @ovar{value-if-not-found}, @dvar{path, $PATH})
4276 @acindex{CHECK_TOOL}
4277 @c @caindex prog_@var{VARIABLE}
4278 @c @caindex prog_ac_ct_@var{VARIABLE}
4279 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4280 with a prefix of the host type as specified by @option{--host}, followed by a
4281 dash.  For example, if the user runs
4282 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4283 @example
4284 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4285 @end example
4286 @noindent
4287 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4288 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4289 @var{path}, or to @samp{:} if neither program exists.
4291 When cross-compiling, this macro will issue a warning if no program
4292 prefixed with the host type could be found.
4293 For more information, see @ref{Specifying Target Triplets}.
4294 @end defmac
4296 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4297   @ovar{value-if-not-found}, @dvar{path, $PATH})
4298 @acindex{CHECK_TARGET_TOOLS}
4299 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4300 @var{progs-to-check-for} are checked with a prefix of the target type as
4301 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4302 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4303 prefix, and if the build and target types are equal, then the first one
4304 without a prefix is used.  If a tool is found, set @var{variable} to
4305 the name of that program.  If none of the tools in the list are found,
4306 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4307 is not specified, the value of @var{variable} is not changed.  Calls
4308 @code{AC_SUBST} for @var{variable}.
4309 @end defmac
4311 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4312   @ovar{value-if-not-found}, @dvar{path, $PATH})
4313 @acindex{CHECK_TOOLS}
4314 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4315 @var{progs-to-check-for} are checked with a prefix of the host type as
4316 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4317 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4318 prefix, then the first one without a prefix is used.  If a tool is found,
4319 set @var{variable} to the name of that program.  If none of the tools in
4320 the list are found, set @var{variable} to @var{value-if-not-found}; if
4321 @var{value-if-not-found} is not specified, the value of @var{variable}
4322 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4324 When cross-compiling, this macro will issue a warning if no program
4325 prefixed with the host type could be found.
4326 For more information, see @ref{Specifying Target Triplets}.
4327 @end defmac
4329 @anchor{AC_PATH_PROG}
4330 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4331   @ovar{value-if-not-found}, @dvar{path, $PATH})
4332 @acindex{PATH_PROG}
4333 @caindex path_@var{variable}
4334 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4335 name of @var{prog-to-check-for} if found.  The result of this test
4336 can be overridden by setting the @var{variable} variable.  A positive
4337 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4338 variable.
4339 @end defmac
4341 @anchor{AC_PATH_PROGS}
4342 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4343   @ovar{value-if-not-found}, @dvar{path, $PATH})
4344 @acindex{PATH_PROGS}
4345 @caindex path_@var{variable}
4346 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4347 are found, set @var{variable} to the absolute name of the program
4348 found.  The result of this test can be overridden by setting the
4349 @var{variable} variable.  A positive result of this test is cached in
4350 the @code{ac_cv_path_@var{variable}} variable.
4351 @end defmac
4353 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4354   @var{progs-to-check-for}, @var{feature-test}, @
4355   @ovar{action-if-not-found}, @dvar{path, $PATH})
4356 @acindex{PATH_PROGS_FEATURE_CHECK}
4357 @caindex path_@var{variable}
4358 @vrindex ac_path_@var{variable}
4359 @vrindex ac_path_@var{variable}_found
4360 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4361 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4362 its value.  Otherwise, check for each program in the blank-separated
4363 list @var{progs-to-check-for} existing in @var{path}.  For each program
4364 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4365 set to the absolute name of the candidate program.  If no invocation of
4366 @var{feature-test} sets the shell variable
4367 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4368 executed.  @var{feature-test} will be run even when
4369 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4370 choose a better candidate found later in @var{path}; to accept the
4371 current setting and bypass all further checks, @var{feature-test} can
4372 execute @code{ac_path_@var{variable}_found=:}.
4374 Note that this macro has some subtle differences from
4375 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4376 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4377 particular, @var{variable} is not set to the final value of
4378 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4379 run.  Also, on failure, any action can be performed, whereas
4380 @code{AC_CHECK_PROGS} only performs
4381 @code{@var{variable}=@var{value-if-not-found}}.
4383 Here is an example, similar to what Autoconf uses in its own configure
4384 script.  It will search for an implementation of @command{m4} that
4385 supports the @code{indir} builtin, even if it goes by the name
4386 @command{gm4} or is not the first implementation on @env{PATH}.
4388 @example
4389 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4390   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4391     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4392       test "x$m4out" = x0 \
4393       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4394     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4395 AC_SUBST([M4], [$ac_cv_path_M4])
4396 @end example
4397 @end defmac
4399 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4400   @ovar{value-if-not-found}, @dvar{path, $PATH})
4401 @acindex{PATH_TARGET_TOOL}
4402 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4403 name of the program if it is found.
4404 @end defmac
4406 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4407   @ovar{value-if-not-found}, @dvar{path, $PATH})
4408 @acindex{PATH_TOOL}
4409 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4410 name of the program if it is found.
4412 When cross-compiling, this macro will issue a warning if no program
4413 prefixed with the host type could be found.
4414 For more information, see @ref{Specifying Target Triplets}.
4415 @end defmac
4418 @node Files
4419 @section Files
4420 @cindex File, checking
4422 You might also need to check for the existence of files.  Before using
4423 these macros, ask yourself whether a runtime test might not be a better
4424 solution.  Be aware that, like most Autoconf macros, they test a feature
4425 of the host machine, and therefore, they die when cross-compiling.
4427 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4428   @ovar{action-if-not-found})
4429 @acindex{CHECK_FILE}
4430 @caindex file_@var{file}
4431 Check whether file @var{file} exists on the native system.  If it is
4432 found, execute @var{action-if-found}, otherwise do
4433 @var{action-if-not-found}, if given.  The result of this test is cached
4434 in the @code{ac_cv_file_@var{file}} variable, with characters not
4435 suitable for a variable name mapped to underscores.
4436 @end defmac
4438 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4439   @ovar{action-if-not-found})
4440 @acindex{CHECK_FILES}
4441 @caindex file_@var{file}
4442 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4443 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4444 for each file found.  The results of each test are cached in the
4445 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4446 a variable name mapped to underscores.
4447 @end defmac
4450 @node Libraries
4451 @section Library Files
4452 @cindex Library, checking
4454 The following macros check for the presence of certain C, C++, Fortran,
4455 or Go library archive files.
4457 @anchor{AC_CHECK_LIB}
4458 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4459   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4460 @acindex{CHECK_LIB}
4461 @caindex lib_@var{library}_@var{function}
4462 Test whether the library @var{library} is available by trying to link
4463 a test program that calls function @var{function} with the library.
4464 @var{function} should be a function provided by the library.
4465 Use the base
4466 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4467 the @var{library} argument.
4469 @var{action-if-found} is a list of shell commands to run if the link
4470 with the library succeeds; @var{action-if-not-found} is a list of shell
4471 commands to run if the link fails.  If @var{action-if-found} is not
4472 specified, the default action prepends @option{-l@var{library}} to
4473 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4474 capitals).  This macro is intended to support building @code{LIBS} in
4475 a right-to-left (least-dependent to most-dependent) fashion such that
4476 library dependencies are satisfied as a natural side effect of
4477 consecutive tests.  Linkers are sensitive to library ordering
4478 so the order in which @code{LIBS} is generated is important to reliable
4479 detection of libraries.
4481 If linking with @var{library} results in unresolved symbols that would
4482 be resolved by linking with additional libraries, give those libraries
4483 as the @var{other-libraries} argument, separated by spaces:
4484 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4485 that @var{library} is present, because linking the test program can
4486 fail with unresolved symbols.  The @var{other-libraries} argument
4487 should be limited to cases where it is desirable to test for one library
4488 in the presence of another that is not already in @code{LIBS}.
4490 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4491 in some common cases.  Many standard functions like @code{gethostbyname}
4492 appear in the standard C library on some hosts, and in special libraries
4493 like @code{nsl} on other hosts.  On some hosts the special libraries
4494 contain variant implementations that you may not want to use.  These
4495 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4496 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4498 The result of this test is cached in the
4499 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4500 @end defmac
4502 @anchor{AC_SEARCH_LIBS}
4503 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4504   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4505 @acindex{SEARCH_LIBS}
4506 @caindex search_@var{function}
4507 Search for a library defining @var{function} if it's not already
4508 available.  This equates to calling
4509 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4510 no libraries, then for each library listed in @var{search-libs}.
4512 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4513 to contain @var{function}, and run @var{action-if-found}.  If the
4514 function is not found, run @var{action-if-not-found}.
4516 If linking with @var{library} results in unresolved symbols that would
4517 be resolved by linking with additional libraries, give those libraries
4518 as the @var{other-libraries} argument, separated by spaces:
4519 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4520 that @var{function} is present, because linking the test program
4521 always fails with unresolved symbols.
4523 The result of this test is cached in the
4524 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4525 @var{function} is already available, as @samp{no} if no library
4526 containing @var{function} was found, otherwise as the
4527 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4528 @end defmac
4532 @node Library Functions
4533 @section Library Functions
4535 The following macros check for particular C library functions.
4536 If there is no macro specifically defined to check for a function you need,
4537 and you don't need to check for any special properties of
4538 it, then you can use one of the general function-check macros.
4540 @menu
4541 * Function Portability::        Pitfalls with usual functions
4542 * Particular Functions::        Special handling to find certain functions
4543 * Generic Functions::           How to find other functions
4544 @end menu
4546 @node Function Portability
4547 @subsection Portability of C Functions
4548 @cindex Portability of C functions
4549 @cindex C function portability
4551 Most usual functions can either be missing, or be buggy, or be limited
4552 on some architectures.  This section tries to make an inventory of these
4553 portability issues.  By definition, this list always requires
4554 additions.  A much more complete list is maintained by the Gnulib
4555 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4556 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4557 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4558 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4559 help us keep the gnulib list as complete as possible.
4561 @table @asis
4562 @item @code{exit}
4563 @c @fuindex exit
4564 @prindex @code{exit}
4565 On ancient hosts, @code{exit} returned @code{int}.
4566 This is because @code{exit} predates @code{void}, and there was a long
4567 tradition of it returning @code{int}.
4569 On current hosts, the problem more likely is that @code{exit} is not
4570 declared, due to C++ problems of some sort or another.  For this reason
4571 we suggest that test programs not invoke @code{exit}, but return from
4572 @code{main} instead.
4574 @item @code{free}
4575 @c @fuindex free
4576 @prindex @code{free}
4577 The C standard says a call @code{free (NULL)} does nothing, but
4578 some old systems don't support this (e.g., NextStep).
4580 @item @code{isinf}
4581 @itemx @code{isnan}
4582 @c @fuindex isinf
4583 @c @fuindex isnan
4584 @prindex @code{isinf}
4585 @prindex @code{isnan}
4586 In C99 and later, @code{isinf} and @code{isnan} are
4587 macros.  On some systems just macros are available
4588 (e.g., HP-UX and Solaris 10), on
4589 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4590 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4591 these functions are declared in nonstandard headers like
4592 @code{<sunmath.h>} and defined in non-default libraries like
4593 @option{-lm} or @option{-lsunmath}.
4595 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4596 @code{long double} arguments, but pre-C99 systems that use functions
4597 typically assume @code{double} arguments.  On such a system,
4598 @code{isinf} incorrectly returns true for a finite @code{long double}
4599 argument that is outside the range of @code{double}.
4601 The best workaround for these issues is to use gnulib modules
4602 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4603 solution involves code like the following.
4605 @smallexample
4606 #include <math.h>
4608 #ifndef isnan
4609 # define isnan(x) \
4610     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4611      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4612      : isnan_f (x))
4613 static inline int isnan_f  (float       x) @{ return x != x; @}
4614 static inline int isnan_d  (double      x) @{ return x != x; @}
4615 static inline int isnan_ld (long double x) @{ return x != x; @}
4616 #endif
4618 #ifndef isinf
4619 # define isinf(x) \
4620     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4621      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4622      : isinf_f (x))
4623 static inline int isinf_f  (float       x)
4624 @{ return !isnan (x) && isnan (x - x); @}
4625 static inline int isinf_d  (double      x)
4626 @{ return !isnan (x) && isnan (x - x); @}
4627 static inline int isinf_ld (long double x)
4628 @{ return !isnan (x) && isnan (x - x); @}
4629 #endif
4630 @end smallexample
4632 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4633 compilers that lack the @code{inline} keyword.  Some optimizing
4634 compilers mishandle these definitions, but systems with that bug
4635 typically have many other floating point corner-case compliance problems
4636 anyway, so it's probably not worth worrying about.
4638 @item @code{malloc}
4639 @c @fuindex malloc
4640 @prindex @code{malloc}
4641 The C standard says a call @code{malloc (0)} is implementation
4642 dependent.  It can return either @code{NULL} or a new non-null pointer.
4643 The latter is more common (e.g., the GNU C Library) but is by
4644 no means universal.  @code{AC_FUNC_MALLOC}
4645 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4647 @item @code{putenv}
4648 @c @fuindex putenv
4649 @prindex @code{putenv}
4650 Posix prefers @code{setenv} to @code{putenv}; among other things,
4651 @code{putenv} is not required of all Posix implementations, but
4652 @code{setenv} is.
4654 Posix specifies that @code{putenv} puts the given string directly in
4655 @code{environ}, but some systems make a copy of it instead (e.g.,
4656 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4657 not free it, causing a memory leak (e.g., FreeBSD 4).
4659 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4660 environment, but this is not standard usage and it dumps core
4661 on some systems (e.g., AIX).
4663 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4664 environment, rather than inserting it with an empty value.
4666 @item @code{realloc}
4667 @c @fuindex realloc
4668 @prindex @code{realloc}
4669 The C standard says a call @code{realloc (NULL, size)} is equivalent
4670 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4671 NextStep).
4673 @item @code{signal} handler
4674 @c @fuindex signal
4675 @prindex @code{signal}
4676 @prindex @code{sigaction}
4677 Normally @code{signal} takes a handler function with a return type of
4678 @code{void}, but some old systems required @code{int} instead.  Any
4679 actual @code{int} value returned is not used; this is only a
4680 difference in the function prototype demanded.
4682 All systems we know of in current use return @code{void}.  The
4683 @code{int} was to support K&R C, where of course @code{void} is not
4684 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4685 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4686 all cases.
4688 In most cases, it is more robust to use @code{sigaction} when it is
4689 available, rather than @code{signal}.
4691 @item @code{snprintf}
4692 @c @fuindex snprintf
4693 @prindex @code{snprintf}
4694 @c @fuindex vsnprintf
4695 @prindex @code{vsnprintf}
4696 In C99 and later, if the output array isn't big enough
4697 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4698 truncate the output and return the number of bytes that ought to have
4699 been produced.  Some older systems return the truncated length (e.g.,
4700 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4701 (e.g., earlier GNU C Library versions), and some the buffer
4702 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4703 older systems ignore the length and overrun the buffer (e.g., 64-bit
4704 Solaris 7).
4706 @item @code{sprintf}
4707 @c @fuindex sprintf
4708 @prindex @code{sprintf}
4709 @c @fuindex vsprintf
4710 @prindex @code{vsprintf}
4711 The C standard says @code{sprintf} and @code{vsprintf} return the
4712 number of bytes written.  On some ancient systems (SunOS 4 for
4713 instance) they return the buffer pointer instead, but these no
4714 longer need to be worried about.
4716 @item @code{sscanf}
4717 @c @fuindex sscanf
4718 @prindex @code{sscanf}
4719 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4720 that its
4721 input string be writable (though it doesn't actually change it).  This
4722 can be a problem when using @command{gcc} since it normally puts
4723 constant strings in read-only memory (@pxref{Incompatibilities,
4724 Incompatibilities of GCC, , gcc, Using and
4725 Porting the GNU Compiler Collection}).  Apparently in some cases even
4726 having format strings read-only can be a problem.
4728 @item @code{strerror_r}
4729 @c @fuindex strerror_r
4730 @prindex @code{strerror_r}
4731 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4732 systems (e.g., GNU C Library version 2.2.4) provide a
4733 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4734 can detect which is in use (@pxref{Particular Functions}).
4736 @item @code{strnlen}
4737 @c @fuindex strnlen
4738 @prindex @code{strnlen}
4739 AIX 4.3 provides a broken version which produces the
4740 following results:
4742 @example
4743 strnlen ("foobar", 0) = 0
4744 strnlen ("foobar", 1) = 3
4745 strnlen ("foobar", 2) = 2
4746 strnlen ("foobar", 3) = 1
4747 strnlen ("foobar", 4) = 0
4748 strnlen ("foobar", 5) = 6
4749 strnlen ("foobar", 6) = 6
4750 strnlen ("foobar", 7) = 6
4751 strnlen ("foobar", 8) = 6
4752 strnlen ("foobar", 9) = 6
4753 @end example
4755 @item @code{sysconf}
4756 @c @fuindex sysconf
4757 @prindex @code{sysconf}
4758 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4759 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4760 @code{#ifdef}.
4762 @item @code{unlink}
4763 @c @fuindex unlink
4764 @prindex @code{unlink}
4765 The Posix spec says that @code{unlink} causes the given file to be
4766 removed only after there are no more open file handles for it.  Some
4767 non-Posix hosts have trouble with this requirement, though,
4768 and some DOS variants even corrupt the file system.
4770 @item @code{unsetenv}
4771 @c @fuindex unsetenv
4772 @prindex @code{unsetenv}
4773 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4774 can be removed with a call @code{putenv ("FOO=")}, as described under
4775 @code{putenv} above.
4777 @item @code{va_copy}
4778 @c @fuindex va_copy
4779 @prindex @code{va_copy}
4780 C99 and later provide @code{va_copy} for copying
4781 @code{va_list} variables.  It may be available in older environments
4782 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4783 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4784 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4785 portability.
4787 @item @code{va_list}
4788 @c @fuindex va_list
4789 @prindex @code{va_list}
4790 @code{va_list} is not necessarily just a pointer.  It can be a
4791 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4792 not portable.  Or it can be an array (e.g., @command{gcc} in some
4793 PowerPC configurations), which means as a function parameter it can be
4794 effectively call-by-reference and library routines might modify the
4795 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4796 2.1).
4798 @item Signed @code{>>}
4799 Normally the C @code{>>} right shift of a signed type replicates the
4800 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4801 taken since Standard C doesn't require that behavior.  On those
4802 few processors without a native arithmetic shift (for instance Cray
4803 vector systems) zero bits may be shifted in, the same as a shift of an
4804 unsigned type.
4806 @item Integer @code{/}
4807 C divides signed integers by truncating their quotient toward zero,
4808 yielding the same result as Fortran.  However, before C99 the standard
4809 allowed C implementations to take the floor or ceiling of the quotient
4810 in some cases.  Hardly any implementations took advantage of this
4811 freedom, though, and it's probably not worth worrying about this issue
4812 nowadays.
4813 @end table
4816 @node Particular Functions
4817 @subsection Particular Function Checks
4818 @cindex Function, checking
4820 These macros check for particular C functions---whether they exist, and
4821 in some cases how they respond when given certain arguments.
4823 @anchor{AC_FUNC_ALLOCA}
4824 @defmac AC_FUNC_ALLOCA
4825 @acindex{FUNC_ALLOCA}
4826 @cvindex C_ALLOCA
4827 @cvindex HAVE_ALLOCA_H
4828 @ovindex ALLOCA
4829 @c @fuindex alloca
4830 @prindex @code{alloca}
4831 @hdrindex{alloca.h}
4832 @c @caindex working_alloca_h
4833 Check how to get @code{alloca}.  Tries to get a builtin version by
4834 checking for @file{alloca.h} or the predefined C preprocessor macros
4835 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4836 it defines @code{HAVE_ALLOCA_H}.
4838 If those attempts fail, it looks for the function in the standard C
4839 library.  If any of those methods succeed, it defines
4840 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4841 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4842 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4843 garbage collect).  This variable is separate from @code{LIBOBJS} so
4844 multiple programs can share the value of @code{ALLOCA} without needing
4845 to create an actual library, in case only some of them use the code in
4846 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4847 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4849 This macro does not try to get @code{alloca} from the System V R3
4850 @file{libPW} or the System V R4 @file{libucb} because those libraries
4851 contain some incompatible functions that cause trouble.  Some versions
4852 do not even contain @code{alloca} or contain a buggy version.  If you
4853 still want to use their @code{alloca}, use @code{ar} to extract
4854 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4856 Source files that use @code{alloca} should start with a piece of code
4857 like the following, to declare it properly.
4859 @example
4860 @group
4861 #if defined STDC_HEADERS || defined HAVE_STDLIB_H
4862 # include <stdlib.h>
4863 #endif
4864 #include <stddef.h>
4865 #ifdef HAVE_ALLOCA_H
4866 # include <alloca.h>
4867 #elif !defined alloca
4868 # ifdef __GNUC__
4869 #  define alloca __builtin_alloca
4870 # elif defined _AIX
4871 #  define alloca __alloca
4872 # elif defined _MSC_VER
4873 #  include <malloc.h>
4874 #  define alloca _alloca
4875 # elif !defined HAVE_ALLOCA
4876 #  ifdef  __cplusplus
4877 extern "C"
4878 #  endif
4879 void *alloca (size_t);
4880 # endif
4881 #endif
4882 @end group
4883 @end example
4884 @end defmac
4886 @defmac AC_FUNC_CHOWN
4887 @acindex{FUNC_CHOWN}
4888 @cvindex HAVE_CHOWN
4889 @c @fuindex chown
4890 @prindex @code{chown}
4891 @caindex func_chown_works
4892 If the @code{chown} function is available and works (in particular, it
4893 should accept @option{-1} for @code{uid} and @code{gid}), define
4894 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4895 @code{ac_cv_func_chown_works} variable.
4896 @end defmac
4898 @anchor{AC_FUNC_CLOSEDIR_VOID}
4899 @defmac AC_FUNC_CLOSEDIR_VOID
4900 @acindex{FUNC_CLOSEDIR_VOID}
4901 @cvindex CLOSEDIR_VOID
4902 @c @fuindex closedir
4903 @prindex @code{closedir}
4904 @caindex func_closedir_void
4905 If the @code{closedir} function does not return a meaningful value,
4906 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4907 return value for an error indicator.
4909 Currently this test is implemented by running a test program.  When
4910 cross compiling the pessimistic assumption that @code{closedir} does not
4911 return a meaningful value is made.
4913 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4914 variable.
4916 This macro is obsolescent, as @code{closedir} returns a meaningful value
4917 on current systems.  New programs need not use this macro.
4918 @end defmac
4920 @defmac AC_FUNC_ERROR_AT_LINE
4921 @acindex{FUNC_ERROR_AT_LINE}
4922 @c @fuindex error_at_line
4923 @prindex @code{error_at_line}
4924 @caindex lib_error_at_line
4925 If the @code{error_at_line} function is not found, require an
4926 @code{AC_LIBOBJ} replacement of @samp{error}.
4928 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4929 variable.
4931 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4932 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4933 @end defmac
4935 @defmac AC_FUNC_FNMATCH
4936 @acindex{FUNC_FNMATCH}
4937 @c @fuindex fnmatch
4938 @prindex @code{fnmatch}
4939 @caindex func_fnmatch_works
4940 If the @code{fnmatch} function conforms to Posix, define
4941 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4942 the bugs in Solaris 2.4.
4944 Unlike the other specific
4945 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4946 broken/missing @code{fnmatch}.  This is for historical reasons.
4947 See @code{AC_REPLACE_FNMATCH} below.
4949 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4950 variable.
4952 This macro is obsolescent.  New programs should use Gnulib's
4953 @code{fnmatch-posix} module.  @xref{Gnulib}.
4954 @end defmac
4956 @defmac AC_FUNC_FNMATCH_GNU
4957 @acindex{FUNC_FNMATCH_GNU}
4958 @c @fuindex fnmatch
4959 @prindex @code{fnmatch}
4960 @caindex func_fnmatch_gnu
4961 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4962 whether @code{fnmatch} supports GNU extensions.  Detect common
4963 implementation bugs, for example, the bugs in the GNU C
4964 Library 2.1.
4966 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4967 variable.
4969 This macro is obsolescent.  New programs should use Gnulib's
4970 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4971 @end defmac
4973 @anchor{AC_FUNC_FORK}
4974 @defmac AC_FUNC_FORK
4975 @acindex{FUNC_FORK}
4976 @cvindex HAVE_VFORK_H
4977 @cvindex HAVE_WORKING_FORK
4978 @cvindex HAVE_WORKING_VFORK
4979 @cvindex vfork
4980 @c @fuindex fork
4981 @prindex @code{fork}
4982 @c @fuindex vfork
4983 @prindex @code{vfork}
4984 @hdrindex{vfork.h}
4985 @c @caindex func_fork
4986 @c @caindex func_fork_works
4987 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4988 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4989 checks whether @code{fork} is just a stub by trying to run it.
4991 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4992 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4993 define @code{vfork} to be @code{fork} for backward compatibility with
4994 previous versions of @command{autoconf}.  This macro checks for several known
4995 errors in implementations of @code{vfork} and considers the system to not
4996 have a working @code{vfork} if it detects any of them.
4998 Since this macro defines @code{vfork} only for backward compatibility with
4999 previous versions of @command{autoconf} you're encouraged to define it
5000 yourself in new code:
5001 @example
5002 @group
5003 #ifndef HAVE_WORKING_VFORK
5004 # define vfork fork
5005 #endif
5006 @end group
5007 @end example
5009 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5010 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5011 test, you also need to set the @code{ac_cv_func_fork} and
5012 @code{ac_cv_func_vfork} variables.
5013 @end defmac
5015 @defmac AC_FUNC_FSEEKO
5016 @acindex{FUNC_FSEEKO}
5017 @cvindex _LARGEFILE_SOURCE
5018 @cvindex HAVE_FSEEKO
5019 @c @fuindex fseeko
5020 @prindex @code{fseeko}
5021 @c @fuindex ftello
5022 @prindex @code{ftello}
5023 @c @caindex sys_largefile_source
5024 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5025 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5026 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5027 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5028 largefile-sensitive systems where @code{off_t} does not default to a
5029 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5030 @end defmac
5032 @defmac AC_FUNC_GETGROUPS
5033 @acindex{FUNC_GETGROUPS}
5034 @cvindex HAVE_GETGROUPS
5035 @ovindex GETGROUPS_LIBS
5036 @c @fuindex getgroups
5037 @prindex @code{getgroups}
5038 @caindex func_getgroups_works
5039 If the @code{getgroups} function is available and works (unlike on
5040 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5041 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5042 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5043 @end defmac
5045 @anchor{AC_FUNC_GETLOADAVG}
5046 @defmac AC_FUNC_GETLOADAVG
5047 @acindex{FUNC_GETLOADAVG}
5048 @cvindex SVR4
5049 @cvindex DGUX
5050 @cvindex UMAX
5051 @cvindex UMAX4_3
5052 @cvindex HAVE_NLIST_H
5053 @cvindex NLIST_NAME_UNION
5054 @cvindex GETLOADAVG_PRIVILEGED
5055 @cvindex NEED_SETGID
5056 @cvindex C_GETLOADAVG
5057 @ovindex LIBOBJS
5058 @ovindex NEED_SETGID
5059 @ovindex KMEM_GROUP
5060 @ovindex GETLOADAVG_LIBS
5061 @c @fuindex getloadavg
5062 @prindex @code{getloadavg}
5063 Check how to get the system load averages.  To perform its tests
5064 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5065 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5066 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5068 If the system has the @code{getloadavg} function, define
5069 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5070 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5071 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5072 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5073 possibly define several other C preprocessor macros and output
5074 variables:
5076 @enumerate
5077 @item
5078 Define @code{C_GETLOADAVG}.
5080 @item
5081 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5082 those systems.
5084 @item
5085 @hdrindex{nlist.h}
5086 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5088 @item
5089 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5090 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5091 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5093 @item
5094 Programs may need to be installed set-group-ID (or set-user-ID) for
5095 @code{getloadavg} to work.  In this case, define
5096 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5097 to @samp{true} (and otherwise to @samp{false}), and set
5098 @code{KMEM_GROUP} to the name of the group that should own the installed
5099 program.
5100 @end enumerate
5102 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5103 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5104 @end defmac
5106 @anchor{AC_FUNC_GETMNTENT}
5107 @defmac AC_FUNC_GETMNTENT
5108 @acindex{FUNC_GETMNTENT}
5109 @cvindex HAVE_GETMNTENT
5110 @c @fuindex getmntent
5111 @prindex @code{getmntent}
5112 @caindex search_getmntent
5113 Check for @code{getmntent} in the standard C library, and then in the
5114 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5115 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5116 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5117 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5118 @code{ac_cv_func_getmntent} to @code{no}.
5120 The result of this macro can be overridden by setting the cache variable
5121 @code{ac_cv_search_getmntent}.
5122 @end defmac
5124 @defmac AC_FUNC_GETPGRP
5125 @acindex{FUNC_GETPGRP}
5126 @cvindex GETPGRP_VOID
5127 @c @fuindex getpgid
5128 @c @fuindex getpgrp
5129 @prindex @code{getpgid}
5130 @prindex @code{getpgrp}
5131 @caindex func_getpgrp_void
5132 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5133 @code{getpgrp}; this is the Posix behavior.  On older BSD
5134 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5135 behaves like Posix's @code{getpgid}.
5137 @example
5138 #ifdef GETPGRP_VOID
5139   pid = getpgrp ();
5140 #else
5141   pid = getpgrp (0);
5142 #endif
5143 @end example
5145 This macro does not check whether
5146 @code{getpgrp} exists at all; if you need to work in that situation,
5147 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5149 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5150 variable.
5152 This macro is obsolescent, as current systems have a @code{getpgrp}
5153 whose signature conforms to Posix.  New programs need not use this macro.
5154 @end defmac
5156 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5157 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5158 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5159 @c @fuindex lstat
5160 @prindex @code{lstat}
5161 @caindex func_lstat_dereferences_slashed_symlink
5162 If @file{link} is a symbolic link, then @code{lstat} should treat
5163 @file{link/} the same as @file{link/.}.  However, many older
5164 @code{lstat} implementations incorrectly ignore trailing slashes.
5166 It is safe to assume that if @code{lstat} incorrectly ignores
5167 trailing slashes, then other symbolic-link-aware functions like
5168 @code{unlink} also incorrectly ignore trailing slashes.
5170 If @code{lstat} behaves properly, define
5171 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5172 @code{AC_LIBOBJ} replacement of @code{lstat}.
5174 The result of this macro is cached in the
5175 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5177 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5178 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5179 @end defmac
5181 @defmac AC_FUNC_MALLOC
5182 @acindex{FUNC_MALLOC}
5183 @cvindex HAVE_MALLOC
5184 @cvindex malloc
5185 @c @fuindex malloc
5186 @prindex @code{malloc}
5187 @caindex func_malloc_0_nonnull
5188 If the @code{malloc} function is compatible with the GNU C
5189 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5190 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5191 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5192 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5193 native @code{malloc} is not used in the main project.
5195 Typically, the replacement file @file{malloc.c} should look like (note
5196 the @samp{#undef malloc}):
5198 @verbatim
5199 #include <config.h>
5200 #undef malloc
5202 #include <sys/types.h>
5204 void *malloc ();
5206 /* Allocate an N-byte block of memory from the heap.
5207    If N is zero, allocate a 1-byte block.  */
5209 void *
5210 rpl_malloc (size_t n)
5212   if (n == 0)
5213     n = 1;
5214   return malloc (n);
5216 @end verbatim
5218 The result of this macro is cached in the
5219 @code{ac_cv_func_malloc_0_nonnull} variable.
5220 @end defmac
5222 @defmac AC_FUNC_MBRTOWC
5223 @acindex{FUNC_MBRTOWC}
5224 @cvindex HAVE_MBRTOWC
5225 @c @fuindex mbrtowc
5226 @prindex @code{mbrtowc}
5227 @caindex func_mbrtowc
5228 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5229 type @code{mbstate_t} are properly declared.
5231 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5232 variable.
5233 @end defmac
5235 @defmac AC_FUNC_MEMCMP
5236 @acindex{FUNC_MEMCMP}
5237 @ovindex LIBOBJS
5238 @c @fuindex memcmp
5239 @prindex @code{memcmp}
5240 @caindex func_memcmp_working
5241 If the @code{memcmp} function is not available, or does not work on
5242 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5243 bytes or more and with at least one buffer not starting on a 4-byte
5244 boundary (such as the one on NeXT x86 OpenStep), require an
5245 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5247 The result of this macro is cached in the
5248 @code{ac_cv_func_memcmp_working} variable.
5250 This macro is obsolescent, as current systems have a working
5251 @code{memcmp}.  New programs need not use this macro.
5252 @end defmac
5254 @defmac AC_FUNC_MKTIME
5255 @acindex{FUNC_MKTIME}
5256 @ovindex LIBOBJS
5257 @c @fuindex mktime
5258 @prindex @code{mktime}
5259 @caindex func_working_mktime
5260 If the @code{mktime} function is not available, or does not work
5261 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5262 For the purposes of this test, @code{mktime} should conform to the
5263 Posix standard and should be the inverse of
5264 @code{localtime}.
5266 The result of this macro is cached in the
5267 @code{ac_cv_func_working_mktime} variable.
5269 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5270 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5271 @end defmac
5273 @anchor{AC_FUNC_MMAP}
5274 @defmac AC_FUNC_MMAP
5275 @acindex{FUNC_MMAP}
5276 @cvindex HAVE_MMAP
5277 @c @fuindex mmap
5278 @prindex @code{mmap}
5279 @caindex func_mmap_fixed_mapped
5280 If the @code{mmap} function exists and works correctly, define
5281 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5282 memory.
5284 The result of this macro is cached in the
5285 @code{ac_cv_func_mmap_fixed_mapped} variable.
5286 @end defmac
5288 @defmac AC_FUNC_OBSTACK
5289 @acindex{FUNC_OBSTACK}
5290 @cvindex HAVE_OBSTACK
5291 @cindex obstack
5292 @caindex func_obstack
5293 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5294 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5296 The result of this macro is cached in the @code{ac_cv_func_obstack}
5297 variable.
5298 @end defmac
5300 @defmac AC_FUNC_REALLOC
5301 @acindex{FUNC_REALLOC}
5302 @cvindex HAVE_REALLOC
5303 @cvindex realloc
5304 @c @fuindex realloc
5305 @prindex @code{realloc}
5306 @caindex func_realloc_0_nonnull
5307 If the @code{realloc} function is compatible with the GNU C
5308 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5309 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5310 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5311 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5312 the native @code{realloc} is not used in the main project.  See
5313 @code{AC_FUNC_MALLOC} for details.
5315 The result of this macro is cached in the
5316 @code{ac_cv_func_realloc_0_nonnull} variable.
5317 @end defmac
5319 @defmac AC_FUNC_SELECT_ARGTYPES
5320 @acindex{FUNC_SELECT_ARGTYPES}
5321 @cvindex SELECT_TYPE_ARG1
5322 @cvindex SELECT_TYPE_ARG234
5323 @cvindex SELECT_TYPE_ARG5
5324 @c @fuindex select
5325 @prindex @code{select}
5326 @c @caindex func_select_args
5327 Determines the correct type to be passed for each of the
5328 @code{select} function's arguments, and defines those types
5329 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5330 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5331 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5332 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5334 This macro is obsolescent, as current systems have a @code{select} whose
5335 signature conforms to Posix.  New programs need not use this macro.
5336 @end defmac
5338 @defmac AC_FUNC_SETPGRP
5339 @acindex{FUNC_SETPGRP}
5340 @cvindex SETPGRP_VOID
5341 @c @fuindex setpgrp
5342 @prindex @code{setpgrp}
5343 @caindex func_setpgrp_void
5344 If @code{setpgrp} takes no argument (the Posix version), define
5345 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5346 two process IDs as arguments.  This macro does not check whether
5347 @code{setpgrp} exists at all; if you need to work in that situation,
5348 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5350 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5351 variable.
5353 This macro is obsolescent, as current systems have a @code{setpgrp}
5354 whose signature conforms to Posix.  New programs need not use this macro.
5355 @end defmac
5357 @defmac AC_FUNC_STAT
5358 @defmacx AC_FUNC_LSTAT
5359 @acindex{FUNC_STAT}
5360 @acindex{FUNC_LSTAT}
5361 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5362 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5363 @c @fuindex stat
5364 @prindex @code{stat}
5365 @c @fuindex lstat
5366 @prindex @code{lstat}
5367 @caindex func_stat_empty_string_bug
5368 @caindex func_lstat_empty_string_bug
5369 Determine whether @code{stat} or @code{lstat} have the bug that it
5370 succeeds when given the zero-length file name as argument.  The @code{stat}
5371 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5372 this.
5374 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5375 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5376 replacement of it.
5378 The results of these macros are cached in the
5379 @code{ac_cv_func_stat_empty_string_bug} and the
5380 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5382 These macros are obsolescent, as no current systems have the bug.
5383 New programs need not use these macros.
5384 @end defmac
5386 @anchor{AC_FUNC_STRCOLL}
5387 @defmac AC_FUNC_STRCOLL
5388 @acindex{FUNC_STRCOLL}
5389 @cvindex HAVE_STRCOLL
5390 @c @fuindex strcoll
5391 @prindex @code{strcoll}
5392 @caindex func_strcoll_works
5393 If the @code{strcoll} function exists and works correctly, define
5394 @code{HAVE_STRCOLL}.  This does a bit more than
5395 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5396 definitions of @code{strcoll} that should not be used.
5398 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5399 variable.
5400 @end defmac
5402 @defmac AC_FUNC_STRERROR_R
5403 @acindex{FUNC_STRERROR_R}
5404 @cvindex HAVE_STRERROR_R
5405 @cvindex HAVE_DECL_STRERROR_R
5406 @cvindex STRERROR_R_CHAR_P
5407 @c @fuindex strerror_r
5408 @caindex func_strerror_r_char_p
5409 @prindex @code{strerror_r}
5410 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5411 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5412 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5413 returns an @code{int} error number.  The Thread-Safe Functions option of
5414 Posix requires @code{strerror_r} to return @code{int}, but
5415 many systems (including, for example, version 2.2.4 of the GNU C
5416 Library) return a @code{char *} value that is not necessarily equal to
5417 the buffer argument.
5419 The result of this macro is cached in the
5420 @code{ac_cv_func_strerror_r_char_p} variable.
5421 @end defmac
5423 @anchor{AC_FUNC_STRFTIME}
5424 @defmac AC_FUNC_STRFTIME
5425 @acindex{FUNC_STRFTIME}
5426 @cvindex HAVE_STRFTIME
5427 @c @fuindex strftime
5428 @prindex @code{strftime}
5429 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5430 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5432 This macro is obsolescent, as no current systems require the @file{intl}
5433 library for @code{strftime}.  New programs need not use this macro.
5434 @end defmac
5436 @defmac AC_FUNC_STRTOD
5437 @acindex{FUNC_STRTOD}
5438 @ovindex POW_LIB
5439 @c @fuindex strtod
5440 @prindex @code{strtod}
5441 @caindex func_strtod
5442 @caindex func_pow
5443 If the @code{strtod} function does not exist or doesn't work correctly,
5444 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5445 because @file{strtod.c} is likely to need @samp{pow}, set the output
5446 variable @code{POW_LIB} to the extra library needed.
5448 This macro caches its result in the @code{ac_cv_func_strtod} variable
5449 and depends upon the result in the @code{ac_cv_func_pow} variable.
5451 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5452 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5453 @end defmac
5455 @defmac AC_FUNC_STRTOLD
5456 @acindex{FUNC_STRTOLD}
5457 @cvindex HAVE_STRTOLD
5458 @prindex @code{strtold}
5459 @caindex func_strtold
5460 If the @code{strtold} function exists and conforms to C99 or later, define
5461 @code{HAVE_STRTOLD}.
5463 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5464 @end defmac
5466 @defmac AC_FUNC_STRNLEN
5467 @acindex{FUNC_STRNLEN}
5468 @cvindex HAVE_STRNLEN
5469 @c @fuindex strnlen
5470 @prindex @code{strnlen}
5471 @caindex func_strnlen_working
5472 If the @code{strnlen} function is not available, or is buggy (like the one
5473 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5475 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5476 variable.
5477 @end defmac
5479 @anchor{AC_FUNC_UTIME_NULL}
5480 @defmac AC_FUNC_UTIME_NULL
5481 @acindex{FUNC_UTIME_NULL}
5482 @cvindex HAVE_UTIME_NULL
5483 @c @fuindex utime
5484 @prindex @code{utime}
5485 @caindex func_utime_null
5486 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5487 the present, define @code{HAVE_UTIME_NULL}.
5489 This macro caches its result in the @code{ac_cv_func_utime_null}
5490 variable.
5492 This macro is obsolescent, as all current systems have a @code{utime}
5493 that behaves this way.  New programs need not use this macro.
5494 @end defmac
5496 @anchor{AC_FUNC_VPRINTF}
5497 @defmac AC_FUNC_VPRINTF
5498 @acindex{FUNC_VPRINTF}
5499 @cvindex HAVE_VPRINTF
5500 @cvindex HAVE_DOPRNT
5501 @c @fuindex vprintf
5502 @prindex @code{vprintf}
5503 @c @fuindex vsprintf
5504 @prindex @code{vsprintf}
5505 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5506 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5507 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5508 are also available.)
5510 This macro is obsolescent, as all current systems have @code{vprintf}.
5511 New programs need not use this macro.
5512 @end defmac
5514 @defmac AC_REPLACE_FNMATCH
5515 @acindex{REPLACE_FNMATCH}
5516 @c @fuindex fnmatch
5517 @prindex @code{fnmatch}
5518 @hdrindex{fnmatch.h}
5519 @caindex func_fnmatch_works
5520 If the @code{fnmatch} function does not conform to Posix (see
5521 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5523 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5524 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5525 copy of the source code of GNU @code{fnmatch}.  If necessary,
5526 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5527 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5528 included in place of the system @code{<fnmatch.h>}.
5530 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5531 variable.
5533 This macro is obsolescent, as it assumes the use of particular source
5534 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5535 which provides this macro along with the source files.  @xref{Gnulib}.
5536 @end defmac
5540 @node Generic Functions
5541 @subsection Generic Function Checks
5543 These macros are used to find functions not covered by the ``particular''
5544 test macros.  If the functions might be in libraries other than the
5545 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5546 If you need to check the behavior of a function as well as find out
5547 whether it is present, you have to write your own test for
5548 it (@pxref{Writing Tests}).
5550 @anchor{AC_CHECK_FUNC}
5551 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5552   @ovar{action-if-not-found})
5553 @acindex{CHECK_FUNC}
5554 @caindex func_@var{function}
5555 If C function @var{function} is available, run shell commands
5556 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5557 want to define a symbol if the function is available, consider using
5558 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5559 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5560 standardized than C++.  (@pxref{Language Choice}, for more information
5561 about selecting the language for checks.)
5563 This macro caches its result in the @code{ac_cv_func_@var{function}}
5564 variable.
5565 @end defmac
5567 @anchor{AC_CHECK_FUNCS}
5568 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5569   @ovar{action-if-not-found})
5570 @acindex{CHECK_FUNCS}
5571 @cvindex HAVE_@var{function}
5572 For each @var{function} enumerated in the blank-or-newline-separated argument
5573 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5574 If @var{action-if-found} is given, it is additional shell code to
5575 execute when one of the functions is found.  You can give it a value of
5576 @samp{break} to break out of the loop on the first match.  If
5577 @var{action-if-not-found} is given, it is executed when one of the
5578 functions is not found.
5580 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5581 @end defmac
5583 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5584 @acindex{CHECK_FUNCS_ONCE}
5585 @cvindex HAVE_@var{function}
5586 For each @var{function} enumerated in the blank-or-newline-separated argument
5587 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5588 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5589 checking code at most once, so that @command{configure} is smaller and
5590 faster; but the checks cannot be conditionalized and are always done once,
5591 early during the @command{configure} run.
5592 @end defmac
5594 @sp 1
5596 Autoconf follows a philosophy that was formed over the years by those
5597 who have struggled for portability: isolate the portability issues in
5598 specific files, and then program as if you were in a Posix
5599 environment.  Some functions may be missing or unfixable, and your
5600 package must be ready to replace them.
5602 Suitable replacements for many such problem functions are available from
5603 Gnulib (@pxref{Gnulib}).
5605 @defmac AC_LIBOBJ (@var{function})
5606 @acindex{LIBOBJ}
5607 @ovindex LIBOBJS
5608 Specify that @samp{@var{function}.c} must be included in the executables
5609 to replace a missing or broken implementation of @var{function}.
5611 @vrindex ac_objext
5612 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5613 variable @code{LIBOBJS} if it is not already in, and calls
5614 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5615 directly change @code{LIBOBJS}, since this is not traceable.
5616 @end defmac
5618 @defmac AC_LIBSOURCE (@var{file})
5619 @acindex{LIBSOURCE}
5620 Specify that @var{file} might be needed to compile the project.  If you
5621 need to know what files might be needed by a @file{configure.ac}, you
5622 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5624 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5625 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5626 that case, since shell variables cannot be traced statically, you must
5627 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5628 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5629 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5630 @code{"foo"} or @code{"bar"}, you should do:
5632 @example
5633 AC_LIBSOURCE([foo.c])
5634 AC_LIBSOURCE([bar.c])
5635 AC_LIBOBJ([$foo_or_bar])
5636 @end example
5638 @noindent
5639 There is usually a way to avoid this, however, and you are encouraged to
5640 simply call @code{AC_LIBOBJ} with literal arguments.
5642 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5643 slightly different semantics: the old macro took the function name,
5644 e.g., @code{foo}, as its argument rather than the file name.
5645 @end defmac
5647 @defmac AC_LIBSOURCES (@var{files})
5648 @acindex{LIBSOURCES}
5649 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5650 comma-separated M4 list.  Thus, the above example might be rewritten:
5652 @example
5653 AC_LIBSOURCES([foo.c, bar.c])
5654 AC_LIBOBJ([$foo_or_bar])
5655 @end example
5656 @end defmac
5658 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5659 @acindex{CONFIG_LIBOBJ_DIR}
5660 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5661 @var{directory}, a name relative to the top level of the
5662 source tree.  The replacement directory defaults to @file{.}, the top
5663 level directory, and the most typical value is @file{lib}, corresponding
5664 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5666 @command{configure} might need to know the replacement directory for the
5667 following reasons: (i) some checks use the replacement files, (ii) some
5668 macros bypass broken system headers by installing links to the
5669 replacement headers (iii) when used in conjunction with Automake,
5670 within each makefile, @var{directory} is used as a relative path
5671 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5672 @code{LTLIBOBJS}, etc.
5673 @end defmac
5675 @sp 1
5677 It is common to merely check for the existence of a function, and ask
5678 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5679 a convenient shorthand.
5681 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5682 @acindex{REPLACE_FUNCS}
5683 @cvindex HAVE_@var{function}
5684 @ovindex LIBOBJS
5685 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5686 @var{action-if-not-found}.  You can declare your replacement function by
5687 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5688 system has the function, it probably declares it in a header file you
5689 should be including, so you shouldn't redeclare it lest your declaration
5690 conflict.
5691 @end defmac
5693 @node Header Files
5694 @section Header Files
5695 @cindex Header, checking
5697 The following macros check for the presence of certain C header files.
5698 If there is no macro specifically defined to check for a header file you need,
5699 and you don't need to check for any special properties of
5700 it, then you can use one of the general header-file check macros.
5702 @menu
5703 * Header Portability::          Collected knowledge on common headers
5704 * Particular Headers::          Special handling to find certain headers
5705 * Generic Headers::             How to find other headers
5706 @end menu
5708 @node Header Portability
5709 @subsection Portability of Headers
5710 @cindex Portability of headers
5711 @cindex Header portability
5713 This section documents some collected knowledge about common headers,
5714 and the problems they cause.  By definition, this list always requires
5715 additions.  A much more complete list is maintained by the Gnulib
5716 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5717 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5718 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5719 the gnulib list as complete as possible.
5721 @table @asis
5723 @item @file{limits.h}
5724 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5725 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5726 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5727 define them.
5729 @item @file{inttypes.h} vs.@: @file{stdint.h}
5730 @hdrindex{inttypes.h}
5731 @hdrindex{stdint.h}
5732 In C99 and later, @file{inttypes.h} includes
5733 @file{stdint.h}, so there's no need to include @file{stdint.h}
5734 separately in a standard environment.  Some implementations have
5735 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5736 know of any implementation that has @file{stdint.h} but not
5737 @file{inttypes.h}.
5739 @item @file{linux/irda.h}
5740 @hdrindex{linux/irda.h}
5741 It requires @file{linux/types.h} and @file{sys/socket.h}.
5743 @item @file{linux/random.h}
5744 @hdrindex{linux/random.h}
5745 It requires @file{linux/types.h}.
5747 @item @file{net/if.h}
5748 @hdrindex{net/if.h}
5749 On Darwin, this file requires that @file{sys/socket.h} be included
5750 beforehand.  One should run:
5752 @example
5753 AC_CHECK_HEADERS([sys/socket.h])
5754 AC_CHECK_HEADERS([net/if.h], [], [],
5755 [#include <stdio.h>
5756 #if defined STDC_HEADERS || defined HAVE_STDLIB_H
5757 # include <stdlib.h>
5758 #endif
5759 #include <stddef.h>
5760 #ifdef HAVE_SYS_SOCKET_H
5761 # include <sys/socket.h>
5762 #endif
5764 @end example
5766 @item @file{netinet/if_ether.h}
5767 @hdrindex{netinet/if_ether.h}
5768 On Darwin, this file requires that @file{stdio.h} and
5769 @file{sys/socket.h} be included beforehand.  One should run:
5771 @example
5772 AC_CHECK_HEADERS([sys/socket.h])
5773 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5774 [#include <stdio.h>
5775 #if defined STDC_HEADERS || defined HAVE_STDLIB_H
5776 # include <stdlib.h>
5777 #endif
5778 #include <stddef.h>
5779 #ifdef HAVE_SYS_SOCKET_H
5780 # include <sys/socket.h>
5781 #endif
5783 @end example
5785 @item @file{stdint.h}
5786 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5788 @item @file{stdlib.h}
5789 @hdrindex{stdlib.h}
5790 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5792 @item @file{sys/mount.h}
5793 @hdrindex{sys/mount.h}
5794 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5795 @file{sys/params.h} is a prerequisite.
5797 @item @file{sys/ptem.h}
5798 @hdrindex{sys/ptem.h}
5799 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5801 @item @file{sys/socket.h}
5802 @hdrindex{sys/socket.h}
5803 On Darwin, @file{stdlib.h} is a prerequisite.
5805 @item @file{sys/ucred.h}
5806 @hdrindex{sys/ucred.h}
5807 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5809 @item @file{X11/extensions/scrnsaver.h}
5810 @hdrindex{X11/extensions/scrnsaver.h}
5811 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5812 so required that you might not even consider looking for it.
5814 @example
5815 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5816 [[#include <X11/Xlib.h>
5818 @end example
5819 @end table
5822 @node Particular Headers
5823 @subsection Particular Header Checks
5825 These macros check for particular system header files---whether they
5826 exist, and in some cases whether they declare certain symbols.
5828 @defmac AC_CHECK_HEADER_STDBOOL
5829 @acindex{CHECK_HEADER_STDBOOL}
5830 @cvindex HAVE__BOOL
5831 @hdrindex{stdbool.h}
5832 @caindex header_stdbool_h
5833 Check whether @file{stdbool.h} exists and conforms to C99 or later,
5834 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
5835 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5837 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5838 packages that supply a substitute @file{stdbool.h} on platforms lacking
5839 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5840 that explicitly checks for @file{stdbool.h}.
5841 @end defmac
5843 @defmac AC_HEADER_ASSERT
5844 @acindex{HEADER_ASSERT}
5845 @cvindex NDEBUG
5846 @hdrindex{assert.h}
5847 Check whether to enable assertions in the style of @file{assert.h}.
5848 Assertions are enabled by default, but the user can override this by
5849 invoking @command{configure} with the @option{--disable-assert} option.
5850 @end defmac
5852 @anchor{AC_HEADER_DIRENT}
5853 @defmac AC_HEADER_DIRENT
5854 @acindex{HEADER_DIRENT}
5855 @cvindex HAVE_DIRENT_H
5856 @cvindex HAVE_NDIR_H
5857 @cvindex HAVE_SYS_DIR_H
5858 @cvindex HAVE_SYS_NDIR_H
5859 @hdrindex{dirent.h}
5860 @hdrindex{sys/ndir.h}
5861 @hdrindex{sys/dir.h}
5862 @hdrindex{ndir.h}
5863 Check for the following header files.  For the first one that is
5864 found and defines @samp{DIR}, define the listed C preprocessor macro:
5866 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5867 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5868 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5869 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5870 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5871 @end multitable
5873 The directory-library declarations in your source code should look
5874 something like the following:
5876 @example
5877 @group
5878 #include <sys/types.h>
5879 #ifdef HAVE_DIRENT_H
5880 # include <dirent.h>
5881 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5882 #else
5883 # define dirent direct
5884 # define NAMLEN(dirent) ((dirent)->d_namlen)
5885 # ifdef HAVE_SYS_NDIR_H
5886 #  include <sys/ndir.h>
5887 # endif
5888 # ifdef HAVE_SYS_DIR_H
5889 #  include <sys/dir.h>
5890 # endif
5891 # ifdef HAVE_NDIR_H
5892 #  include <ndir.h>
5893 # endif
5894 #endif
5895 @end group
5896 @end example
5898 Using the above declarations, the program would declare variables to be
5899 of type @code{struct dirent}, not @code{struct direct}, and would access
5900 the length of a directory entry name by passing a pointer to a
5901 @code{struct dirent} to the @code{NAMLEN} macro.
5903 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5905 This macro is obsolescent, as all current systems with directory
5906 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5908 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5909 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5910 @end defmac
5912 @anchor{AC_HEADER_MAJOR}
5913 @defmac AC_HEADER_MAJOR
5914 @acindex{HEADER_MAJOR}
5915 @cvindex MAJOR_IN_MKDEV
5916 @cvindex MAJOR_IN_SYSMACROS
5917 @hdrindex{sys/mkdev.h}
5918 @hdrindex{sys/sysmacros.h}
5919 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5920 @code{makedev}, but @file{sys/mkdev.h} does, define
5921 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5922 @code{MAJOR_IN_SYSMACROS}.
5923 @end defmac
5925 @defmac AC_HEADER_RESOLV
5926 @acindex{HEADER_RESOLV}
5927 @cvindex HAVE_RESOLV_H
5928 @hdrindex{resolv.h}
5929 Checks for header @file{resolv.h}, checking for prerequisites first.
5930 To properly use @file{resolv.h}, your code should contain something like
5931 the following:
5933 @verbatim
5934 #ifdef HAVE_SYS_TYPES_H
5935 #  include <sys/types.h>
5936 #endif
5937 #ifdef HAVE_NETINET_IN_H
5938 #  include <netinet/in.h>   /* inet_ functions / structs */
5939 #endif
5940 #ifdef HAVE_ARPA_NAMESER_H
5941 #  include <arpa/nameser.h> /* DNS HEADER struct */
5942 #endif
5943 #ifdef HAVE_NETDB_H
5944 #  include <netdb.h>
5945 #endif
5946 #include <resolv.h>
5947 @end verbatim
5948 @end defmac
5950 @anchor{AC_HEADER_STAT}
5951 @defmac AC_HEADER_STAT
5952 @acindex{HEADER_STAT}
5953 @cvindex STAT_MACROS_BROKEN
5954 @hdrindex{sys/stat.h}
5955 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5956 @file{sys/stat.h} do not work properly (returning false positives),
5957 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5958 Amdahl UTS and Motorola System V/88.
5960 This macro is obsolescent, as no current systems have the bug.
5961 New programs need not use this macro.
5962 @end defmac
5964 @defmac AC_HEADER_STDBOOL
5965 @acindex{HEADER_STDBOOL}
5966 @cvindex HAVE_STDBOOL_H
5967 @cvindex HAVE__BOOL
5968 @hdrindex{stdbool.h}
5969 @caindex header_stdbool_h
5970 If @file{stdbool.h} exists and conforms to C99 or later, define
5971 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5972 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
5973 program could contain the following code:
5975 @example
5976 @group
5977 #ifdef HAVE_STDBOOL_H
5978 # include <stdbool.h>
5979 #else
5980 # ifndef HAVE__BOOL
5981 #  ifdef __cplusplus
5982 typedef bool _Bool;
5983 #  else
5984 #   define _Bool signed char
5985 #  endif
5986 # endif
5987 # define bool _Bool
5988 # define false 0
5989 # define true 1
5990 # define __bool_true_false_are_defined 1
5991 #endif
5992 @end group
5993 @end example
5995 Alternatively you can use the @samp{stdbool} package of Gnulib
5996 (@pxref{Gnulib}).  It simplifies your code so that it can say just
5997 @code{#include <stdbool.h>}, and it adds support for less-common
5998 platforms.
6000 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6001 variable.
6003 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6004 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6005 does not.
6006 @end defmac
6008 @anchor{AC_HEADER_STDC}
6009 @defmac AC_HEADER_STDC
6010 @acindex{HEADER_STDC}
6011 @cvindex STDC_HEADERS
6012 @hdrindex{stdlib.h}
6013 @hdrindex{stdarg.h}
6014 @hdrindex{string.h}
6015 @hdrindex{float.h}
6016 @hdrindex{ctype.h}
6017 @caindex header_stdc
6018 Define @code{STDC_HEADERS} if the system has C header files
6019 conforming to ANSI C89 (ISO C90).
6020 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
6021 @file{string.h}, and @file{float.h}; if the system has those, it
6022 probably has the rest of the C89 header files.  This macro also
6023 checks whether @file{string.h} declares @code{memchr} (and thus
6024 presumably the other @code{mem} functions), whether @file{stdlib.h}
6025 declare @code{free} (and thus presumably @code{malloc} and other related
6026 functions), and whether the @file{ctype.h} macros work on characters
6027 with the high bit set, as the C standard requires.
6029 If you use this macro, your code can refer to @code{STDC_HEADERS} to
6030 determine whether the system has conforming header files (and probably C
6031 library functions).
6033 This macro caches its result in the @code{ac_cv_header_stdc} variable.
6035 This macro is obsolescent, as current systems have conforming header
6036 files.  New programs need not use this macro.
6038 @hdrindex{string.h}
6039 @hdrindex{strings.h}
6040 Nowadays @file{string.h} is part of the C standard and declares functions like
6041 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
6042 BSD functions like @code{bcopy}; but
6043 historically, string functions were a major sticking point in this area.
6044 If you still want to worry about portability to ancient systems without
6045 standard headers, there is so much variation
6046 that it is probably easier to declare the functions you use than to
6047 figure out exactly what the system header files declare.  Some ancient systems
6048 contained a mix of functions from the C standard and from BSD;
6049 some were mostly standard but lacked @samp{memmove}; some defined the
6050 BSD functions as macros in @file{string.h} or
6051 @file{strings.h}; some had only the BSD functions but
6052 @file{string.h}; some declared the memory functions in @file{memory.h},
6053 some in @file{string.h}; etc.  It is probably sufficient to check for
6054 one string function and one memory function; if the library had the
6055 standard versions of those then it probably had most of the others.
6056 If you put the following in @file{configure.ac}:
6058 @example
6059 # This example is obsolescent.
6060 # Nowadays you can omit these macro calls.
6061 AC_HEADER_STDC
6062 AC_CHECK_FUNCS([strchr memcpy])
6063 @end example
6065 @noindent
6066 then, in your code, you can use declarations like this:
6068 @example
6069 @group
6070 /* This example is obsolescent.
6071    Nowadays you can just #include <string.h>.  */
6072 #ifdef STDC_HEADERS
6073 # include <string.h>
6074 #else
6075 # ifndef HAVE_STRCHR
6076 #  define strchr index
6077 #  define strrchr rindex
6078 # endif
6079 char *strchr (), *strrchr ();
6080 # ifndef HAVE_MEMCPY
6081 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
6082 #  define memmove(d, s, n) bcopy ((s), (d), (n))
6083 # endif
6084 #endif
6085 @end group
6086 @end example
6088 @noindent
6089 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6090 or @code{strspn}, which have no BSD equivalent, then macros don't
6091 suffice to port to ancient hosts; you must provide an implementation of
6092 each function.  An easy
6093 way to incorporate your implementations only when needed (since the ones
6094 in system C libraries may be hand optimized) is to, taking @code{memchr}
6095 for example, put it in @file{memchr.c} and use
6096 @samp{AC_REPLACE_FUNCS([memchr])}.
6097 @end defmac
6099 @defmac AC_HEADER_SYS_WAIT
6100 @acindex{HEADER_SYS_WAIT}
6101 @cvindex HAVE_SYS_WAIT_H
6102 @hdrindex{sys/wait.h}
6103 @caindex header_sys_wait_h
6104 If @file{sys/wait.h} exists and is compatible with Posix, define
6105 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6106 does not exist, or if it uses the old BSD @code{union wait} instead
6107 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6108 Posix compatible, then instead of including it, define the
6109 Posix macros with their usual interpretations.  Here is an
6110 example:
6112 @example
6113 @group
6114 #include <sys/types.h>
6115 #ifdef HAVE_SYS_WAIT_H
6116 # include <sys/wait.h>
6117 #endif
6118 #ifndef WEXITSTATUS
6119 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6120 #endif
6121 #ifndef WIFEXITED
6122 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6123 #endif
6124 @end group
6125 @end example
6127 @noindent
6128 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6129 variable.
6131 This macro is obsolescent, as current systems are compatible with Posix.
6132 New programs need not use this macro.
6133 @end defmac
6135 @cvindex _POSIX_VERSION
6136 @hdrindex{unistd.h}
6137 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6138 Posix systems.  If there is no @file{unistd.h}, it is definitely
6139 not a Posix system.  However, some non-Posix systems do
6140 have @file{unistd.h}.
6142 The way to check whether the system supports Posix is:
6144 @example
6145 @group
6146 #ifdef HAVE_UNISTD_H
6147 # include <sys/types.h>
6148 # include <unistd.h>
6149 #endif
6151 #ifdef _POSIX_VERSION
6152 /* Code for Posix systems.  */
6153 #endif
6154 @end group
6155 @end example
6157 @anchor{AC_HEADER_TIME}
6158 @defmac AC_HEADER_TIME
6159 @acindex{HEADER_TIME}
6160 @cvindex TIME_WITH_SYS_TIME
6161 @hdrindex{time.h}
6162 @hdrindex{sys/time.h}
6163 @caindex header_time
6164 If a program may include both @file{time.h} and @file{sys/time.h},
6165 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6166 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6167 protected against multiple inclusion, so programs could not explicitly
6168 include both files.  This macro is useful in programs that use, for
6169 example, @code{struct timeval} as well as
6170 @code{struct tm}.  It is best used in conjunction with
6171 @code{HAVE_SYS_TIME_H}, which can be checked for using
6172 @code{AC_CHECK_HEADERS([sys/time.h])}.
6174 @example
6175 @group
6176 #ifdef TIME_WITH_SYS_TIME
6177 # include <sys/time.h>
6178 # include <time.h>
6179 #else
6180 # ifdef HAVE_SYS_TIME_H
6181 #  include <sys/time.h>
6182 # else
6183 #  include <time.h>
6184 # endif
6185 #endif
6186 @end group
6187 @end example
6189 @noindent
6190 This macro caches its result in the @code{ac_cv_header_time} variable.
6192 This macro is obsolescent, as current systems can include both files
6193 when they exist.  New programs need not use this macro.
6194 @end defmac
6197 @defmac AC_HEADER_TIOCGWINSZ
6198 @acindex{HEADER_TIOCGWINSZ}
6199 @cvindex GWINSZ_IN_SYS_IOCTL
6200 @hdrindex{sys/ioctl.h}
6201 @hdrindex{termios.h}
6202 @c FIXME: I need clarifications from Jim.
6203 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6204 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6205 found in @file{<termios.h>}.
6207 Use:
6209 @example
6210 @group
6211 #ifdef HAVE_TERMIOS_H
6212 # include <termios.h>
6213 #endif
6215 #ifdef GWINSZ_IN_SYS_IOCTL
6216 # include <sys/ioctl.h>
6217 #endif
6218 @end group
6219 @end example
6220 @end defmac
6222 @node Generic Headers
6223 @subsection Generic Header Checks
6225 These macros are used to find system header files not covered by the
6226 ``particular'' test macros.  If you need to check the contents of a header
6227 as well as find out whether it is present, you have to write your own
6228 test for it (@pxref{Writing Tests}).
6230 @anchor{AC_CHECK_HEADER}
6231 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6232   @ovar{action-if-not-found}, @ovar{includes})
6233 @acindex{CHECK_HEADER}
6234 @caindex header_@var{header-file}
6235 If the system header file @var{header-file} is compilable, execute shell
6236 commands @var{action-if-found}, otherwise execute
6237 @var{action-if-not-found}.  If you just want to define a symbol if the
6238 header file is available, consider using @code{AC_CHECK_HEADERS}
6239 instead.
6241 @var{includes} is decoded to determine the appropriate include
6242 directives.  If omitted or empty, @file{configure} will check for both header
6243 existence (with the preprocessor) and usability (with the compiler),
6244 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6245 there is a discrepancy between the results, a warning is issued to the
6246 user, and the compiler results are favored (@pxref{Present But
6247 Cannot Be Compiled}).  In general, favoring the compiler results means
6248 that a header will be treated as not found even though the file exists,
6249 because you did not provide enough prerequisites.
6251 Providing a non-empty @var{includes} argument allows the code to provide
6252 any prerequisites prior to including the header under test; it is common
6253 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6254 Includes}).  With an explicit fourth argument, no preprocessor test is
6255 needed.  As a special case, an @var{includes} of exactly @samp{-}
6256 triggers the older preprocessor check, which merely determines existence
6257 of the file in the preprocessor search path; this should only be used as
6258 a last resort (it is safer to determine the actual prerequisites and
6259 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6260 it obvious that only a preprocessor check is desired).
6262 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6263 variable, with characters not suitable for a variable name mapped to
6264 underscores.
6265 @end defmac
6267 @anchor{AC_CHECK_HEADERS}
6268 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6269   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6270   @ovar{includes})
6271 @acindex{CHECK_HEADERS}
6272 @cvindex HAVE_@var{header}
6273 @caindex header_@var{header-file}
6274 For each given system header file @var{header-file} in the
6275 blank-separated argument list that exists, define
6276 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6277 is given, it is additional shell code to execute when one of the header
6278 files is found.  You can give it a value of @samp{break} to break out of
6279 the loop on the first match.  If @var{action-if-not-found} is given, it
6280 is executed when one of the header files is not found.
6282 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6283 choose the set of preprocessor directives supplied before the header
6284 under test.
6286 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6287 variable, with characters not suitable for a variable name mapped to
6288 underscores.
6289 @end defmac
6291 Previous versions of Autoconf merely checked whether the header was
6292 accepted by the preprocessor.  This was changed because the old test was
6293 inappropriate for typical uses.  Headers are typically used to compile,
6294 not merely to preprocess, and the old behavior sometimes accepted
6295 headers that clashed at compile-time (@pxref{Present But Cannot Be
6296 Compiled}).  If you need to check whether a header is preprocessable,
6297 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6299 Actually requiring a header to compile improves the robustness of the
6300 test, but it also requires
6301 that you make sure that headers that must be included before the
6302 @var{header-file} be part of the @var{includes}, (@pxref{Default
6303 Includes}).  If looking for @file{bar.h}, which requires that
6304 @file{foo.h} be included before if it exists, we suggest the following
6305 scheme:
6307 @verbatim
6308 AC_CHECK_HEADERS([foo.h])
6309 AC_CHECK_HEADERS([bar.h], [], [],
6310 [#ifdef HAVE_FOO_H
6311 # include <foo.h>
6312 #endif
6314 @end verbatim
6316 The following variant generates smaller, faster @command{configure}
6317 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6319 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6320 @acindex{CHECK_HEADERS_ONCE}
6321 @cvindex HAVE_@var{header}
6322 For each given system header file @var{header-file} in the
6323 blank-separated argument list that exists, define
6324 @code{HAVE_@var{header-file}} (in all capitals).
6325 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6326 checking code at most once, so that @command{configure} is smaller and
6327 faster; but the checks cannot be conditionalized and are always done once,
6328 early during the @command{configure} run.  Thus, this macro is only safe
6329 for checking headers that do not have prerequisites beyond what
6330 @code{AC_INCLUDES_DEFAULT} provides.
6331 @end defmac
6333 @node Declarations
6334 @section Declarations
6335 @cindex Declaration, checking
6337 The following macros check for the declaration of variables and
6338 functions.  If there is no macro specifically defined to check for a
6339 symbol you need, then you can use the general macros (@pxref{Generic
6340 Declarations}) or, for more complex tests, you may use
6341 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6343 @menu
6344 * Particular Declarations::     Macros to check for certain declarations
6345 * Generic Declarations::        How to find other declarations
6346 @end menu
6348 @node Particular Declarations
6349 @subsection Particular Declaration Checks
6351 There are no specific macros for declarations.
6353 @node Generic Declarations
6354 @subsection Generic Declaration Checks
6356 These macros are used to find declarations not covered by the ``particular''
6357 test macros.
6359 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6360   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6361 @acindex{CHECK_DECL}
6362 @caindex have_decl_@var{symbol}
6363 If @var{symbol} (a function, variable, or constant) is not declared in
6364 @var{includes} and a declaration is needed, run the shell commands
6365 @var{action-if-not-found}, otherwise @var{action-if-found}.
6366 @var{includes} is a series of include directives, defaulting to
6367 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6368 prior to the declaration under test.
6370 This macro actually tests whether @var{symbol} is defined as a macro or
6371 can be used as an r-value, not whether it is really declared, because it
6372 is much safer to avoid introducing extra declarations when they are not
6373 needed.  In order to facilitate use of C++ and overloaded function
6374 declarations, it is possible to specify function argument types in
6375 parentheses for types which can be zero-initialized:
6377 @example
6378 AC_CHECK_DECL([basename(char *)])
6379 @end example
6381 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6382 variable, with characters not suitable for a variable name mapped to
6383 underscores.
6384 @end defmac
6386 @anchor{AC_CHECK_DECLS}
6387 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6388   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6389 @acindex{CHECK_DECLS}
6390 @cvindex HAVE_DECL_@var{symbol}
6391 @caindex have_decl_@var{symbol}
6392 For each of the @var{symbols} (@emph{comma}-separated list with optional
6393 function argument types for C++ overloads), define
6394 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6395 @var{symbol} is declared, otherwise to @samp{0}.  If
6396 @var{action-if-not-found} is given, it is additional shell code to
6397 execute when one of the function declarations is needed, otherwise
6398 @var{action-if-found} is executed.
6400 @var{includes} is a series of include directives, defaulting to
6401 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6402 prior to the declarations under test.
6404 This macro uses an M4 list as first argument:
6405 @example
6406 AC_CHECK_DECLS([strdup])
6407 AC_CHECK_DECLS([strlen])
6408 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6409 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6410 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6411 @end example
6413 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6414 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6415 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6416 @emph{sure} that the check was performed, use
6417 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6419 @example
6420 #if !HAVE_DECL_SYMBOL
6421 extern char *symbol;
6422 #endif
6423 @end example
6425 @noindent
6426 If the test may have not been performed, however, because it is safer
6427 @emph{not} to declare a symbol than to use a declaration that conflicts
6428 with the system's one, you should use:
6430 @example
6431 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6432 void *malloc (size_t *s);
6433 #endif
6434 @end example
6436 @noindent
6437 You fall into the second category only in extreme situations: either
6438 your files may be used without being configured, or they are used during
6439 the configuration.  In most cases the traditional approach is enough.
6441 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6442 variables, with characters not suitable for a variable name mapped to
6443 underscores.
6444 @end defmac
6446 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6447 @acindex{CHECK_DECLS_ONCE}
6448 @cvindex HAVE_DECL_@var{symbol}
6449 For each of the @var{symbols} (@emph{comma}-separated list), define
6450 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6451 @var{symbol} is declared in the default include files, otherwise to
6452 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6453 generates the checking code at most once, so that @command{configure} is
6454 smaller and faster; but the checks cannot be conditionalized and are
6455 always done once, early during the @command{configure} run.
6456 @end defmac
6459 @node Structures
6460 @section Structures
6461 @cindex Structure, checking
6463 The following macros check for the presence of certain members in C
6464 structures.  If there is no macro specifically defined to check for a
6465 member you need, then you can use the general structure-member macros
6466 (@pxref{Generic Structures}) or, for more complex tests, you may use
6467 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6469 @menu
6470 * Particular Structures::       Macros to check for certain structure members
6471 * Generic Structures::          How to find other structure members
6472 @end menu
6474 @node Particular Structures
6475 @subsection Particular Structure Checks
6477 The following macros check for certain structures or structure members.
6479 @defmac AC_STRUCT_DIRENT_D_INO
6480 @acindex{STRUCT_DIRENT_D_INO}
6481 @cvindex HAVE_STRUCT_DIRENT_D_INO
6482 @c @caindex header_dirent_dirent_h
6483 @c @caindex member_struct_dirent_d_ino
6484 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6485 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6486 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6488 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6489 @code{d_ino}, not whether its contents are always reliable.
6490 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6491 though current systems hide this detail from the user and never return
6492 zero @code{d_ino} values.
6493 Many current systems report an incorrect @code{d_ino} for a directory
6494 entry that is a mount point.
6495 @end defmac
6497 @defmac AC_STRUCT_DIRENT_D_TYPE
6498 @acindex{STRUCT_DIRENT_D_TYPE}
6499 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6500 @c @caindex header_dirent_dirent_h
6501 @c @caindex member_struct_dirent_d_type
6502 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6503 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6504 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6505 @end defmac
6507 @anchor{AC_STRUCT_ST_BLOCKS}
6508 @defmac AC_STRUCT_ST_BLOCKS
6509 @acindex{STRUCT_ST_BLOCKS}
6510 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6511 @cvindex HAVE_ST_BLOCKS
6512 @ovindex LIBOBJS
6513 @caindex member_struct_stat_st_blocks
6514 If @code{struct stat} contains an @code{st_blocks} member, define
6515 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6516 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6517 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6518 future.
6520 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6521 variable.
6522 @end defmac
6524 @defmac AC_STRUCT_TM
6525 @acindex{STRUCT_TM}
6526 @cvindex TM_IN_SYS_TIME
6527 @hdrindex{time.h}
6528 @hdrindex{sys/time.h}
6529 If @file{time.h} does not define @code{struct tm}, define
6530 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6531 had better define @code{struct tm}.
6533 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6534 current systems.  New programs need not use this macro.
6535 @end defmac
6537 @anchor{AC_STRUCT_TIMEZONE}
6538 @defmac AC_STRUCT_TIMEZONE
6539 @acindex{STRUCT_TIMEZONE}
6540 @cvindex HAVE_DECL_TZNAME
6541 @cvindex HAVE_STRUCT_TM_TM_ZONE
6542 @cvindex HAVE_TM_ZONE
6543 @cvindex HAVE_TZNAME
6544 @c @caindex member_struct_tm_tm_zone
6545 @c @caindex struct_tm
6546 Figure out how to get the current timezone.  If @code{struct tm} has a
6547 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6548 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6549 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6550 define @code{HAVE_DECL_TZNAME}.
6551 @end defmac
6553 @node Generic Structures
6554 @subsection Generic Structure Checks
6556 These macros are used to find structure members not covered by the
6557 ``particular'' test macros.
6559 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6560   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6561   @dvar{includes, AC_INCLUDES_DEFAULT})
6562 @acindex{CHECK_MEMBER}
6563 @caindex member_@var{aggregate}_@var{member}
6564 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6565 If no @var{includes} are specified, the default includes are used
6566 (@pxref{Default Includes}).
6568 @example
6569 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6570                 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6571                 [[#include <pwd.h>]])
6572 @end example
6574 You can use this macro for submembers:
6576 @example
6577 AC_CHECK_MEMBER(struct top.middle.bot)
6578 @end example
6580 This macro caches its result in the
6581 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6582 characters not suitable for a variable name mapped to underscores.
6583 @end defmac
6585 @anchor{AC_CHECK_MEMBERS}
6586 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6587   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6588 @acindex{CHECK_MEMBERS}
6589 @cvindex HAVE_@var{aggregate}_@var{member}
6590 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6591 @var{members} using the previous macro.  When @var{member} belongs to
6592 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6593 capitals, with spaces and dots replaced by underscores).  If
6594 @var{action-if-found} is given, it is executed for each of the found
6595 members.  If @var{action-if-not-found} is given, it is executed for each
6596 of the members that could not be found.
6598 @var{includes} is a series of include directives, defaulting to
6599 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6600 prior to the members under test.
6602 This macro uses M4 lists:
6603 @example
6604 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6605 @end example
6606 @end defmac
6609 @node Types
6610 @section Types
6611 @cindex Types
6612 @cindex C types
6614 The following macros check for C types, either builtin or typedefs.  If
6615 there is no macro specifically defined to check for a type you need, and
6616 you don't need to check for any special properties of it, then you can
6617 use a general type-check macro.
6619 @menu
6620 * Particular Types::            Special handling to find certain types
6621 * Generic Types::               How to find other types
6622 @end menu
6624 @node Particular Types
6625 @subsection Particular Type Checks
6627 @hdrindex{sys/types.h}
6628 @hdrindex{stdlib.h}
6629 @hdrindex{stdint.h}
6630 @hdrindex{inttypes.h}
6631 These macros check for particular C types in @file{sys/types.h},
6632 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6633 exist.
6635 The Gnulib @code{stdint} module is an alternate way to define many of
6636 these symbols; it is useful if you prefer your code to assume a
6637 C99-or-better environment.  @xref{Gnulib}.
6639 @anchor{AC_TYPE_GETGROUPS}
6640 @defmac AC_TYPE_GETGROUPS
6641 @acindex{TYPE_GETGROUPS}
6642 @cvindex GETGROUPS_T
6643 @caindex type_getgroups
6644 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6645 is the base type of the array argument to @code{getgroups}.
6647 This macro caches the base type in the @code{ac_cv_type_getgroups}
6648 variable.
6649 @end defmac
6651 @defmac AC_TYPE_INT8_T
6652 @acindex{TYPE_INT8_T}
6653 @cvindex HAVE_INT8_T
6654 @cvindex int8_t
6655 @caindex c_int8_t
6656 If @file{stdint.h} or @file{inttypes.h} does not define the type
6657 @code{int8_t}, define @code{int8_t} to a signed
6658 integer type that is exactly 8 bits wide and that uses two's complement
6659 representation, if such a type exists.
6660 If you are worried about porting to hosts that lack such a type, you can
6661 use the results of this macro in C89-or-later code as follows:
6663 @example
6664 #if HAVE_STDINT_H
6665 # include <stdint.h>
6666 #endif
6667 #if defined INT8_MAX || defined int8_t
6668  @emph{code using int8_t}
6669 #else
6670  @emph{complicated alternative using >8-bit 'signed char'}
6671 #endif
6672 @end example
6674 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6675 @end defmac
6677 @defmac AC_TYPE_INT16_T
6678 @acindex{TYPE_INT16_T}
6679 @cvindex HAVE_INT16_T
6680 @cvindex int16_t
6681 @caindex c_int16_t
6682 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6683 @end defmac
6685 @defmac AC_TYPE_INT32_T
6686 @acindex{TYPE_INT32_T}
6687 @cvindex HAVE_INT32_T
6688 @cvindex int32_t
6689 @caindex c_int32_t
6690 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6691 @end defmac
6693 @defmac AC_TYPE_INT64_T
6694 @acindex{TYPE_INT64_T}
6695 @cvindex HAVE_INT64_T
6696 @cvindex int64_t
6697 @caindex c_int64_t
6698 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6699 @end defmac
6701 @defmac AC_TYPE_INTMAX_T
6702 @acindex{TYPE_INTMAX_T}
6703 @cvindex HAVE_INTMAX_T
6704 @cvindex intmax_t
6705 @c @caindex type_intmax_t
6706 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6707 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6708 widest signed integer type.
6709 @end defmac
6711 @defmac AC_TYPE_INTPTR_T
6712 @acindex{TYPE_INTPTR_T}
6713 @cvindex HAVE_INTPTR_T
6714 @cvindex intptr_t
6715 @c @caindex type_intptr_t
6716 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6717 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6718 signed integer type wide enough to hold a pointer, if such a type
6719 exists.
6720 @end defmac
6722 @defmac AC_TYPE_LONG_DOUBLE
6723 @acindex{TYPE_LONG_DOUBLE}
6724 @cvindex HAVE_LONG_DOUBLE
6725 @caindex type_long_double
6726 If the C compiler supports a working @code{long double} type, define
6727 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6728 same range and precision as @code{double}.
6730 This macro caches its result in the @code{ac_cv_type_long_double}
6731 variable.
6733 This macro is obsolescent, as current C compilers support @code{long
6734 double}.  New programs need not use this macro.
6735 @end defmac
6737 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6738 @acindex{TYPE_LONG_DOUBLE_WIDER}
6739 @cvindex HAVE_LONG_DOUBLE_WIDER
6740 @caindex type_long_double_wider
6741 If the C compiler supports a working @code{long double} type with more
6742 range or precision than the @code{double} type, define
6743 @code{HAVE_LONG_DOUBLE_WIDER}.
6745 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6746 variable.
6747 @end defmac
6749 @defmac AC_TYPE_LONG_LONG_INT
6750 @acindex{TYPE_LONG_LONG_INT}
6751 @cvindex HAVE_LONG_LONG_INT
6752 @caindex type_long_long_int
6753 If the C compiler supports a working @code{long long int} type, define
6754 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6755 @code{long long int} values in preprocessor @code{#if} expressions,
6756 because too many compilers mishandle such expressions.
6757 @xref{Preprocessor Arithmetic}.
6759 This macro caches its result in the @code{ac_cv_type_long_long_int}
6760 variable.
6761 @end defmac
6763 @defmac AC_TYPE_MBSTATE_T
6764 @acindex{TYPE_MBSTATE_T}
6765 @cvindex mbstate_t
6766 @hdrindex{wchar.h}
6767 @caindex type_mbstate_t
6768 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6769 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6770 @code{<wchar.h>} does not declare it.
6772 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6773 variable.
6774 @end defmac
6776 @anchor{AC_TYPE_MODE_T}
6777 @defmac AC_TYPE_MODE_T
6778 @acindex{TYPE_MODE_T}
6779 @cvindex mode_t
6780 @caindex type_mode_t
6781 Define @code{mode_t} to a suitable type, if standard headers do not
6782 define it.
6784 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6785 @end defmac
6787 @anchor{AC_TYPE_OFF_T}
6788 @defmac AC_TYPE_OFF_T
6789 @acindex{TYPE_OFF_T}
6790 @cvindex off_t
6791 @caindex type_off_t
6792 Define @code{off_t} to a suitable type, if standard headers do not
6793 define it.
6795 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6796 @end defmac
6798 @anchor{AC_TYPE_PID_T}
6799 @defmac AC_TYPE_PID_T
6800 @acindex{TYPE_PID_T}
6801 @cvindex pid_t
6802 @caindex type_pid_t
6803 Define @code{pid_t} to a suitable type, if standard headers do not
6804 define it.
6806 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6807 @end defmac
6809 @anchor{AC_TYPE_SIZE_T}
6810 @defmac AC_TYPE_SIZE_T
6811 @acindex{TYPE_SIZE_T}
6812 @cvindex size_t
6813 @caindex type_size_t
6814 Define @code{size_t} to a suitable type, if standard headers do not
6815 define it.
6817 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6818 @end defmac
6820 @defmac AC_TYPE_SSIZE_T
6821 @acindex{TYPE_SSIZE_T}
6822 @cvindex ssize_t
6823 @caindex type_ssize_t
6824 Define @code{ssize_t} to a suitable type, if standard headers do not
6825 define it.
6827 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6828 @end defmac
6830 @anchor{AC_TYPE_UID_T}
6831 @defmac AC_TYPE_UID_T
6832 @acindex{TYPE_UID_T}
6833 @cvindex uid_t
6834 @cvindex gid_t
6835 @caindex type_uid_t
6836 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6837 headers do not define them.
6839 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6840 @end defmac
6842 @defmac AC_TYPE_UINT8_T
6843 @acindex{TYPE_UINT8_T}
6844 @cvindex HAVE_UINT8_T
6845 @cvindex uint8_t
6846 @caindex c_uint8_t
6847 If @file{stdint.h} or @file{inttypes.h} does not define the type
6848 @code{uint8_t}, define @code{uint8_t} to an
6849 unsigned integer type that is exactly 8 bits wide, if such a type
6850 exists.
6851 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6852 @end defmac
6854 @defmac AC_TYPE_UINT16_T
6855 @acindex{TYPE_UINT16_T}
6856 @cvindex HAVE_UINT16_T
6857 @cvindex uint16_t
6858 @caindex c_uint16_t
6859 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6860 @end defmac
6862 @defmac AC_TYPE_UINT32_T
6863 @acindex{TYPE_UINT32_T}
6864 @cvindex HAVE_UINT32_T
6865 @cvindex uint32_t
6866 @caindex c_uint32_t
6867 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6868 @end defmac
6870 @defmac AC_TYPE_UINT64_T
6871 @acindex{TYPE_UINT64_T}
6872 @cvindex HAVE_UINT64_T
6873 @cvindex uint64_t
6874 @caindex c_uint64_t
6875 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6876 @end defmac
6878 @defmac AC_TYPE_UINTMAX_T
6879 @acindex{TYPE_UINTMAX_T}
6880 @cvindex HAVE_UINTMAX_T
6881 @cvindex uintmax_t
6882 @c @caindex type_uintmax_t
6883 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6884 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6885 widest unsigned integer type.
6886 @end defmac
6888 @defmac AC_TYPE_UINTPTR_T
6889 @acindex{TYPE_UINTPTR_T}
6890 @cvindex HAVE_UINTPTR_T
6891 @cvindex uintptr_t
6892 @c @caindex type_uintptr_t
6893 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6894 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6895 unsigned integer type wide enough to hold a pointer, if such a type
6896 exists.
6897 @end defmac
6899 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6900 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6901 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6902 @caindex type_unsigned_long_long_int
6903 If the C compiler supports a working @code{unsigned long long int} type,
6904 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6905 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6906 because too many compilers mishandle such expressions.
6907 @xref{Preprocessor Arithmetic}.
6909 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6910 variable.
6911 @end defmac
6913 @node Generic Types
6914 @subsection Generic Type Checks
6916 These macros are used to check for types not covered by the ``particular''
6917 test macros.
6919 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6920   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6921 @acindex{CHECK_TYPE}
6922 @caindex type_@var{type}
6923 Check whether @var{type} is defined.  It may be a compiler builtin type
6924 or defined by the @var{includes}.  @var{includes} is a series of include
6925 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6926 Includes}), which are used prior to the type under test.
6928 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6929 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6930 same test is applied when compiling for C++, which means that in C++
6931 @var{type} should be a type-id and should not be an anonymous
6932 @samp{struct} or @samp{union}.
6934 This macro caches its result in the @code{ac_cv_type_@var{type}}
6935 variable, with @samp{*} mapped to @samp{p} and other characters not
6936 suitable for a variable name mapped to underscores.
6937 @end defmac
6940 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6941   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6942 @acindex{CHECK_TYPES}
6943 @cvindex HAVE_@var{type}
6944 For each @var{type} of the @var{types} that is defined, define
6945 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6946 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6947 specified, the default includes are used (@pxref{Default Includes}).  If
6948 @var{action-if-found} is given, it is additional shell code to execute
6949 when one of the types is found.  If @var{action-if-not-found} is given,
6950 it is executed when one of the types is not found.
6952 This macro uses M4 lists:
6953 @example
6954 AC_CHECK_TYPES([ptrdiff_t])
6955 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6956 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6957 @end example
6959 @end defmac
6961 Autoconf, up to 2.13, used to provide to another version of
6962 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6963 compatibility, a simple heuristic, quite safe but not totally, is
6964 implemented.  In case of doubt, read the documentation of the former
6965 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6968 @node Compilers and Preprocessors
6969 @section Compilers and Preprocessors
6970 @cindex Compilers
6971 @cindex Preprocessors
6973 @ovindex EXEEXT
6974 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6975 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6976 the output of the compiler, typically to the empty string if
6977 Posix and @samp{.exe} if a DOS variant.
6979 @ovindex OBJEXT
6980 They also define the output variable @code{OBJEXT} based on the
6981 output of the compiler, after @file{.c} files have been excluded, typically
6982 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6984 If the compiler being used does not produce executables, the tests fail.  If
6985 the executables can't be run, and cross-compilation is not enabled, they
6986 fail too.  @xref{Manual Configuration}, for more on support for cross
6987 compiling.
6989 @menu
6990 * Specific Compiler Characteristics::  Some portability issues
6991 * Generic Compiler Characteristics::  Language independent tests and features
6992 * C Compiler::                  Checking its characteristics
6993 * C++ Compiler::                Likewise
6994 * Objective C Compiler::        Likewise
6995 * Objective C++ Compiler::      Likewise
6996 * Erlang Compiler and Interpreter::  Likewise
6997 * Fortran Compiler::            Likewise
6998 * Go Compiler::                 Likewise
6999 @end menu
7001 @node Specific Compiler Characteristics
7002 @subsection Specific Compiler Characteristics
7004 Some compilers exhibit different behaviors.
7006 @table @asis
7007 @item Static/Dynamic Expressions
7008 Autoconf relies on a trick to extract one bit of information from the C
7009 compiler: using negative array sizes.  For instance the following
7010 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7011 bytes wide:
7013 @example
7014 static int test_array[sizeof (int) == 4 ? 1 : -1];
7015 @end example
7017 @noindent
7018 To our knowledge, there is a single compiler that does not support this
7019 trick: the HP C compilers (the real ones, not only the
7020 ``bundled'') on HP-UX 11.00.
7021 They incorrectly reject the above program with the diagnostic
7022 ``Variable-length arrays cannot have static storage.''
7023 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7024 not from the @code{? 1 : -1}, and
7025 Autoconf works around this problem by casting @code{sizeof (int)} to
7026 @code{long int} before comparing it.
7027 @end table
7029 @node Generic Compiler Characteristics
7030 @subsection Generic Compiler Characteristics
7032 @anchor{AC_CHECK_SIZEOF}
7033 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7034   @dvar{includes, AC_INCLUDES_DEFAULT})
7035 @acindex{CHECK_SIZEOF}
7036 @cvindex SIZEOF_@var{type-or-expr}
7037 @caindex sizeof_@var{type-or-expr}
7038 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7039 the size in bytes of @var{type-or-expr}, which may be either a type or
7040 an expression returning a value that has a size.  If the expression
7041 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7042 @var{includes} is a series of include directives, defaulting to
7043 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7044 prior to the expression under test.
7046 This macro now works even when cross-compiling.  The @var{unused}
7047 argument was used when cross-compiling.
7049 For example, the call
7051 @example
7052 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7053 AC_CHECK_SIZEOF([int *])
7054 @end example
7056 @noindent
7057 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7059 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7060 variable, with @samp{*} mapped to @samp{p} and other characters not
7061 suitable for a variable name mapped to underscores.
7062 @end defmac
7064 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7065 @acindex{CHECK_ALIGNOF}
7066 @cvindex ALIGNOF_@var{type}
7067 @caindex alignof_@var{type-or-expr}
7068 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7069 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7070 a structure member declaration.  If @samp{type} is unknown, the result
7071 is 0.  If no @var{includes} are specified, the default includes are used
7072 (@pxref{Default Includes}).
7074 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7075 variable, with @samp{*} mapped to @samp{p} and other characters not
7076 suitable for a variable name mapped to underscores.
7077 @end defmac
7079 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7080   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7081 @acindex{COMPUTE_INT}
7082 Store into the shell variable @var{var} the value of the integer
7083 @var{expression}.  The
7084 value should fit in an initializer in a C variable of type @code{signed
7085 long}.  To support cross compilation (in which case, the macro only works on
7086 hosts that use twos-complement arithmetic), it should be possible to evaluate
7087 the expression at compile-time.  If no @var{includes} are specified, the
7088 default includes are used (@pxref{Default Includes}).
7090 Execute @var{action-if-fails} if the value cannot be determined correctly.
7091 @end defmac
7093 @defmac AC_LANG_WERROR
7094 @acindex{LANG_WERROR}
7095 Normally Autoconf ignores warnings generated by the compiler, linker, and
7096 preprocessor.  If this macro is used, warnings count as fatal
7097 errors for the current language.  This macro is useful when the
7098 results of configuration are used where warnings are unacceptable; for
7099 instance, if parts of a program are built with the GCC
7100 @option{-Werror}
7101 option.  If the whole program is built using @option{-Werror} it is
7102 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7103 etc.).
7104 @end defmac
7106 @defmac AC_OPENMP
7107 @acindex{OPENMP}
7108 @cvindex _OPENMP
7109 @ovindex OPENMP_CFLAGS
7110 @ovindex OPENMP_CXXFLAGS
7111 @ovindex OPENMP_FFLAGS
7112 @ovindex OPENMP_FCFLAGS
7113 @caindex prog_c_openmp
7114 @caindex prog_cxx_openmp
7115 @caindex prog_f77_openmp
7116 @caindex prog_fc_openmp
7117 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7118 and Fortran that simplify optimization of shared memory parallelism,
7119 which is a common problem on multicore CPUs.
7121 If the current language is C, the macro @code{AC_OPENMP} sets the
7122 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7123 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7124 compiler already supports OpenMP, if it has no way to activate OpenMP
7125 support, or if the user rejects OpenMP support by invoking
7126 @samp{configure} with the @samp{--disable-openmp} option.
7128 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7129 preprocessing program source, and when linking programs.  Therefore you
7130 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7131 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7132 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7133 OpenMP support is revealed at compile time by the preprocessor macro
7134 @code{_OPENMP}.
7136 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7137 shared library to the program's dependencies, so its use is recommended
7138 only on programs that actually require OpenMP.
7140 If the current language is C++, @code{AC_OPENMP} sets the variable
7141 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7142 hold as for C.
7144 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7145 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7146 respectively.  Similar remarks as for C hold, except that
7147 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7148 signals OpenMP support.
7150 For portability, it is best to avoid spaces between @samp{#} and
7151 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7152 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7153 latter.
7155 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7156 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7157 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7158 @end defmac
7160 @node C Compiler
7161 @subsection C Compiler Characteristics
7163 The following macros provide ways to find and exercise a C Compiler.
7164 There are a few constructs that ought to be avoided, but do not deserve
7165 being checked for, since they can easily be worked around.
7167 @table @asis
7168 @item Don't use lines containing solitary backslashes
7169 They tickle a bug in the HP-UX C compiler (checked on
7170 HP-UX 10.20,
7171 11.00, and 11i).  When given the following source:
7173 @example
7174 #ifdef __STDC__
7176 * A comment with backslash-newlines in it.  %@{ %@} *\
7179 char str[] = "\\
7180 " A string with backslash-newlines in it %@{ %@} \\
7182 char apostrophe = '\\
7186 #endif
7187 @end example
7189 @noindent
7190 the compiler incorrectly fails with the diagnostics ``Non-terminating
7191 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7192 Removing the lines with solitary backslashes solves the problem.
7194 @item Don't compile several files at once if output matters to you
7195 Some compilers, such as HP's, report names of files being
7196 compiled when given more than one file operand.  For instance:
7198 @example
7199 $ @kbd{cc a.c b.c}
7200 a.c:
7201 b.c:
7202 @end example
7204 @noindent
7205 This can cause problems if you observe the output of the compiler to
7206 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7207 b.o} solves the issue.
7209 @item Don't rely on @code{#error} failing
7210 The IRIX C compiler does not fail when #error is preprocessed; it
7211 simply emits a diagnostic and continues, exiting successfully.  So,
7212 instead of an error directive like @code{#error "Unsupported word size"}
7213 it is more portable to use an invalid directive like @code{#Unsupported
7214 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7215 OK, since installers with inadequate compilers like IRIX can simply
7216 examine these compilers' diagnostic output.
7218 @item Don't rely on correct @code{#line} support
7219 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7220 diagnoses @code{#line} directives whose line
7221 numbers are greater than 32767.  Nothing in Posix
7222 makes this invalid.  That is why Autoconf stopped issuing
7223 @code{#line} directives.
7224 @end table
7226 @anchor{AC_PROG_CC}
7227 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7228 @acindex{PROG_CC}
7229 @evindex CC
7230 @evindex CFLAGS
7231 @ovindex CC
7232 @ovindex CFLAGS
7233 @caindex prog_cc_stdc
7234 Determine a C compiler to use.  If @code{CC} is not already set in the
7235 environment, check for @code{gcc} and @code{cc}, then for other C
7236 compilers.  Set output variable @code{CC} to the name of the compiler
7237 found.
7239 This macro may, however, be invoked with an optional first argument
7240 which, if specified, must be a blank-separated list of C compilers to
7241 search for.  This just gives the user an opportunity to specify an
7242 alternative search list for the C compiler.  For example, if you didn't
7243 like the default order, then you could invoke @code{AC_PROG_CC} like
7244 this:
7246 @example
7247 AC_PROG_CC([gcc cl cc])
7248 @end example
7250 If the C compiler cannot compile ISO Standard C (currently
7251 C11), try to add an option to output variable @code{CC} to make it work.
7252 If the compiler does not support C11, fall back to supporting
7253 ISO C99; if C99 does not work, fall back to ANSI C89 (ISO C90).
7254 When testing for ISO C versions, use GNU extensions if available.
7255 After calling this macro you can check whether the C compiler has been
7256 set to accept Standard C; if not, the shell variable
7257 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7259 If using the GNU C compiler, set shell variable @code{GCC} to
7260 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7261 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7262 where GCC does not accept @option{-g}), or @option{-g} for
7263 other compilers.  If your package does not like this default, then it is
7264 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7265 and before @code{AC_PROG_CC} to select an empty default instead.
7267 Many Autoconf macros use a compiler, and thus call
7268 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7269 determined before the body of the outermost @code{AC_DEFUN} macro.
7270 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7271 performs certain checks (such as the proper value of @env{EXEEXT}) only
7272 on the first invocation.  Therefore, care must be used when invoking
7273 this macro from within another macro rather than at the top level
7274 (@pxref{Expanded Before Required}).
7275 @end defmac
7277 @anchor{AC_PROG_CC_C_O}
7278 @defmac AC_PROG_CC_C_O
7279 @acindex{PROG_CC_C_O}
7280 @cvindex NO_MINUS_C_MINUS_O
7281 @caindex prog_cc_@var{compiler}_c_o
7282 If the C compiler does not accept the @option{-c} and @option{-o} options
7283 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7284 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7285 the first @code{cc} in the path.  The test fails if one fails.  This
7286 macro was created for GNU Make to choose the default C compilation
7287 rule.
7289 For the compiler @var{compiler}, this macro caches its result in the
7290 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7291 @end defmac
7294 @defmac AC_PROG_CPP
7295 @acindex{PROG_CPP}
7296 @evindex CPP
7297 @ovindex CPP
7298 Set output variable @code{CPP} to a command that runs the
7299 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7300 It is only portable to run @code{CPP} on files with a @file{.c}
7301 extension.
7303 Some preprocessors don't indicate missing include files by the error
7304 status.  For such preprocessors an internal variable is set that causes
7305 other macros to check the standard error from the preprocessor and
7306 consider the test failed if any warnings have been reported.
7307 For most preprocessors, though, warnings do not cause include-file
7308 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7309 @end defmac
7311 @defmac AC_PROG_CPP_WERROR
7312 @acindex{PROG_CPP_WERROR}
7313 @ovindex CPP
7314 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7315 preprocessor as errors even if the preprocessor exit status indicates
7316 success.  This is useful for avoiding headers that generate mandatory
7317 warnings, such as deprecation notices.
7318 @end defmac
7321 The following macros check for C compiler or machine architecture
7322 features.  To check for characteristics not listed here, use
7323 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7324 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7326 @defmac AC_PROG_CC_C89
7327 @acindex{PROG_CC_C89}
7328 @caindex prog_cc_c89
7329 If the C compiler is not in ANSI C89 (ISO C90) mode by
7330 default, try to add an option to output variable @code{CC} to make it
7331 so.  This macro tries various options that select ANSI C89 on
7332 some system or another, preferring extended functionality modes over
7333 strict conformance modes.  It considers the compiler to be in
7334 ANSI C89 mode if it handles function prototypes correctly.
7336 After calling this macro you can check whether the C compiler has been
7337 set to accept ANSI C89; if not, the shell variable
7338 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7340 This macro is rarely needed.  It should be used only if your application
7341 requires C89 and will not work in later C versions.  Typical applications
7342 should use @code{AC_PROG_CC} instead.
7343 @end defmac
7345 @defmac AC_PROG_CC_C99
7346 @acindex{PROG_CC_C99}
7347 @caindex prog_cc_c99
7348 If the C compiler is not in C99 mode by default, try to add an
7349 option to output variable @code{CC} to make it so.  This macro tries
7350 various options that select C99 on some system or another, preferring
7351 extended functionality modes over strict conformance modes.  It
7352 considers the compiler to be in C99 mode if it handles @code{_Bool},
7353 @code{//} comments, flexible array members, @code{inline}, signed and
7354 unsigned @code{long long int}, mixed code and declarations, named
7355 initialization of structs,
7356 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7357 in @code{for} loops, and variable length arrays.
7359 After calling this macro you can check whether the C compiler has been
7360 set to accept C99; if not, the shell variable
7361 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7363 This macro is rarely needed.  It should be used only if your application
7364 requires C99 and will not work in later C versions.  Typical applications
7365 should use @code{AC_PROG_CC} instead.
7367 There is no @code{AC_PROG_CC_C11} macro, as no need for one has been
7368 identified.
7369 @end defmac
7371 @defmac AC_C_BACKSLASH_A
7372 @acindex{C_BACKSLASH_A}
7373 @cvindex HAVE_C_BACKSLASH_A
7374 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7375 @samp{\a}.
7377 This macro is obsolescent, as current C compilers understand @samp{\a}.
7378 New programs need not use this macro.
7379 @end defmac
7381 @anchor{AC_C_BIGENDIAN}
7382 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7383   @ovar{action-if-unknown}, @ovar{action-if-universal})
7384 @acindex{C_BIGENDIAN}
7385 @cvindex WORDS_BIGENDIAN
7386 @cindex Endianness
7387 If words are stored with the most significant byte first (like Motorola
7388 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7389 the least significant byte first (like Intel and VAX CPUs), execute
7390 @var{action-if-false}.
7392 This macro runs a test-case if endianness cannot be determined from the
7393 system header files.  When cross-compiling, the test-case is not run but
7394 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7395 the latter case fails to determine the byte sex of the host system.
7397 In some cases a single run of a compiler can generate code for multiple
7398 architectures.  This can happen, for example, when generating Mac OS X
7399 universal binary files, which work on both PowerPC and Intel
7400 architectures.  In this case, the different variants might be for
7401 different architectures whose endiannesses differ.  If
7402 @command{configure} detects this, it executes @var{action-if-universal}
7403 instead of @var{action-if-unknown}.
7405 The default for @var{action-if-true} is to define
7406 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7407 nothing.  The default for @var{action-if-unknown} is to
7408 abort configure and tell the installer how to bypass this test.
7409 And finally, the default for @var{action-if-universal} is to ensure that
7410 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7411 detected and the current code is big-endian; this default works only if
7412 @command{autoheader} is used (@pxref{autoheader Invocation}).
7414 If you use this macro without specifying @var{action-if-universal}, you
7415 should also use @code{AC_CONFIG_HEADERS}; otherwise
7416 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7417 binary files.
7418 @end defmac
7420 @anchor{AC_C_CONST}
7421 @defmac AC_C_CONST
7422 @acindex{C_CONST}
7423 @cvindex const
7424 @caindex c_const
7425 If the C compiler does not fully support the @code{const} keyword,
7426 define @code{const} to be empty.  Some C compilers that do
7427 not define @code{__STDC__} do support @code{const}; some compilers that
7428 define @code{__STDC__} do not completely support @code{const}.  Programs
7429 can simply use @code{const} as if every C compiler supported it; for
7430 those that don't, the makefile or configuration header file
7431 defines it as empty.
7433 Occasionally installers use a C++ compiler to compile C code, typically
7434 because they lack a C compiler.  This causes problems with @code{const},
7435 because C and C++ treat @code{const} differently.  For example:
7437 @example
7438 const int foo;
7439 @end example
7441 @noindent
7442 is valid in C but not in C++.  These differences unfortunately cannot be
7443 papered over by defining @code{const} to be empty.
7445 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7446 as this generally yields better results in practice.  However, using a
7447 C++ compiler to compile C code is not recommended or supported, and
7448 installers who run into trouble in this area should get a C compiler
7449 like GCC to compile their C code.
7451 This macro caches its result in the @code{ac_cv_c_const} variable.
7453 This macro is obsolescent, as current C compilers support @code{const}.
7454 New programs need not use this macro.
7455 @end defmac
7457 @defmac AC_C_RESTRICT
7458 @acindex{C_RESTRICT}
7459 @cvindex restrict
7460 @caindex c_restrict
7461 If the C compiler recognizes a variant spelling for the @code{restrict}
7462 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7463 then define @code{restrict} to that; this is more likely to do the right
7464 thing with compilers that support language variants where plain
7465 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7466 recognizes the @code{restrict} keyword, don't do anything.
7467 Otherwise, define @code{restrict} to be empty.
7468 Thus, programs may simply use @code{restrict} as if every C compiler
7469 supported it; for those that do not, the makefile
7470 or configuration header defines it away.
7472 Although support in C++ for the @code{restrict} keyword is not
7473 required, several C++ compilers do accept the keyword.
7474 This macro works for them, too.
7476 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7477 if @code{restrict} is not supported, and a supported spelling otherwise.
7478 @end defmac
7480 @defmac AC_C_VOLATILE
7481 @acindex{C_VOLATILE}
7482 @cvindex volatile
7483 If the C compiler does not understand the keyword @code{volatile},
7484 define @code{volatile} to be empty.  Programs can simply use
7485 @code{volatile} as if every C compiler supported it; for those that do
7486 not, the makefile or configuration header defines it as
7487 empty.
7489 If the correctness of your program depends on the semantics of
7490 @code{volatile}, simply defining it to be empty does, in a sense, break
7491 your code.  However, given that the compiler does not support
7492 @code{volatile}, you are at its mercy anyway.  At least your
7493 program compiles, when it wouldn't before.
7494 @xref{Volatile Objects}, for more about @code{volatile}.
7496 In general, the @code{volatile} keyword is a standard C feature, so
7497 you might expect that @code{volatile} is available only when
7498 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7499 support volatile, but does not define @code{__STDC__}.
7501 This macro is obsolescent, as current C compilers support @code{volatile}.
7502 New programs need not use this macro.
7503 @end defmac
7505 @anchor{AC_C_INLINE}
7506 @defmac AC_C_INLINE
7507 @acindex{C_INLINE}
7508 @cvindex inline
7509 If the C compiler supports the keyword @code{inline}, do nothing.
7510 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7511 if it accepts one of those, otherwise define @code{inline} to be empty.
7512 @end defmac
7514 @anchor{AC_C_CHAR_UNSIGNED}
7515 @defmac AC_C_CHAR_UNSIGNED
7516 @acindex{C_CHAR_UNSIGNED}
7517 @cvindex __CHAR_UNSIGNED__
7518 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7519 unless the C compiler predefines it.
7521 These days, using this macro is not necessary.  The same information can
7522 be determined by this portable alternative, thus avoiding the use of
7523 preprocessor macros in the namespace reserved for the implementation.
7525 @example
7526 #include <limits.h>
7527 #if CHAR_MIN == 0
7528 # define CHAR_UNSIGNED 1
7529 #endif
7530 @end example
7531 @end defmac
7533 @defmac AC_C_STRINGIZE
7534 @acindex{C_STRINGIZE}
7535 @cvindex HAVE_STRINGIZE
7536 If the C preprocessor supports the stringizing operator, define
7537 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7538 found in macros such as this:
7540 @example
7541 #define x(y) #y
7542 @end example
7544 This macro is obsolescent, as current C compilers support the
7545 stringizing operator.  New programs need not use this macro.
7546 @end defmac
7548 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7549 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7550 @cvindex FLEXIBLE_ARRAY_MEMBER
7551 If the C compiler supports flexible array members, define
7552 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7553 That way, a declaration like this:
7555 @example
7556 struct s
7557   @{
7558     size_t n_vals;
7559     double val[FLEXIBLE_ARRAY_MEMBER];
7560   @};
7561 @end example
7563 @noindent
7564 will let applications use the ``struct hack'' even with compilers that
7565 do not support flexible array members.  To allocate and use such an
7566 object, you can use code like this:
7568 @example
7569 size_t i;
7570 size_t n = compute_value_count ();
7571 struct s *p =
7572    malloc (offsetof (struct s, val)
7573            + n * sizeof (double));
7574 p->n_vals = n;
7575 for (i = 0; i < n; i++)
7576   p->val[i] = compute_value (i);
7577 @end example
7578 @end defmac
7580 @defmac AC_C_VARARRAYS
7581 @acindex{C_VARARRAYS}
7582 @cvindex HAVE_C_VARARRAYS
7583 If the C compiler supports variable-length arrays, define
7584 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7585 storage duration whose length is determined at run time, when the array
7586 is declared.
7587 @end defmac
7589 @defmac AC_C_TYPEOF
7590 @acindex{C_TYPEOF}
7591 @cvindex HAVE_TYPEOF
7592 @cvindex typeof
7593 If the C compiler supports GCC's @code{typeof} syntax either
7594 directly or
7595 through a different spelling of the keyword (e.g., @code{__typeof__}),
7596 define @code{HAVE_TYPEOF}.  If the support is available only through a
7597 different spelling, define @code{typeof} to that spelling.
7598 @end defmac
7600 @defmac AC_C_PROTOTYPES
7601 @acindex{C_PROTOTYPES}
7602 @cvindex PROTOTYPES
7603 @cvindex __PROTOTYPES
7604 @cvindex PARAMS
7605 If function prototypes are understood by the compiler (as determined by
7606 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7607 Defining @code{__PROTOTYPES} is for the benefit of
7608 header files that cannot use macros that infringe on user name space.
7610 This macro is obsolescent, as current C compilers support prototypes.
7611 New programs need not use this macro.
7612 @end defmac
7614 @anchor{AC_PROG_GCC_TRADITIONAL}
7615 @defmac AC_PROG_GCC_TRADITIONAL
7616 @acindex{PROG_GCC_TRADITIONAL}
7617 @ovindex CC
7618 Add @option{-traditional} to output variable @code{CC} if using the
7619 GNU C compiler and @code{ioctl} does not work properly without
7620 @option{-traditional}.  That usually happens when the fixed header files
7621 have not been installed on an old system.
7623 This macro is obsolescent, since current versions of the GNU C
7624 compiler fix the header files automatically when installed.
7625 @end defmac
7628 @node C++ Compiler
7629 @subsection C++ Compiler Characteristics
7632 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7633 @acindex{PROG_CXX}
7634 @evindex CXX
7635 @evindex CXXFLAGS
7636 @ovindex CXX
7637 @ovindex CXXFLAGS
7638 Determine a C++ compiler to use.  Check whether the environment variable
7639 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7640 variable @code{CXX} to its value.
7642 Otherwise, if the macro is invoked without an argument, then search for
7643 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7644 then other names).  If none of those checks succeed, then as a last
7645 resort set @code{CXX} to @code{g++}.
7647 This macro may, however, be invoked with an optional first argument
7648 which, if specified, must be a blank-separated list of C++ compilers to
7649 search for.  This just gives the user an opportunity to specify an
7650 alternative search list for the C++ compiler.  For example, if you
7651 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7652 like this:
7654 @example
7655 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7656 @end example
7658 If using the GNU C++ compiler, set shell variable @code{GXX} to
7659 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7660 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7661 systems where G++ does not accept @option{-g}), or @option{-g} for other
7662 compilers.  If your package does not like this default, then it is
7663 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7664 and before @code{AC_PROG_CXX} to select an empty default instead.
7666 @end defmac
7668 @defmac AC_PROG_CXXCPP
7669 @acindex{PROG_CXXCPP}
7670 @evindex CXXCPP
7671 @ovindex CXXCPP
7672 Set output variable @code{CXXCPP} to a command that runs the C++
7673 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7674 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7675 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7677 Some preprocessors don't indicate missing include files by the error
7678 status.  For such preprocessors an internal variable is set that causes
7679 other macros to check the standard error from the preprocessor and
7680 consider the test failed if any warnings have been reported.  However,
7681 it is not known whether such broken preprocessors exist for C++.
7682 @end defmac
7684 @defmac AC_PROG_CXX_C_O
7685 @acindex{PROG_CXX_C_O}
7686 @cvindex CXX_NO_MINUS_C_MINUS_O
7687 Test whether the C++ compiler accepts the options @option{-c} and
7688 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7689 if it does not.
7690 @end defmac
7693 @node Objective C Compiler
7694 @subsection Objective C Compiler Characteristics
7697 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7698 @acindex{PROG_OBJC}
7699 @evindex OBJC
7700 @evindex OBJCFLAGS
7701 @ovindex OBJC
7702 @ovindex OBJCFLAGS
7703 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7704 set in the environment, check for Objective C compilers.  Set output
7705 variable @code{OBJC} to the name of the compiler found.
7707 This macro may, however, be invoked with an optional first argument
7708 which, if specified, must be a blank-separated list of Objective C compilers to
7709 search for.  This just gives the user an opportunity to specify an
7710 alternative search list for the Objective C compiler.  For example, if you
7711 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7712 like this:
7714 @example
7715 AC_PROG_OBJC([gcc objcc objc])
7716 @end example
7718 If using the GNU Objective C compiler, set shell variable
7719 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7720 already set, set it to @option{-g -O2} for the GNU Objective C
7721 compiler (@option{-O2} on systems where @command{gcc} does not accept
7722 @option{-g}), or @option{-g} for other compilers.
7723 @end defmac
7725 @defmac AC_PROG_OBJCPP
7726 @acindex{PROG_OBJCPP}
7727 @evindex OBJCPP
7728 @ovindex OBJCPP
7729 Set output variable @code{OBJCPP} to a command that runs the Objective C
7730 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7731 @end defmac
7734 @node Objective C++ Compiler
7735 @subsection Objective C++ Compiler Characteristics
7738 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7739 @acindex{PROG_OBJCXX}
7740 @evindex OBJCXX
7741 @evindex OBJCXXFLAGS
7742 @ovindex OBJCXX
7743 @ovindex OBJCXXFLAGS
7744 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7745 set in the environment, check for Objective C++ compilers.  Set output
7746 variable @code{OBJCXX} to the name of the compiler found.
7748 This macro may, however, be invoked with an optional first argument
7749 which, if specified, must be a blank-separated list of Objective C++ compilers
7750 to search for.  This just gives the user an opportunity to specify an
7751 alternative search list for the Objective C++ compiler.  For example, if you
7752 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7753 like this:
7755 @example
7756 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7757 @end example
7759 If using the GNU Objective C++ compiler, set shell variable
7760 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7761 already set, set it to @option{-g -O2} for the GNU Objective C++
7762 compiler (@option{-O2} on systems where @command{gcc} does not accept
7763 @option{-g}), or @option{-g} for other compilers.
7764 @end defmac
7766 @defmac AC_PROG_OBJCXXCPP
7767 @acindex{PROG_OBJCXXCPP}
7768 @evindex OBJCXXCPP
7769 @ovindex OBJCXXCPP
7770 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7771 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7772 @end defmac
7775 @node Erlang Compiler and Interpreter
7776 @subsection Erlang Compiler and Interpreter Characteristics
7777 @cindex Erlang
7779 Autoconf defines the following macros for determining paths to the essential
7780 Erlang/OTP programs:
7782 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7783 @acindex{ERLANG_PATH_ERLC}
7784 @evindex ERLC
7785 @evindex ERLCFLAGS
7786 @ovindex ERLC
7787 @ovindex ERLCFLAGS
7788 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7789 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7790 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7791 is not set in the environment, set it to an empty value.
7793 The two optional arguments have the same meaning as the two last arguments of
7794 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7795 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7796 directory:
7798 @example
7799 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7800 @end example
7801 @end defmac
7803 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7804 @acindex{ERLANG_NEED_ERLC}
7805 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7806 error message and exits the @command{configure} script if the @command{erlc}
7807 program is not found.
7808 @end defmac
7810 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7811 @acindex{ERLANG_PATH_ERL}
7812 @evindex ERL
7813 @ovindex ERL
7814 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7815 set in the
7816 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7817 complete path of the interpreter command found.
7819 The two optional arguments have the same meaning as the two last arguments of
7820 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7821 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7822 directory:
7824 @example
7825 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7826 @end example
7827 @end defmac
7829 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7830 @acindex{ERLANG_NEED_ERL}
7831 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7832 error message and exits the @command{configure} script if the @command{erl}
7833 program is not found.
7834 @end defmac
7837 @node Fortran Compiler
7838 @subsection Fortran Compiler Characteristics
7839 @cindex Fortran
7840 @cindex F77
7842 The Autoconf Fortran support is divided into two categories: legacy
7843 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7844 The former are intended for traditional Fortran 77 code, and have output
7845 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7846 are for newer programs that can (or must) compile under the newer
7847 Fortran standards, and have output variables like @code{FC},
7848 @code{FCFLAGS}, and @code{FCLIBS}.
7850 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7851 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7852 @code{FC} and @code{F77} macros behave almost identically, and so they
7853 are documented together in this section.
7856 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7857 @acindex{PROG_F77}
7858 @evindex F77
7859 @evindex FFLAGS
7860 @ovindex F77
7861 @ovindex FFLAGS
7862 @caindex f77_compiler_gnu
7863 @caindex prog_f77_g
7864 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7865 set in the environment, then check for @code{g77} and @code{f77}, and
7866 then some other names.  Set the output variable @code{F77} to the name
7867 of the compiler found.
7869 This macro may, however, be invoked with an optional first argument
7870 which, if specified, must be a blank-separated list of Fortran 77
7871 compilers to search for.  This just gives the user an opportunity to
7872 specify an alternative search list for the Fortran 77 compiler.  For
7873 example, if you didn't like the default order, then you could invoke
7874 @code{AC_PROG_F77} like this:
7876 @example
7877 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7878 @end example
7880 If using @code{g77} (the GNU Fortran 77 compiler), then
7881 set the shell variable @code{G77} to @samp{yes}.
7882 If the output variable @code{FFLAGS} was not already set in the
7883 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7884 where @code{g77} does not accept @option{-g}).  Otherwise, set
7885 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7887 The result of the GNU test is cached in the
7888 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7889 @code{ac_cv_prog_f77_g} variable.
7890 @end defmac
7892 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7893 @acindex{PROG_FC}
7894 @evindex FC
7895 @evindex FCFLAGS
7896 @ovindex FC
7897 @ovindex FCFLAGS
7898 @caindex fc_compiler_gnu
7899 @caindex prog_fc_g
7900 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7901 the environment, then @code{dialect} is a hint to indicate what Fortran
7902 dialect to search for; the default is to search for the newest available
7903 dialect.  Set the output variable @code{FC} to the name of the compiler
7904 found.
7906 By default, newer dialects are preferred over older dialects, but if
7907 @code{dialect} is specified then older dialects are preferred starting
7908 with the specified dialect.  @code{dialect} can currently be one of
7909 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7910 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7911 and no attempt is made to guarantee that a particular language standard
7912 is actually supported.  Thus, it is preferable that you avoid the
7913 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7914 the latest Fortran standard.
7916 This macro may, alternatively, be invoked with an optional first argument
7917 which, if specified, must be a blank-separated list of Fortran
7918 compilers to search for, just as in @code{AC_PROG_F77}.
7920 If using @code{gfortran} or @code{g77} (the GNU Fortran compilers), then
7921 set the shell variable @code{GFC} to @samp{yes}.
7922 If the output variable @code{FCFLAGS} was not already set in the
7923 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7924 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7925 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7927 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7928 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7929 variable.
7930 @end defmac
7932 @defmac AC_PROG_F77_C_O
7933 @defmacx AC_PROG_FC_C_O
7934 @acindex{PROG_F77_C_O}
7935 @acindex{PROG_FC_C_O}
7936 @cvindex F77_NO_MINUS_C_MINUS_O
7937 @cvindex FC_NO_MINUS_C_MINUS_O
7938 @caindex prog_f77_c_o
7939 @caindex prog_fc_c_o
7940 Test whether the Fortran compiler accepts the options @option{-c} and
7941 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7942 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7944 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7945 @code{ac_cv_prog_fc_c_o} variable, respectively.
7946 @end defmac
7948 The following macros check for Fortran compiler characteristics.
7949 To check for characteristics not listed here, use
7950 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7951 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7952 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7953 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7956 @defmac AC_F77_LIBRARY_LDFLAGS
7957 @defmacx AC_FC_LIBRARY_LDFLAGS
7958 @acindex{F77_LIBRARY_LDFLAGS}
7959 @ovindex FLIBS
7960 @acindex{FC_LIBRARY_LDFLAGS}
7961 @ovindex FCLIBS
7962 @caindex prog_f77_v
7963 @caindex prog_fc_v
7964 @caindex f77_libs
7965 @caindex fc_libs
7966 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7967 @dfn{Fortran intrinsic and runtime libraries} that are required to
7968 successfully link a Fortran program or shared library.  The output
7969 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7970 should be included after @code{LIBS} when linking).
7972 This macro is intended to be used in those situations when it is
7973 necessary to mix, e.g., C++ and Fortran source code in a single
7974 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7975 automake, GNU Automake}).
7977 For example, if object files from a C++ and Fortran compiler must be
7978 linked together, then the C++ compiler/linker must be used for linking
7979 (since special C++-ish things need to happen at link time like calling
7980 global constructors, instantiating templates, enabling exception
7981 support, etc.).
7983 However, the Fortran intrinsic and runtime libraries must be linked in
7984 as well, but the C++ compiler/linker doesn't know by default how to add
7985 these Fortran 77 libraries.  Hence, this macro was created to determine
7986 these Fortran libraries.
7988 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7989 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7990 link C/C++ with Fortran; see below.  Further, it is highly recommended
7991 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7992 because the complex defines that the function wrapper macros create
7993 may not work with C/C++ compiler drivers.
7995 These macros internally compute the flag needed to verbose linking
7996 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
7997 variables, respectively.  The computed linker flags are cached in
7998 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
7999 @end defmac
8001 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8002   @dvar{action-if-not-found, AC_MSG_FAILURE})
8003 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8004   @dvar{action-if-not-found, AC_MSG_FAILURE})
8005 @acindex{F77_DUMMY_MAIN}
8006 @cvindex F77_DUMMY_MAIN
8007 @acindex{FC_DUMMY_MAIN}
8008 @cvindex FC_DUMMY_MAIN
8009 @caindex f77_dummy_main
8010 @caindex fc_dummy_main
8011 With many compilers, the Fortran libraries detected by
8012 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8013 their own @code{main} entry function that initializes things like
8014 Fortran I/O, and which then calls a user-provided entry function named
8015 (say) @code{MAIN__} to run the user's program.  The
8016 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8017 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8018 this interaction.
8020 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8021 one prefers to provide one's own @code{main} and skip the Fortran
8022 library initializations.  In this case, however, one may still need to
8023 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8024 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8025 detects whether any such routine is @emph{required} for linking, and
8026 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8027 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8028 was found, and @code{none} when no such dummy main is needed.
8030 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8031 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8032 @emph{if} it is required.  @var{action-if-not-found} defaults to
8033 exiting with an error.
8035 In order to link with Fortran routines, the user's C/C++ program should
8036 then include the following code to define the dummy main if it is
8037 needed:
8039 @example
8040 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8041 #ifdef F77_DUMMY_MAIN
8042 #  ifdef __cplusplus
8043      extern "C"
8044 #  endif
8045    int F77_DUMMY_MAIN () @{ return 1; @}
8046 #endif
8047 @end example
8049 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8051 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8052 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8053 explicitly unless one wants to change the default actions.
8055 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8056 @code{ac_cv_fc_dummy_main} variable, respectively.
8057 @end defmac
8059 @defmac AC_F77_MAIN
8060 @defmacx AC_FC_MAIN
8061 @acindex{F77_MAIN}
8062 @cvindex F77_MAIN
8063 @acindex{FC_MAIN}
8064 @cvindex FC_MAIN
8065 @caindex f77_main
8066 @caindex fc_main
8067 As discussed above, many Fortran libraries allow you to provide an entry
8068 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8069 is then called by a @code{main} function in the Fortran libraries that
8070 initializes things like Fortran I/O@.  The
8071 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8072 @emph{possible} to utilize such an alternate main function, and defines
8073 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8074 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8075 simply defined to @code{main}.)
8077 Thus, when calling Fortran routines from C that perform things like I/O,
8078 one should use this macro and declare the "main" function like so:
8080 @example
8081 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8082 #ifdef __cplusplus
8083   extern "C"
8084 #endif
8085 int F77_MAIN (int argc, char *argv[]);
8086 @end example
8088 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8090 The result of this macro is cached in the @code{ac_cv_f77_main} or
8091 @code{ac_cv_fc_main} variable, respectively.
8092 @end defmac
8094 @defmac AC_F77_WRAPPERS
8095 @defmacx AC_FC_WRAPPERS
8096 @acindex{F77_WRAPPERS}
8097 @cvindex F77_FUNC
8098 @cvindex F77_FUNC_
8099 @acindex{FC_WRAPPERS}
8100 @cvindex FC_FUNC
8101 @cvindex FC_FUNC_
8102 @caindex f77_mangling
8103 @caindex fc_mangling
8104 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8105 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8106 mangle the names of C/C++ identifiers, and identifiers with underscores,
8107 respectively, so that they match the name-mangling scheme used by the
8108 Fortran compiler.
8110 Fortran is case-insensitive, and in order to achieve this the Fortran
8111 compiler converts all identifiers into a canonical case and format.  To
8112 call a Fortran subroutine from C or to write a C function that is
8113 callable from Fortran, the C program must explicitly use identifiers in
8114 the format expected by the Fortran compiler.  In order to do this, one
8115 simply wraps all C identifiers in one of the macros provided by
8116 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8117 you have the following Fortran 77 subroutine:
8119 @example
8120 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8121       subroutine foobar (x, y)
8122       double precision x, y
8123       y = 3.14159 * x
8124       return
8125       end
8126 @end example
8128 You would then declare its prototype in C or C++ as:
8130 @example
8131 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8132 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8133 #ifdef __cplusplus
8134 extern "C"  /* prevent C++ name mangling */
8135 #endif
8136 void FOOBAR_F77 (double *x, double *y);
8137 @end example
8139 Note that we pass both the lowercase and uppercase versions of the
8140 function name to @code{F77_FUNC} so that it can select the right one.
8141 Note also that all parameters to Fortran 77 routines are passed as
8142 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8143 Automake}).
8145 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8147 Although Autoconf tries to be intelligent about detecting the
8148 name-mangling scheme of the Fortran compiler, there may be Fortran
8149 compilers that it doesn't support yet.  In this case, the above code
8150 generates a compile-time error, but some other behavior
8151 (e.g., disabling Fortran-related features) can be induced by checking
8152 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8154 Now, to call that routine from a C program, we would do something like:
8156 @example
8157 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8159     double x = 2.7183, y;
8160     FOOBAR_F77 (&x, &y);
8162 @end example
8164 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8165 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8166 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8167 because some Fortran compilers mangle names differently if they contain
8168 an underscore.
8170 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8171 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8172 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8173 @end defmac
8175 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8176 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8177 @acindex{F77_FUNC}
8178 @acindex{FC_FUNC}
8179 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8180 hold the mangled version @var{name} according to the rules of the
8181 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8182 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8183 supplied, the shell variable is simply @var{name}.  The purpose of
8184 this macro is to give the caller a way to access the name-mangling
8185 information other than through the C preprocessor as above, for example,
8186 to call Fortran routines from some language other than C/C++.
8187 @end defmac
8189 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8190   @dvar{action-if-failure, AC_MSG_FAILURE})
8191 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8192   @dvar{action-if-failure, AC_MSG_FAILURE})
8193 @acindex{FC_SRCEXT}
8194 @acindex{FC_PP_SRCEXT}
8195 @caindex fc_srcext_@var{ext}
8196 @caindex fc_pp_srcext_@var{ext}
8197 By default, the @code{FC} macros perform their tests using a @file{.f}
8198 extension for source-code files.  Some compilers, however, only enable
8199 newer language features for appropriately named files, e.g., Fortran 90
8200 features only for @file{.f90} files, or preprocessing only with
8201 @file{.F} files or maybe other upper-case extensions.  On the other
8202 hand, some other compilers expect all source files to end in @file{.f}
8203 and require special flags to support other file name extensions.  The
8204 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8205 issues.
8207 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8208 accept files ending with the extension @file{.@var{ext}} (i.e.,
8209 @var{ext} does @emph{not} contain the dot).  If any special compiler
8210 flags are needed for this, it stores them in the output variable
8211 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8212 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8213 @code{AC_FC_PP_SRCEXT} is called another time).
8215 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8216 @file{.f90} extension in future tests, and it would set the
8217 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8218 to compile such files.
8220 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8221 compiler to preprocess and compile files with the extension
8222 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8223 preprocessing are provided, the former is preferred, as the latter may
8224 treat continuation lines, @code{//} tokens, and white space differently
8225 from what some Fortran dialects expect.  Conversely, if you do not want
8226 files to be preprocessed, use only lower-case characters in the file
8227 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8228 are stored in the @code{FCFLAGS_@var{ext}} variable.
8230 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8231 into @code{FCFLAGS}, for two reasons based on the limitations of some
8232 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8233 time, so files with different extensions must be compiled separately.
8234 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8235 the source-code file name when compiling.  So, continuing the example
8236 above, you might compile a @file{foo.f90} file in your makefile with the
8237 command:
8239 @example
8240 foo.o: foo.f90
8241        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8242 @end example
8244 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8245 files with the @var{ext} extension, it calls @var{action-if-success}
8246 (defaults to nothing).  If it fails, and cannot find a way to make the
8247 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8248 (defaults to exiting with an error message).
8250 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8251 results in @code{ac_cv_fc_srcext_@var{ext}} and
8252 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8253 @end defmac
8255 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8256   @dvar{action-if-failure, AC_MSG_FAILURE})
8257 @acindex{FC_PP_DEFINE}
8258 @caindex fc_pp_define
8260 Find a flag to specify defines for preprocessed Fortran.  Not all
8261 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8262 the result and call @var{action-if-success} (defaults to nothing) if
8263 successful, and @var{action-if-failure} (defaults to failing with an
8264 error message) if not.
8266 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8267 preprocess a @file{conftest.F} file, but restores a previously used
8268 Fortran source file extension afterwards again.
8270 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8271 variable.
8272 @end defmac
8274 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8275   @dvar{action-if-failure, AC_MSG_FAILURE})
8276 @acindex{FC_FREEFORM}
8277 @caindex fc_freeform
8279 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8280 source code (as opposed to the older fixed-format style from Fortran
8281 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8283 This macro is most important if you are using the default @file{.f}
8284 extension, since many compilers interpret this extension as indicating
8285 fixed-format source unless an additional flag is supplied.  If you
8286 specify a different extension with @code{AC_FC_SRCEXT}, such as
8287 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8288 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8289 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8290 the compiler assume Fortran 77 by default, however.
8292 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8293 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8294 calls @var{action-if-failure} (defaults to exiting with an error
8295 message).
8297 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8298 the @code{ac_cv_fc_freeform} variable.
8299 @end defmac
8301 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8302   @dvar{action-if-failure, AC_MSG_FAILURE})
8303 @acindex{FC_FIXEDFORM}
8304 @caindex fc_fixedform
8306 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8307 fixed-format source code (as opposed to free-format style).  If
8308 necessary, it may add some additional flags to @code{FCFLAGS}.
8310 This macro is needed for some compilers alias names like @command{xlf95}
8311 which assume free-form source code by default, and in case you want to
8312 use fixed-form source with an extension like @file{.f90} which many
8313 compilers interpret as free-form by default.  If you specify a different
8314 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8315 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8316 @code{FCFLAGS}.
8318 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8319 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8320 calls @var{action-if-failure} (defaults to exiting with an error
8321 message).
8323 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8324 the @code{ac_cv_fc_fixedform} variable.
8325 @end defmac
8327 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8328   @dvar{action-if-failure, AC_MSG_FAILURE})
8329 @acindex{FC_LINE_LENGTH}
8330 @caindex fc_line_length
8332 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8333 code lines.  The @var{length} argument may be given as 80, 132, or
8334 unlimited, and defaults to 132.  Note that line lengths above 254
8335 columns are not portable, and some compilers do not accept more than 132
8336 columns at least for fixed format source.  If necessary, it may add some
8337 additional flags to @code{FCFLAGS}.
8339 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8340 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8341 calls @var{action-if-failure} (defaults to exiting with an error
8342 message).
8344 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8345 the @code{ac_cv_fc_line_length} variable.
8346 @end defmac
8348 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8349   @dvar{action-if-failure, AC_MSG_FAILURE})
8350 @acindex{FC_CHECK_BOUNDS}
8351 @caindex fc_check_bounds
8353 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8354 in the Fortran compiler.  If successful, the @var{action-if-success}
8355 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8356 @var{action-if-failure} is called, which defaults to failing with an error
8357 message.  The macro currently requires Fortran 90 or a newer dialect.
8359 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8360 variable.
8361 @end defmac
8363 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8364   @dvar{action-if-failure, AC_MSG_FAILURE})
8365 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8366   @dvar{action-if-failure, AC_MSG_FAILURE})
8367 @acindex{F77_IMPLICIT_NONE}
8368 @acindex{FC_IMPLICIT_NONE}
8369 @caindex f77_implicit_none
8370 @caindex fc_implicit_none
8372 Try to disallow implicit declarations in the Fortran compiler.  If
8373 successful, @var{action-if-success} is called and any needed flags
8374 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8375 @var{action-if-failure} is called, which defaults to failing with an error
8376 message.
8378 The result of these macros are cached in the
8379 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8380 variables, respectively.
8381 @end defmac
8383 @defmac AC_FC_MODULE_EXTENSION
8384 @acindex{FC_MODULE_EXTENSION}
8385 @caindex fc_module_ext
8386 @ovindex FC_MODEXT
8388 Find the Fortran 90 module file name extension.  Most Fortran 90
8389 compilers store module information in files separate from the object
8390 files.  The module files are usually named after the name of the module
8391 rather than the source file name, with characters possibly turned to
8392 upper case, plus an extension, often @file{.mod}.
8394 Not all compilers use module files at all, or by default.  The Cray
8395 Fortran compiler requires @option{-e m} in order to store and search
8396 module information in @file{.mod} files rather than in object files.
8397 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8398 indicate how module information is stored.
8400 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8401 without the leading dot, and stores that in the @code{FC_MODEXT}
8402 variable.  If the compiler does not produce module files, or the
8403 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8404 the result of this macro may be used in cleanup @command{make} rules as
8405 follows:
8407 @example
8408 clean-modules:
8409         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8410 @end example
8412 The extension, or @samp{unknown}, is cached in the
8413 @code{ac_cv_fc_module_ext} variable.
8414 @end defmac
8416 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8417   @dvar{action-if-failure, AC_MSG_FAILURE})
8418 @acindex{FC_MODULE_FLAG}
8419 @caindex fc_module_flag
8420 @ovindex FC_MODINC
8421 @ovindex ac_empty
8423 Find the compiler flag to include Fortran 90 module information from
8424 another directory, and store that in the @code{FC_MODINC} variable.
8425 Call @var{action-if-success} (defaults to nothing) if successful, and
8426 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8427 to exiting with an error message) if not.
8429 Most Fortran 90 compilers provide a way to specify module directories.
8430 Some have separate flags for the directory to write module files to,
8431 and directories to search them in, whereas others only allow writing to
8432 the current directory or to the first directory specified in the include
8433 path.  Further, with some compilers, the module search path and the
8434 preprocessor search path can only be modified with the same flag.  Thus,
8435 for portability, write module files to the current directory only and
8436 list that as first directory in the search path.
8438 There may be no whitespace between @code{FC_MODINC} and the following
8439 directory name, but @code{FC_MODINC} may contain trailing white space.
8440 For example, if you use Automake and would like to search @file{../lib}
8441 for module files, you can use the following:
8443 @example
8444 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8445 @end example
8447 Inside @command{configure} tests, you can use:
8449 @example
8450 if test -n "$FC_MODINC"; then
8451   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8453 @end example
8455 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8456 The substituted value of @code{FC_MODINC} may refer to the
8457 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8458 the significant trailing whitespace in a @file{Makefile}.
8459 @end defmac
8461 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8462   @dvar{action-if-failure, AC_MSG_FAILURE})
8463 @acindex{FC_MODULE_OUTPUT_FLAG}
8464 @caindex fc_module_output_flag
8465 @ovindex FC_MODOUT
8467 Find the compiler flag to write Fortran 90 module information to
8468 another directory, and store that in the @code{FC_MODOUT} variable.
8469 Call @var{action-if-success} (defaults to nothing) if successful, and
8470 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8471 to exiting with an error message) if not.
8473 Not all Fortran 90 compilers write module files, and of those that do,
8474 not all allow writing to a directory other than the current one, nor
8475 do all have separate flags for writing and reading; see the description
8476 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8477 another directory, for maximum portability use @code{FC_MODOUT} before
8478 any @code{FC_MODINC} and include both the current directory and the one
8479 you write to in the search path:
8481 @example
8482 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8483 @end example
8485 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8486 The substituted value of @code{FC_MODOUT} may refer to the
8487 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8488 the significant trailing whitespace in a @file{Makefile}.
8489 @end defmac
8492 @node Go Compiler
8493 @subsection Go Compiler Characteristics
8494 @cindex Go
8496 Autoconf provides basic support for the Go programming language when
8497 using the @code{gccgo} compiler (there is currently no support for the
8498 @code{6g} and @code{8g} compilers).
8500 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8501 Find the Go compiler to use.  Check whether the environment variable
8502 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8503 value.
8505 Otherwise, if the macro is invoked without an argument, then search for
8506 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8507 resort set @code{GOC} to @code{gccgo}.
8509 This macro may be invoked with an optional first argument which, if
8510 specified, must be a blank-separated list of Go compilers to search for.
8512 If output variable @code{GOFLAGS} was not already set, set it to
8513 @option{-g -O2}.  If your package does not like this default,
8514 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8515 @end defmac
8518 @node System Services
8519 @section System Services
8521 The following macros check for operating system services or capabilities.
8523 @anchor{AC_PATH_X}
8524 @defmac AC_PATH_X
8525 @acindex{PATH_X}
8526 @evindex XMKMF
8527 @cindex X Window System
8528 Try to locate the X Window System include files and libraries.  If the
8529 user gave the command line options @option{--x-includes=@var{dir}} and
8530 @option{--x-libraries=@var{dir}}, use those directories.
8532 If either or both were not given, get the missing values by running
8533 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8534 environment variable) on a trivial @file{Imakefile} and examining the
8535 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8536 disables this method.
8538 If this method fails to find the X Window System, @command{configure}
8539 looks for the files in several directories where they often reside.
8540 If either method is successful, set the shell variables
8541 @code{x_includes} and @code{x_libraries} to their locations, unless they
8542 are in directories the compiler searches by default.
8544 If both methods fail, or the user gave the command line option
8545 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8546 otherwise set it to the empty string.
8547 @end defmac
8549 @anchor{AC_PATH_XTRA}
8550 @defmac AC_PATH_XTRA
8551 @acindex{PATH_XTRA}
8552 @ovindex X_CFLAGS
8553 @ovindex X_LIBS
8554 @ovindex X_EXTRA_LIBS
8555 @ovindex X_PRE_LIBS
8556 @cvindex X_DISPLAY_MISSING
8557 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8558 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8559 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8560 available.
8562 This macro also checks for special libraries that some systems need in
8563 order to compile X programs.  It adds any that the system needs to
8564 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8565 libraries that need to be linked with before @option{-lX11}, and adds
8566 any found to the output variable @code{X_PRE_LIBS}.
8568 @c This is an incomplete kludge.  Make a real way to do it.
8569 @c If you need to check for other X functions or libraries yourself, then
8570 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8571 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8572 @end defmac
8574 @anchor{AC_SYS_INTERPRETER}
8575 @defmac AC_SYS_INTERPRETER
8576 @acindex{SYS_INTERPRETER}
8577 Check whether the system supports starting scripts with a line of the
8578 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8579 After running this macro, shell code in @file{configure.ac} can check
8580 the shell variable @code{interpval}; it is set to @samp{yes}
8581 if the system supports @samp{#!}, @samp{no} if not.
8582 @end defmac
8584 @defmac AC_SYS_LARGEFILE
8585 @acindex{SYS_LARGEFILE}
8586 @cvindex _FILE_OFFSET_BITS
8587 @cvindex _LARGE_FILES
8588 @ovindex CC
8589 @cindex Large file support
8590 @cindex LFS
8591 Arrange for 64-bit file offsets, known as
8592 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8593 large-file support}.  On some hosts, one must use special compiler
8594 options to build programs that can access large files.  Append any such
8595 options to the output variable @code{CC}.  Define
8596 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8598 Large-file support can be disabled by configuring with the
8599 @option{--disable-largefile} option.
8601 If you use this macro, check that your program works even when
8602 @code{off_t} is wider than @code{long int}, since this is common when
8603 large-file support is enabled.  For example, it is not correct to print
8604 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8605 (long int) X)}.
8607 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8608 replace their C counterparts @code{fseek} and @code{ftell} that do not
8609 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8610 prototypes available when using them and large-file support is
8611 enabled.
8612 @end defmac
8614 @anchor{AC_SYS_LONG_FILE_NAMES}
8615 @defmac AC_SYS_LONG_FILE_NAMES
8616 @acindex{SYS_LONG_FILE_NAMES}
8617 @cvindex HAVE_LONG_FILE_NAMES
8618 If the system supports file names longer than 14 characters, define
8619 @code{HAVE_LONG_FILE_NAMES}.
8620 @end defmac
8622 @defmac AC_SYS_POSIX_TERMIOS
8623 @acindex{SYS_POSIX_TERMIOS}
8624 @cindex Posix termios headers
8625 @cindex termios Posix headers
8626 @caindex sys_posix_termios
8627 Check to see if the Posix termios headers and functions are available on the
8628 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8629 @samp{yes}.  If not, set the variable to @samp{no}.
8630 @end defmac
8632 @node Posix Variants
8633 @section Posix Variants
8635 The following macro makes it possible to use features of Posix that are
8636 extensions to C, as well as platform extensions not defined by Posix.
8638 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8639 @defmac AC_USE_SYSTEM_EXTENSIONS
8640 @acindex{USE_SYSTEM_EXTENSIONS}
8641 @cvindex _ALL_SOURCE
8642 @cvindex _GNU_SOURCE
8643 @cvindex _MINIX
8644 @cvindex _POSIX_1_SOURCE
8645 @cvindex _POSIX_PTHREAD_SEMANTICS
8646 @cvindex _POSIX_SOURCE
8647 @cvindex _TANDEM_SOURCE
8648 @cvindex __EXTENSIONS__
8649 This macro was introduced in Autoconf 2.60.  If possible, enable
8650 extensions to C or Posix on hosts that normally disable the extensions,
8651 typically due to standards-conformance namespace issues.  This should be
8652 called before any macros that run the C compiler.  The following
8653 preprocessor macros are defined where appropriate:
8655 @table @code
8656 @item _GNU_SOURCE
8657 Enable extensions on GNU/Linux.
8658 @item __EXTENSIONS__
8659 Enable general extensions on Solaris.
8660 @item _POSIX_PTHREAD_SEMANTICS
8661 Enable threading extensions on Solaris.
8662 @item _TANDEM_SOURCE
8663 Enable extensions for the HP NonStop platform.
8664 @item _ALL_SOURCE
8665 Enable extensions for AIX 3, and for Interix.
8666 @item _POSIX_SOURCE
8667 Enable Posix functions for Minix.
8668 @item _POSIX_1_SOURCE
8669 Enable additional Posix functions for Minix.
8670 @item _MINIX
8671 Identify Minix platform.  This particular preprocessor macro is
8672 obsolescent, and may be removed in a future release of Autoconf.
8673 @end table
8674 @end defmac
8677 @node Erlang Libraries
8678 @section Erlang Libraries
8679 @cindex Erlang, Library, checking
8681 The following macros check for an installation of Erlang/OTP, and for the
8682 presence of certain Erlang libraries.  All those macros require the
8683 configuration of an Erlang interpreter and an Erlang compiler
8684 (@pxref{Erlang Compiler and Interpreter}).
8686 @defmac AC_ERLANG_SUBST_ERTS_VER
8687 @acindex{ERLANG_SUBST_ERTS_VER}
8688 @ovindex ERLANG_ERTS_VER
8689 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8690 Erlang runtime system (as returned by Erlang's
8691 @code{erlang:system_info(version)} function).  The result of this test
8692 is cached if caching is enabled when running @command{configure}.  The
8693 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8694 for features of specific ERTS versions, but to be used for substituting
8695 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8696 files), as shown below.
8697 @end defmac
8699 @defmac AC_ERLANG_SUBST_ROOT_DIR
8700 @acindex{ERLANG_SUBST_ROOT_DIR}
8701 @ovindex ERLANG_ROOT_DIR
8702 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8703 directory in which Erlang/OTP is installed (as returned by Erlang's
8704 @code{code:root_dir/0} function).  The result of this test is cached if
8705 caching is enabled when running @command{configure}.
8706 @end defmac
8708 @defmac AC_ERLANG_SUBST_LIB_DIR
8709 @acindex{ERLANG_SUBST_LIB_DIR}
8710 @ovindex ERLANG_LIB_DIR
8711 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8712 directory of Erlang/OTP (as returned by Erlang's
8713 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8714 Erlang/OTP library.  The result of this test is cached if caching is enabled
8715 when running @command{configure}.
8716 @end defmac
8718 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8719   @ovar{action-if-not-found})
8720 @acindex{ERLANG_CHECK_LIB}
8721 @ovindex ERLANG_LIB_DIR_@var{library}
8722 @ovindex ERLANG_LIB_VER_@var{library}
8723 Test whether the Erlang/OTP library @var{library} is installed by
8724 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8725 test is cached if caching is enabled when running @command{configure}.
8726 @var{action-if-found} is a list of shell commands to run if the library
8727 is installed; @var{action-if-not-found} is a list of shell commands to
8728 run if it is not.  Additionally, if the library is installed, the output
8729 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8730 library installation directory, and the output variable
8731 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8732 part of the subdirectory name, if it is in the standard form
8733 (@code{@var{library}-@var{version}}).  If the directory name does not
8734 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8735 empty string.  If the library is not installed,
8736 @samp{ERLANG_LIB_DIR_@var{library}} and
8737 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8738 example, to check if library @code{stdlib} is installed:
8740 @example
8741 AC_ERLANG_CHECK_LIB([stdlib],
8742   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8743    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8744   [AC_MSG_ERROR([stdlib was not found!])])
8745 @end example
8747 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8748 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8749 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8750 testing for features of specific versions of libraries or of the Erlang
8751 runtime system.  Those variables are intended to be substituted in
8752 Erlang release resource files (@code{.rel} files).  For instance, to
8753 generate a @file{example.rel} file for an application depending on the
8754 @code{stdlib} library, @file{configure.ac} could contain:
8756 @example
8757 AC_ERLANG_SUBST_ERTS_VER
8758 AC_ERLANG_CHECK_LIB([stdlib],
8759   [],
8760   [AC_MSG_ERROR([stdlib was not found!])])
8761 AC_CONFIG_FILES([example.rel])
8762 @end example
8764 @noindent
8765 The @file{example.rel.in} file used to generate @file{example.rel}
8766 should contain:
8768 @example
8769 @{release,
8770     @{"@@PACKAGE@@", "@@VERSION@@"@},
8771     @{erts, "@@ERLANG_ERTS_VER@@"@},
8772     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8773      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8774 @end example
8775 @end defmac
8777 In addition to the above macros, which test installed Erlang libraries, the
8778 following macros determine the paths to the directories into which newly built
8779 Erlang libraries are to be installed:
8781 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8782 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8783 @ovindex ERLANG_INSTALL_LIB_DIR
8785 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8786 which every built Erlang library should be installed in a separate
8787 subdirectory.
8788 If this variable is not set in the environment when @command{configure} runs,
8789 its default value is @code{$@{libdir@}/erlang/lib}.
8790 @end defmac
8792 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8793 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8794 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8796 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8797 directory into which the built Erlang library @var{library} version
8798 @var{version} should be installed.  If this variable is not set in the
8799 environment when @command{configure} runs, its default value is
8800 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8801 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8802 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8803 @end defmac
8809 @c ========================================================= Writing Tests
8811 @node Writing Tests
8812 @chapter Writing Tests
8814 If the existing feature tests don't do something you need, you have to
8815 write new ones.  These macros are the building blocks.  They provide
8816 ways for other macros to check whether various kinds of features are
8817 available and report the results.
8819 This chapter contains some suggestions and some of the reasons why the
8820 existing tests are written the way they are.  You can also learn a lot
8821 about how to write Autoconf tests by looking at the existing ones.  If
8822 something goes wrong in one or more of the Autoconf tests, this
8823 information can help you understand the assumptions behind them, which
8824 might help you figure out how to best solve the problem.
8826 These macros check the output of the compiler system of the current
8827 language (@pxref{Language Choice}).  They do not cache the results of
8828 their tests for future use (@pxref{Caching Results}), because they don't
8829 know enough about the information they are checking for to generate a
8830 cache variable name.  They also do not print any messages, for the same
8831 reason.  The checks for particular kinds of features call these macros
8832 and do cache their results and print messages about what they're
8833 checking for.
8835 When you write a feature test that could be applicable to more than one
8836 software package, the best thing to do is encapsulate it in a new macro.
8837 @xref{Writing Autoconf Macros}, for how to do that.
8839 @menu
8840 * Language Choice::             Selecting which language to use for testing
8841 * Writing Test Programs::       Forging source files for compilers
8842 * Running the Preprocessor::    Detecting preprocessor symbols
8843 * Running the Compiler::        Detecting language or header features
8844 * Running the Linker::          Detecting library features
8845 * Runtime::                     Testing for runtime features
8846 * Systemology::                 A zoology of operating systems
8847 * Multiple Cases::              Tests for several possible values
8848 @end menu
8850 @node Language Choice
8851 @section Language Choice
8852 @cindex Language
8854 Autoconf-generated @command{configure} scripts check for the C compiler and
8855 its features by default.  Packages that use other programming languages
8856 (maybe more than one, e.g., C and C++) need to test features of the
8857 compilers for the respective languages.  The following macros determine
8858 which programming language is used in the subsequent tests in
8859 @file{configure.ac}.
8861 @anchor{AC_LANG}
8862 @defmac AC_LANG (@var{language})
8863 @acindex{LANG}
8864 Do compilation tests using the compiler, preprocessor, and file
8865 extensions for the specified @var{language}.
8867 Supported languages are:
8869 @table @samp
8870 @item C
8871 Do compilation tests using @code{CC} and @code{CPP} and use extension
8872 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8873 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8875 @item C++
8876 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8877 extension @file{.C} for test programs.  Use compilation flags:
8878 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8879 @code{CXXFLAGS} with @code{CXX}.
8881 @item Fortran 77
8882 Do compilation tests using @code{F77} and use extension @file{.f} for
8883 test programs.  Use compilation flags: @code{FFLAGS}.
8885 @item Fortran
8886 Do compilation tests using @code{FC} and use extension @file{.f} (or
8887 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8888 compilation flags: @code{FCFLAGS}.
8890 @item Erlang
8891 @ovindex ERLC
8892 @ovindex ERL
8893 @ovindex ERLCFLAGS
8894 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8895 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8897 @item Objective C
8898 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8899 extension @file{.m} for test programs.  Use compilation flags:
8900 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8901 @code{OBJCFLAGS} with @code{OBJC}.
8903 @item Objective C++
8904 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8905 extension @file{.mm} for test programs.  Use compilation flags:
8906 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8907 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8909 @item Go
8910 Do compilation tests using @code{GOC} and use extension @file{.go} for
8911 test programs.  Use compilation flags @code{GOFLAGS}.
8912 @end table
8913 @end defmac
8915 @anchor{AC_LANG_PUSH}
8916 @defmac AC_LANG_PUSH (@var{language})
8917 @acindex{LANG_PUSH}
8918 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8919 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8920 in macros that need to temporarily switch to a particular language.
8921 @end defmac
8923 @defmac AC_LANG_POP (@ovar{language})
8924 @acindex{LANG_POP}
8925 Select the language that is saved on the top of the stack, as set by
8926 @code{AC_LANG_PUSH}, and remove it from the stack.
8928 If given, @var{language} specifies the language we just @emph{quit}.  It
8929 is a good idea to specify it when it's known (which should be the
8930 case@dots{}), since Autoconf detects inconsistencies.
8932 @example
8933 AC_LANG_PUSH([Fortran 77])
8934 # Perform some tests on Fortran 77.
8935 # @dots{}
8936 AC_LANG_POP([Fortran 77])
8937 @end example
8938 @end defmac
8940 @defmac AC_LANG_ASSERT (@var{language})
8941 @acindex{LANG_ASSERT}
8942 Check statically that the current language is @var{language}.
8943 You should use this in your language specific macros
8944 to avoid that they be called with an inappropriate language.
8946 This macro runs only at @command{autoconf} time, and incurs no cost at
8947 @command{configure} time.  Sadly enough and because Autoconf is a two
8948 layer language @footnote{Because M4 is not aware of Sh code,
8949 especially conditionals, some optimizations that look nice statically
8950 may produce incorrect results at runtime.}, the macros
8951 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8952 therefore as much as possible you ought to avoid using them to wrap
8953 your code, rather, require from the user to run the macro with a
8954 correct current language, and check it with @code{AC_LANG_ASSERT}.
8955 And anyway, that may help the user understand she is running a Fortran
8956 macro while expecting a result about her Fortran 77 compiler@enddots{}
8957 @end defmac
8960 @defmac AC_REQUIRE_CPP
8961 @acindex{REQUIRE_CPP}
8962 Ensure that whichever preprocessor would currently be used for tests has
8963 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8964 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8965 depending on which language is current.
8966 @end defmac
8969 @node Writing Test Programs
8970 @section Writing Test Programs
8972 Autoconf tests follow a common scheme: feed some program with some
8973 input, and most of the time, feed a compiler with some source file.
8974 This section is dedicated to these source samples.
8976 @menu
8977 * Guidelines::                  General rules for writing test programs
8978 * Test Functions::              Avoiding pitfalls in test programs
8979 * Generating Sources::          Source program boilerplate
8980 @end menu
8982 @node Guidelines
8983 @subsection Guidelines for Test Programs
8985 The most important rule to follow when writing testing samples is:
8987 @center @emph{Look for realism.}
8989 This motto means that testing samples must be written with the same
8990 strictness as real programs are written.  In particular, you should
8991 avoid ``shortcuts'' and simplifications.
8993 Don't just play with the preprocessor if you want to prepare a
8994 compilation.  For instance, using @command{cpp} to check whether a header is
8995 functional might let your @command{configure} accept a header which
8996 causes some @emph{compiler} error.  Do not hesitate to check a header with
8997 other headers included before, especially required headers.
8999 Make sure the symbols you use are properly defined, i.e., refrain from
9000 simply declaring a function yourself instead of including the proper
9001 header.
9003 Test programs should not write to standard output.  They
9004 should exit with status 0 if the test succeeds, and with status 1
9005 otherwise, so that success
9006 can be distinguished easily from a core dump or other failure;
9007 segmentation violations and other failures produce a nonzero exit
9008 status.  Unless you arrange for @code{exit} to be declared, test
9009 programs should @code{return}, not @code{exit}, from @code{main},
9010 because on many systems @code{exit} is not declared by default.
9012 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9013 preprocessor macros defined by tests that have already run.  For
9014 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9015 @file{configure.ac} you can have a test program that includes
9016 @file{stdbool.h} conditionally:
9018 @example
9019 @group
9020 #ifdef HAVE_STDBOOL_H
9021 # include <stdbool.h>
9022 #endif
9023 @end group
9024 @end example
9026 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9027 work with any standard C compiler.  Some developers prefer @code{#if}
9028 because it is easier to read, while others prefer @code{#ifdef} because
9029 it avoids diagnostics with picky compilers like GCC with the
9030 @option{-Wundef} option.
9032 If a test program needs to use or create a data file, give it a name
9033 that starts with @file{conftest}, such as @file{conftest.data}.  The
9034 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9035 after running test programs and if the script is interrupted.
9037 @node Test Functions
9038 @subsection Test Functions
9040 These days it's safe to assume support for function prototypes
9041 (introduced in C89).
9043 Functions that test programs declare should also be conditionalized for
9044 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9045 include any header files containing clashing prototypes.
9047 @example
9048 #ifdef __cplusplus
9049 extern "C"
9050 #endif
9051 void *valloc (size_t);
9052 @end example
9054 If a test program calls a function with invalid parameters (just to see
9055 whether it exists), organize the program to ensure that it never invokes
9056 that function.  You can do this by calling it in another function that is
9057 never invoked.  You can't do it by putting it after a call to
9058 @code{exit}, because GCC version 2 knows that @code{exit}
9059 never returns
9060 and optimizes out any code that follows it in the same block.
9062 If you include any header files, be sure to call the functions
9063 relevant to them with the correct number of arguments, even if they are
9064 just 0, to avoid compilation errors due to prototypes.  GCC
9065 version 2
9066 has internal prototypes for several functions that it automatically
9067 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9068 them, either pass them the correct number of arguments or redeclare them
9069 with a different return type (such as @code{char}).
9072 @node Generating Sources
9073 @subsection Generating Sources
9075 Autoconf provides a set of macros that can be used to generate test
9076 source files.  They are written to be language generic, i.e., they
9077 actually depend on the current language (@pxref{Language Choice}) to
9078 ``format'' the output properly.
9081 @defmac AC_LANG_CONFTEST (@var{source})
9082 @acindex{LANG_CONFTEST}
9083 Save the @var{source} text in the current test source file:
9084 @file{conftest.@var{extension}} where the @var{extension} depends on the
9085 current language.  As of Autoconf 2.63b, the source file also contains
9086 the results of all of the @code{AC_DEFINE} performed so far.
9088 Note that the @var{source} is evaluated exactly once, like regular
9089 Autoconf macro arguments, and therefore (i) you may pass a macro
9090 invocation, (ii) if not, be sure to double quote if needed.
9092 This macro issues a warning during @command{autoconf} processing if
9093 @var{source} does not include an expansion of the macro
9094 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9095 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9097 This macro is seldom called directly, but is used under the hood by more
9098 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9099 @end defmac
9101 @defmac AC_LANG_DEFINES_PROVIDED
9102 @acindex{LANG_DEFINES_PROVIDED}
9103 This macro is called as a witness that the file
9104 @file{conftest.@var{extension}} appropriate for the current language is
9105 complete, including all previously determined results from
9106 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9107 you have a compelling reason to write a conftest file without using
9108 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9109 @code{AC_LANG_CONFTEST}.
9110 @end defmac
9112 @defmac AC_LANG_SOURCE (@var{source})
9113 @acindex{LANG_SOURCE}
9114 Expands into the @var{source}, with the definition of
9115 all the @code{AC_DEFINE} performed so far.  This macro includes an
9116 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9118 In many cases, you may find it more convenient to use the wrapper
9119 @code{AC_LANG_PROGRAM}.
9120 @end defmac
9122 For instance, executing (observe the double quotation!):
9124 @example
9125 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9126 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9127         [http://www.example.org/])
9128 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9129   [Greetings string.])
9130 AC_LANG([C])
9131 AC_LANG_CONFTEST(
9132    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9133 gcc -E -dD conftest.c
9134 @end example
9136 @noindent
9137 on a system with @command{gcc} installed, results in:
9139 @example
9140 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9141 @dots{}
9142 @asis{#} 1 "conftest.c"
9144 #define PACKAGE_NAME "Hello"
9145 #define PACKAGE_TARNAME "hello"
9146 #define PACKAGE_VERSION "1.0"
9147 #define PACKAGE_STRING "Hello 1.0"
9148 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9149 #define PACKAGE_URL "http://www.example.org/"
9150 #define HELLO_WORLD "Hello, World\n"
9152 const char hw[] = "Hello, World\n";
9153 @end example
9155 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9156 definitions are not automatically translated into constants in the
9157 source code by this macro.
9159 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9160 @acindex{LANG_PROGRAM}
9161 Expands into a source file which consists of the @var{prologue}, and
9162 then @var{body} as body of the main function (e.g., @code{main} in
9163 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9164 available.
9165 @end defmac
9167 For instance:
9169 @example
9170 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9171 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9172         [http://www.example.org/])
9173 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9174   [Greetings string.])
9175 AC_LANG_CONFTEST(
9176 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9177                  [[fputs (hw, stdout);]])])
9178 gcc -E -dD conftest.c
9179 @end example
9181 @noindent
9182 on a system with @command{gcc} installed, results in:
9184 @example
9185 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9186 @dots{}
9187 @asis{#} 1 "conftest.c"
9189 #define PACKAGE_NAME "Hello"
9190 #define PACKAGE_TARNAME "hello"
9191 #define PACKAGE_VERSION "1.0"
9192 #define PACKAGE_STRING "Hello 1.0"
9193 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9194 #define PACKAGE_URL "http://www.example.org/"
9195 #define HELLO_WORLD "Hello, World\n"
9197 const char hw[] = "Hello, World\n";
9199 main ()
9201 fputs (hw, stdout);
9202   ;
9203   return 0;
9205 @end example
9207 In Erlang tests, the created source file is that of an Erlang module called
9208 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9209 at least
9210 one @code{start/0} function, which is called to perform the test.  The
9211 @var{prologue} is optional code that is inserted between the module header and
9212 the @code{start/0} function definition.  @var{body} is the body of the
9213 @code{start/0} function without the final period (@pxref{Runtime}, about
9214 constraints on this function's behavior).
9216 For instance:
9218 @example
9219 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9220 AC_LANG(Erlang)
9221 AC_LANG_CONFTEST(
9222 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9223                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9224 cat conftest.erl
9225 @end example
9227 @noindent
9228 results in:
9230 @example
9231 -module(conftest).
9232 -export([start/0]).
9233 -define(HELLO_WORLD, "Hello, world!").
9234 start() ->
9235 io:format("~s~n", [?HELLO_WORLD])
9237 @end example
9239 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9240 @acindex{LANG_CALL}
9241 Expands into a source file which consists of the @var{prologue}, and
9242 then a call to the @var{function} as body of the main function (e.g.,
9243 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9244 of the latter are available.
9246 This function will probably be replaced in the future by a version
9247 which would enable specifying the arguments.  The use of this macro is
9248 not encouraged, as it violates strongly the typing system.
9250 This macro cannot be used for Erlang tests.
9251 @end defmac
9253 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9254 @acindex{LANG_FUNC_LINK_TRY}
9255 Expands into a source file which uses the @var{function} in the body of
9256 the main function (e.g., @code{main} in C).  Since it uses
9257 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9259 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9260 It is considered to be severely broken, and in the future will be
9261 removed in favor of actual function calls (with properly typed
9262 arguments).
9264 This macro cannot be used for Erlang tests.
9265 @end defmac
9267 @node Running the Preprocessor
9268 @section Running the Preprocessor
9270 Sometimes one might need to run the preprocessor on some source file.
9271 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9272 your project, not merely run the preprocessor on it; therefore you
9273 certainly want to run the compiler, not the preprocessor.  Resist the
9274 temptation of following the easiest path.
9276 Nevertheless, if you need to run the preprocessor, then use
9277 @code{AC_PREPROC_IFELSE}.
9279 The macros described in this section cannot be used for tests in Erlang,
9280 Fortran, or Go, since those languages require no preprocessor.
9282 @anchor{AC_PREPROC_IFELSE}
9283 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9284   @ovar{action-if-false})
9285 @acindex{PREPROC_IFELSE}
9286 Run the preprocessor of the current language (@pxref{Language Choice})
9287 on the @var{input}, run the shell commands @var{action-if-true} on
9288 success, @var{action-if-false} otherwise.  The @var{input} can be made
9289 by @code{AC_LANG_PROGRAM} and friends.
9291 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9292 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9293 preprocessors.
9295 It is customary to report unexpected failures with
9296 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9297 the preprocessed output in the file @file{conftest.i}.
9298 @end defmac
9300 For instance:
9302 @example
9303 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9304 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9305   [Greetings string.])
9306 AC_PREPROC_IFELSE(
9307    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9308                     [[fputs (hw, stdout);]])],
9309    [AC_MSG_RESULT([OK])],
9310    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9311 @end example
9313 @noindent
9314 results in:
9316 @example
9317 checking for gcc... gcc
9318 checking for C compiler default output file name... a.out
9319 checking whether the C compiler works... yes
9320 checking whether we are cross compiling... no
9321 checking for suffix of executables...
9322 checking for suffix of object files... o
9323 checking whether we are using the GNU C compiler... yes
9324 checking whether gcc accepts -g... yes
9325 checking for gcc option to accept ISO C89... none needed
9326 checking how to run the C preprocessor... gcc -E
9328 @end example
9330 @sp 1
9332 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9333 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9334 it impossible to use it to elaborate sources.  You are encouraged to
9335 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9336 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9337 to run the @emph{preprocessor} and not the compiler?
9339 @anchor{AC_EGREP_HEADER}
9340 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9341   @var{action-if-found}, @ovar{action-if-not-found})
9342 @acindex{EGREP_HEADER}
9343 If the output of running the preprocessor on the system header file
9344 @var{header-file} matches the extended regular expression
9345 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9346 execute @var{action-if-not-found}.
9347 @end defmac
9349 @anchor{AC_EGREP_CPP}
9350 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9351   @ovar{action-if-found}, @ovar{action-if-not-found})
9352 @acindex{EGREP_CPP}
9353 @var{program} is the text of a C or C++ program, on which shell
9354 variable, back quote, and backslash substitutions are performed.  If the
9355 output of running the preprocessor on @var{program} matches the
9356 extended regular expression @var{pattern}, execute shell commands
9357 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9358 @end defmac
9362 @node Running the Compiler
9363 @section Running the Compiler
9365 To check for a syntax feature of the current language's (@pxref{Language
9366 Choice}) compiler, such as whether it recognizes a certain keyword, or
9367 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9368 to compile a small program that uses that feature.
9370 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9371   @ovar{action-if-false})
9372 @acindex{COMPILE_IFELSE}
9373 Run the compiler and compilation flags of the current language
9374 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9375 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9376 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9378 It is customary to report unexpected failures with
9379 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9380 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9381 Linker}).  If needed, @var{action-if-true} can further access the
9382 just-compiled object file @file{conftest.$OBJEXT}.
9384 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9385 current language, which means that if the compiler has not yet been
9386 determined, the compiler determination will be made prior to the body of
9387 the outermost @code{AC_DEFUN} macro that triggered this macro to
9388 expand (@pxref{Expanded Before Required}).
9389 @end defmac
9391 @ovindex ERL
9392 For tests in Erlang, the @var{input} must be the source code of a module named
9393 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9394 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9395 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9396 to ensure that the Erlang module has the right name.
9398 @node Running the Linker
9399 @section Running the Linker
9401 To check for a library, a function, or a global variable, Autoconf
9402 @command{configure} scripts try to compile and link a small program that
9403 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9404 @code{ar} on the C library to try to figure out which functions are
9405 available.  Trying to link with the function is usually a more reliable
9406 approach because it avoids dealing with the variations in the options
9407 and output formats of @code{nm} and @code{ar} and in the location of the
9408 standard libraries.  It also allows configuring for cross-compilation or
9409 checking a function's runtime behavior if needed.  On the other hand,
9410 it can be slower than scanning the libraries once, but accuracy is more
9411 important than speed.
9413 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9414 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9415 to check for libraries (@pxref{Libraries}), by adding the library being
9416 checked for to @code{LIBS} temporarily and trying to link a small
9417 program.
9419 @anchor{AC_LINK_IFELSE}
9420 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9421   @ovar{action-if-false})
9422 @acindex{LINK_IFELSE}
9423 Run the compiler (and compilation flags) and the linker of the current
9424 language (@pxref{Language Choice}) on the @var{input}, run the shell
9425 commands @var{action-if-true} on success, @var{action-if-false}
9426 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9427 friends.  If needed, @var{action-if-true} can further access the
9428 just-linked program file @file{conftest$EXEEXT}.
9430 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9431 current compilation flags.
9433 It is customary to report unexpected failures with
9434 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9435 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9436 @end defmac
9438 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9439 programs are interpreted and do not require linking.
9443 @node Runtime
9444 @section Checking Runtime Behavior
9446 Sometimes you need to find out how a system performs at runtime, such
9447 as whether a given function has a certain capability or bug.  If you
9448 can, make such checks when your program runs instead of when it is
9449 configured.  You can check for things like the machine's endianness when
9450 your program initializes itself.
9452 If you really need to test for a runtime behavior while configuring,
9453 you can write a test program to determine the result, and compile and
9454 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9455 possible, because this prevents people from configuring your package for
9456 cross-compiling.
9458 @anchor{AC_RUN_IFELSE}
9459 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9460   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9461 @acindex{RUN_IFELSE}
9462 Run the compiler (and compilation flags) and the linker of the current
9463 language (@pxref{Language Choice}) on the @var{input}, then execute the
9464 resulting program.  If the program returns an exit
9465 status of 0 when executed, run shell commands @var{action-if-true}.
9466 Otherwise, run shell commands @var{action-if-false}.
9468 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9469 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9470 compilation flags of the current language (@pxref{Language Choice}).
9471 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9472 for further testing.
9474 In the @var{action-if-false} section, the failing exit status is
9475 available in the shell variable @samp{$?}.  This exit status might be
9476 that of a failed compilation, or it might be that of a failed program
9477 execution.
9479 If cross-compilation mode is enabled (this is the case if either the
9480 compiler being used does not produce executables that run on the system
9481 where @command{configure} is being run, or if the options @code{--build}
9482 and @code{--host} were both specified and their values are different),
9483 then the test program is
9484 not run.  If the optional shell commands @var{action-if-cross-compiling}
9485 are given, those commands are run instead; typically these commands
9486 provide pessimistic defaults that allow cross-compilation to work even
9487 if the guess was wrong.  If the fourth argument is empty or omitted, but
9488 cross-compilation is detected, then @command{configure} prints an error
9489 message and exits.  If you want your package to be useful in a
9490 cross-compilation scenario, you @emph{should} provide a non-empty
9491 @var{action-if-cross-compiling} clause, as well as wrap the
9492 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9493 (@pxref{Caching Results}) which allows the user to override the
9494 pessimistic default if needed.
9496 It is customary to report unexpected failures with
9497 @code{AC_MSG_FAILURE}.
9498 @end defmac
9500 @command{autoconf} prints a warning message when creating
9501 @command{configure} each time it encounters a call to
9502 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9503 given.  If you are not concerned about users configuring your package
9504 for cross-compilation, you may ignore the warning.  A few of the macros
9505 distributed with Autoconf produce this warning message; but if this is a
9506 problem for you, please report it as a bug, along with an appropriate
9507 pessimistic guess to use instead.
9509 To configure for cross-compiling you can also choose a value for those
9510 parameters based on the canonical system name (@pxref{Manual
9511 Configuration}).  Alternatively, set up a test results cache file with
9512 the correct values for the host system (@pxref{Caching Results}).
9514 @ovindex cross_compiling
9515 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9516 in other macros, including a few of the ones that come with Autoconf,
9517 you can test whether the shell variable @code{cross_compiling} is set to
9518 @samp{yes}, and then use an alternate method to get the results instead
9519 of calling the macros.
9521 It is also permissible to temporarily assign to @code{cross_compiling}
9522 in order to force tests to behave as though they are in a
9523 cross-compilation environment, particularly since this provides a way to
9524 test your @var{action-if-cross-compiling} even when you are not using a
9525 cross-compiler.
9527 @example
9528 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9529 # to use the slow link-only method
9530 save_cross_compiling=$cross_compiling
9531 cross_compiling=yes
9532 AC_COMPUTE_INT([@dots{}])
9533 cross_compiling=$save_cross_compiling
9534 @end example
9536 A C or C++ runtime test should be portable.
9537 @xref{Portable C and C++}.
9539 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9540 function: the given status code is used to determine the success of the test
9541 (status is @code{0}) or its failure (status is different than @code{0}), as
9542 explained above.  It must be noted that data output through the standard output
9543 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9544 Therefore, if a test must output configuration information, it is recommended
9545 to create and to output data into the temporary file named @file{conftest.out},
9546 using the functions of module @code{file}.  The @code{conftest.out} file is
9547 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9548 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9549 macro is:
9551 @example
9552 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9553 AC_ERLANG_NEED_ERL
9554 AC_LANG(Erlang)
9555 AC_RUN_IFELSE(
9556   [AC_LANG_PROGRAM([], [dnl
9557     file:write_file("conftest.out", code:lib_dir()),
9558     halt(0)])],
9559   [echo "code:lib_dir() returned: `cat conftest.out`"],
9560   [AC_MSG_FAILURE([test Erlang program execution failed])])
9561 @end example
9564 @node Systemology
9565 @section Systemology
9566 @cindex Systemology
9568 This section aims at presenting some systems and pointers to
9569 documentation.  It may help you addressing particular problems reported
9570 by users.
9572 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9573 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9574 operating system}.
9576 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9577 contains a table correlating the features of various Posix-conforming
9578 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9579 simplified diagram of how many Unix systems were derived from each
9580 other.
9582 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9583 provides some variants of traditional implementations of Unix utilities.
9585 @table @asis
9586 @item Darwin
9587 @cindex Darwin
9588 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9589 case-preserving, but case insensitive.  This can cause nasty problems,
9590 since for instance the installation attempt for a package having an
9591 @file{INSTALL} file can result in @samp{make install} report that
9592 nothing was to be done!
9594 That's all dependent on whether the file system is a UFS (case
9595 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9596 install the OS on HFS+.  Unfortunately, there are some pieces of
9597 software which really need to be built on UFS@.  We may want to rebuild
9598 Darwin to have both UFS and HFS+ available (and put the /local/build
9599 tree on the UFS).
9601 @item QNX 4.25
9602 @cindex QNX 4.25
9603 @c FIXME: Please, if you feel like writing something more precise,
9604 @c it'd be great.  In particular, I can't understand the difference with
9605 @c QNX Neutrino.
9606 QNX is a realtime operating system running on Intel architecture
9607 meant to be scalable from the small embedded systems to the hundred
9608 processor super-computer.  It claims to be Posix certified.  More
9609 information is available on the
9610 @uref{http://@/www.qnx.com/, QNX home page}.
9612 @item Tru64
9613 @cindex Tru64
9614 @uref{http://@/h30097.www3.hp.com/@/docs/,
9615 Documentation of several versions of Tru64} is available in different
9616 formats.
9618 @item Unix version 7
9619 @cindex Unix version 7
9620 @cindex V7
9621 Officially this was called the ``Seventh Edition'' of ``the UNIX
9622 time-sharing system'' but we use the more-common name ``Unix version 7''.
9623 Documentation is available in the
9624 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9625 Previous versions of Unix are called ``Unix version 6'', etc., but
9626 they were not as widely used.
9627 @end table
9630 @node Multiple Cases
9631 @section Multiple Cases
9633 Some operations are accomplished in several possible ways, depending on
9634 the OS variant.  Checking for them essentially requires a ``case
9635 statement''.  Autoconf does not directly provide one; however, it is
9636 easy to simulate by using a shell variable to keep track of whether a
9637 way to perform the operation has been found yet.
9639 Here is an example that uses the shell variable @code{fstype} to keep
9640 track of whether the remaining cases need to be checked.  Note that
9641 since the value of @code{fstype} is under our control, we don't have to
9642 use the longer @samp{test "x$fstype" = xno}.
9644 @example
9645 @group
9646 AC_MSG_CHECKING([how to get file system type])
9647 fstype=no
9648 # The order of these tests is important.
9649 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9650 #include <sys/fstyp.h>]])],
9651                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9652                      [Define if statvfs exists.])
9653                    fstype=SVR4])
9654 if test $fstype = no; then
9655   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9656 #include <sys/fstyp.h>]])],
9657                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9658                      [Define if USG statfs.])
9659                    fstype=SVR3])
9661 if test $fstype = no; then
9662   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9663 #include <sys/vmount.h>]])]),
9664                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9665                      [Define if AIX statfs.])
9666                    fstype=AIX])
9668 # (more cases omitted here)
9669 AC_MSG_RESULT([$fstype])
9670 @end group
9671 @end example
9673 @c ====================================================== Results of Tests.
9675 @node Results
9676 @chapter Results of Tests
9678 Once @command{configure} has determined whether a feature exists, what can
9679 it do to record that information?  There are four sorts of things it can
9680 do: define a C preprocessor symbol, set a variable in the output files,
9681 save the result in a cache file for future @command{configure} runs, and
9682 print a message letting the user know the result of the test.
9684 @menu
9685 * Defining Symbols::            Defining C preprocessor symbols
9686 * Setting Output Variables::    Replacing variables in output files
9687 * Special Chars in Variables::  Characters to beware of in variables
9688 * Caching Results::             Speeding up subsequent @command{configure} runs
9689 * Printing Messages::           Notifying @command{configure} users
9690 @end menu
9692 @node Defining Symbols
9693 @section Defining C Preprocessor Symbols
9695 A common action to take in response to a feature test is to define a C
9696 preprocessor symbol indicating the results of the test.  That is done by
9697 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9699 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9700 into the output variable @code{DEFS}, which contains an option
9701 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9702 Autoconf version 1, there is no variable @code{DEFS} defined while
9703 @command{configure} is running.  To check whether Autoconf macros have
9704 already defined a certain C preprocessor symbol, test the value of the
9705 appropriate cache variable, as in this example:
9707 @example
9708 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9709                           [Define if vprintf exists.])])
9710 if test "x$ac_cv_func_vprintf" != xyes; then
9711   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9712                             [Define if _doprnt exists.])])
9714 @end example
9716 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9717 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9718 correct values into @code{#define} statements in a template file.
9719 @xref{Configuration Headers}, for more information about this kind of
9720 output.
9722 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9723 @defmacx AC_DEFINE (@var{variable})
9724 @cvindex @var{variable}
9725 @acindex{DEFINE}
9726 Define @var{variable} to @var{value} (verbatim), by defining a C
9727 preprocessor macro for @var{variable}.  @var{variable} should be a C
9728 identifier, optionally suffixed by a parenthesized argument list to
9729 define a C preprocessor macro with arguments.  The macro argument list,
9730 if present, should be a comma-separated list of C identifiers, possibly
9731 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
9732 @var{variable} should not contain comments, white space, trigraphs,
9733 backslash-newlines, universal character names, or non-ASCII
9734 characters.
9736 @var{value} may contain backslash-escaped newlines, which will be
9737 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9738 via @code{@@DEFS@@} (with no effect on the compilation, since the
9739 preprocessor sees only one line in the first place).  @var{value} should
9740 not contain raw newlines.  If you are not using
9741 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9742 characters, as @command{make} tends to eat them.  To use a shell
9743 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9745 @var{description} is only useful if you are using
9746 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9747 the generated @file{config.h.in} as the comment before the macro define.
9748 The following example defines the C preprocessor variable
9749 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9751 @example
9752 AC_DEFINE([EQUATION], ["$a > $b"],
9753   [Equation string.])
9754 @end example
9756 If neither @var{value} nor @var{description} are given, then
9757 @var{value} defaults to 1 instead of to the empty string.  This is for
9758 backwards compatibility with older versions of Autoconf, but this usage
9759 is obsolescent and may be withdrawn in future versions of Autoconf.
9761 If the @var{variable} is a literal string, it is passed to
9762 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9764 If multiple @code{AC_DEFINE} statements are executed for the same
9765 @var{variable} name (not counting any parenthesized argument list),
9766 the last one wins.
9767 @end defmac
9769 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9770 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9771 @acindex{DEFINE_UNQUOTED}
9772 @cvindex @var{variable}
9773 Like @code{AC_DEFINE}, but three shell expansions are
9774 performed---once---on @var{variable} and @var{value}: variable expansion
9775 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9776 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9777 characters in the value have no
9778 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9779 @var{variable} or @var{value} is a shell variable.  Examples:
9781 @example
9782 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9783   [Configuration machine file.])
9784 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9785   [getgroups return type.])
9786 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9787   [Translated header name.])
9788 @end example
9789 @end defmac
9791 Due to a syntactical bizarreness of the Bourne shell, do not use
9792 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9793 calls from other macro calls or shell code; that can cause syntax errors
9794 in the resulting @command{configure} script.  Use either blanks or
9795 newlines.  That is, do this:
9797 @example
9798 AC_CHECK_HEADER([elf.h],
9799   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9800 @end example
9802 @noindent
9803 or this:
9805 @example
9806 AC_CHECK_HEADER([elf.h],
9807   [AC_DEFINE([SVR4], [1], [System V Release 4])
9808    LIBS="-lelf $LIBS"])
9809 @end example
9811 @noindent
9812 instead of this:
9814 @example
9815 AC_CHECK_HEADER([elf.h],
9816   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9817 @end example
9819 @node Setting Output Variables
9820 @section Setting Output Variables
9821 @cindex Output variables
9823 Another way to record the results of tests is to set @dfn{output
9824 variables}, which are shell variables whose values are substituted into
9825 files that @command{configure} outputs.  The two macros below create new
9826 output variables.  @xref{Preset Output Variables}, for a list of output
9827 variables that are always available.
9829 @defmac AC_SUBST (@var{variable}, @ovar{value})
9830 @acindex{SUBST}
9831 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9832 substitute the variable @var{variable} into output files (typically one
9833 or more makefiles).  This means that @code{AC_OUTPUT}
9834 replaces instances of @samp{@@@var{variable}@@} in input files with the
9835 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9836 is called.  The value can contain any non-@code{NUL} character, including
9837 newline.  If you are using Automake 1.11 or newer, for newlines in values
9838 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9839 @command{automake} from adding a line @code{@var{variable} =
9840 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9841 Automake, automake, Other things Automake recognizes}).
9843 Variable occurrences should not overlap: e.g., an input file should
9844 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9845 are variable names.
9846 The substituted value is not rescanned for more output variables;
9847 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9848 literally into the output file.  (The algorithm uses the special marker
9849 @code{|#_!!_#|} internally, so neither the substituted value nor the
9850 output file may contain @code{|#_!!_#|}.)
9852 If @var{value} is given, in addition assign it to @var{variable}.
9854 The string @var{variable} is passed to @code{m4_pattern_allow}
9855 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
9856 even if there is another macro by the same name.
9857 @end defmac
9859 @defmac AC_SUBST_FILE (@var{variable})
9860 @acindex{SUBST_FILE}
9861 Another way to create an output variable from a shell variable.  Make
9862 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9863 named by shell variable @var{variable} into output files.  This means
9864 that @code{AC_OUTPUT} replaces instances of
9865 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9866 with the contents of the file that the shell variable @var{variable}
9867 names when @code{AC_OUTPUT} is called.  Set the variable to
9868 @file{/dev/null} for cases that do not have a file to insert.
9869 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9870 line by itself, optionally surrounded by spaces and tabs.  The
9871 substitution replaces the whole line, including the spaces, tabs, and
9872 the terminating newline.
9874 This macro is useful for inserting makefile fragments containing
9875 special dependencies or other @command{make} directives for particular host
9876 or target types into makefiles.  For example, @file{configure.ac}
9877 could contain:
9879 @example
9880 AC_SUBST_FILE([host_frag])
9881 host_frag=$srcdir/conf/sun4.mh
9882 @end example
9884 @noindent
9885 and then a @file{Makefile.in} could contain:
9887 @example
9888 @@host_frag@@
9889 @end example
9891 The string @var{variable} is passed to @code{m4_pattern_allow}
9892 (@pxref{Forbidden Patterns}).
9893 @end defmac
9895 @cindex Precious Variable
9896 @cindex Variable, Precious
9897 Running @command{configure} in varying environments can be extremely
9898 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9899 ./configure}, then the cache, @file{config.h}, and many other output
9900 files depend upon @command{bizarre-cc} being the C compiler.  If
9901 for some reason the user runs @command{./configure} again, or if it is
9902 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9903 and @pxref{config.status Invocation}), then the configuration can be
9904 inconsistent, composed of results depending upon two different
9905 compilers.
9907 Environment variables that affect this situation, such as @samp{CC}
9908 above, are called @dfn{precious variables}, and can be declared as such
9909 by @code{AC_ARG_VAR}.
9911 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9912 @acindex{ARG_VAR}
9913 Declare @var{variable} is a precious variable, and include its
9914 @var{description} in the variable section of @samp{./configure --help}.
9916 Being precious means that
9917 @itemize @minus
9918 @item
9919 @var{variable} is substituted via @code{AC_SUBST}.
9921 @item
9922 The value of @var{variable} when @command{configure} was launched is
9923 saved in the cache, including if it was not specified on the command
9924 line but via the environment.  Indeed, while @command{configure} can
9925 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9926 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9927 which, unfortunately, is what most users do.
9929 We emphasize that it is the @emph{initial} value of @var{variable} which
9930 is saved, not that found during the execution of @command{configure}.
9931 Indeed, specifying @samp{./configure FOO=foo} and letting
9932 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9933 different things.
9935 @item
9936 @var{variable} is checked for consistency between two
9937 @command{configure} runs.  For instance:
9939 @example
9940 $ @kbd{./configure --silent --config-cache}
9941 $ @kbd{CC=cc ./configure --silent --config-cache}
9942 configure: error: `CC' was not set in the previous run
9943 configure: error: changes in the environment can compromise \
9944 the build
9945 configure: error: run `make distclean' and/or \
9946 `rm config.cache' and start over
9947 @end example
9949 @noindent
9950 and similarly if the variable is unset, or if its content is changed.
9951 If the content has white space changes only, then the error is degraded
9952 to a warning only, but the old value is reused.
9954 @item
9955 @var{variable} is kept during automatic reconfiguration
9956 (@pxref{config.status Invocation}) as if it had been passed as a command
9957 line argument, including when no cache is used:
9959 @example
9960 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9961 $ @kbd{./config.status --recheck}
9962 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9963   CC=/usr/bin/cc  --no-create --no-recursion
9964 @end example
9965 @end itemize
9966 @end defmac
9968 @node Special Chars in Variables
9969 @section Special Characters in Output Variables
9970 @cindex Output variables, special characters in
9972 Many output variables are intended to be evaluated both by
9973 @command{make} and by the shell.  Some characters are expanded
9974 differently in these two contexts, so to avoid confusion these
9975 variables' values should not contain any of the following characters:
9977 @example
9978 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9979 @end example
9981 Also, these variables' values should neither contain newlines, nor start
9982 with @samp{~}, nor contain white space or @samp{:} immediately followed
9983 by @samp{~}.  The values can contain nonempty sequences of white space
9984 characters like tabs and spaces, but each such sequence might
9985 arbitrarily be replaced by a single space during substitution.
9987 These restrictions apply both to the values that @command{configure}
9988 computes, and to the values set directly by the user.  For example, the
9989 following invocations of @command{configure} are problematic, since they
9990 attempt to use special characters within @code{CPPFLAGS} and white space
9991 within @code{$(srcdir)}:
9993 @example
9994 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9996 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9997 @end example
9999 @node Caching Results
10000 @section Caching Results
10001 @cindex Cache
10003 To avoid checking for the same features repeatedly in various
10004 @command{configure} scripts (or in repeated runs of one script),
10005 @command{configure} can optionally save the results of many checks in a
10006 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10007 runs with caching enabled and finds a cache file, it reads the results
10008 of previous runs from the cache and avoids rerunning those checks.  As a
10009 result, @command{configure} can then run much faster than if it had to
10010 perform all of the checks every time.
10012 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10013 @acindex{CACHE_VAL}
10014 Ensure that the results of the check identified by @var{cache-id} are
10015 available.  If the results of the check were in the cache file that was
10016 read, and @command{configure} was not given the @option{--quiet} or
10017 @option{--silent} option, print a message saying that the result was
10018 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10019 the shell commands are run to determine the value, the value is
10020 saved in the cache file just before @command{configure} creates its output
10021 files.  @xref{Cache Variable Names}, for how to choose the name of the
10022 @var{cache-id} variable.
10024 The @var{commands-to-set-it} @emph{must have no side effects} except for
10025 setting the variable @var{cache-id}, see below.
10026 @end defmac
10028 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10029   @var{commands-to-set-it})
10030 @acindex{CACHE_CHECK}
10031 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10032 messages.  This macro provides a convenient shorthand for the most
10033 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10034 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10035 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10037 The @var{commands-to-set-it} @emph{must have no side effects} except for
10038 setting the variable @var{cache-id}, see below.
10039 @end defmac
10041 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10042 @code{AC_CACHE_CHECK}, because people are tempted to call
10043 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10044 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10045 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10046 instance, the following macro is broken:
10048 @example
10049 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10050 @group
10051 AC_DEFUN([AC_SHELL_TRUE],
10052 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10053                 [my_cv_shell_true_works=no
10054                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10055                  if test "x$my_cv_shell_true_works" = xyes; then
10056                    AC_DEFINE([TRUE_WORKS], [1],
10057                              [Define if `true(1)' works properly.])
10058                  fi])
10060 @end group
10061 @end example
10063 @noindent
10064 This fails if the cache is enabled: the second time this macro is run,
10065 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10068 @example
10069 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10070 @group
10071 AC_DEFUN([AC_SHELL_TRUE],
10072 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10073                 [my_cv_shell_true_works=no
10074                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10075  if test "x$my_cv_shell_true_works" = xyes; then
10076    AC_DEFINE([TRUE_WORKS], [1],
10077              [Define if `true(1)' works properly.])
10078  fi
10080 @end group
10081 @end example
10083 Also, @var{commands-to-set-it} should not print any messages, for
10084 example with @code{AC_MSG_CHECKING}; do that before calling
10085 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10086 the results of the check are retrieved from the cache or determined by
10087 running the shell commands.
10089 @menu
10090 * Cache Variable Names::        Shell variables used in caches
10091 * Cache Files::                 Files @command{configure} uses for caching
10092 * Cache Checkpointing::         Loading and saving the cache file
10093 @end menu
10095 @node Cache Variable Names
10096 @subsection Cache Variable Names
10097 @cindex Cache variable
10099 The names of cache variables should have the following format:
10101 @example
10102 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10103 @end example
10105 @noindent
10106 for example, @samp{ac_cv_header_stat_broken} or
10107 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10109 @table @asis
10110 @item @var{package-prefix}
10111 An abbreviation for your package or organization; the same prefix you
10112 begin local Autoconf macros with, except lowercase by convention.
10113 For cache values used by the distributed Autoconf macros, this value is
10114 @samp{ac}.
10116 @item @code{_cv_}
10117 Indicates that this shell variable is a cache value.  This string
10118 @emph{must} be present in the variable name, including the leading
10119 underscore.
10121 @item @var{value-type}
10122 A convention for classifying cache values, to produce a rational naming
10123 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10125 @item @var{specific-value}
10126 Which member of the class of cache values this test applies to.
10127 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10128 output variable (@samp{INSTALL}).
10130 @item @var{additional-options}
10131 Any particular behavior of the specific member that this test applies to.
10132 For example, @samp{broken} or @samp{set}.  This part of the name may
10133 be omitted if it does not apply.
10134 @end table
10136 The values assigned to cache variables may not contain newlines.
10137 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10138 names of files or functions; so this is not an important restriction.
10139 @ref{Cache Variable Index} for an index of cache variables with
10140 documented semantics.
10143 @node Cache Files
10144 @subsection Cache Files
10146 A cache file is a shell script that caches the results of configure
10147 tests run on one system so they can be shared between configure scripts
10148 and configure runs.  It is not useful on other systems.  If its contents
10149 are invalid for some reason, the user may delete or edit it, or override
10150 documented cache variables on the @command{configure} command line.
10152 By default, @command{configure} uses no cache file,
10153 to avoid problems caused by accidental
10154 use of stale cache files.
10156 To enable caching, @command{configure} accepts @option{--config-cache} (or
10157 @option{-C}) to cache results in the file @file{config.cache}.
10158 Alternatively, @option{--cache-file=@var{file}} specifies that
10159 @var{file} be the cache file.  The cache file is created if it does not
10160 exist already.  When @command{configure} calls @command{configure} scripts in
10161 subdirectories, it uses the @option{--cache-file} argument so that they
10162 share the same cache.  @xref{Subdirectories}, for information on
10163 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10165 @file{config.status} only pays attention to the cache file if it is
10166 given the @option{--recheck} option, which makes it rerun
10167 @command{configure}.
10169 It is wrong to try to distribute cache files for particular system types.
10170 There is too much room for error in doing that, and too much
10171 administrative overhead in maintaining them.  For any features that
10172 can't be guessed automatically, use the standard method of the canonical
10173 system type and linking files (@pxref{Manual Configuration}).
10175 The site initialization script can specify a site-wide cache file to
10176 use, instead of the usual per-program cache.  In this case, the cache
10177 file gradually accumulates information whenever someone runs a new
10178 @command{configure} script.  (Running @command{configure} merges the new cache
10179 results with the existing cache file.)  This may cause problems,
10180 however, if the system configuration (e.g., the installed libraries or
10181 compilers) changes and the stale cache file is not deleted.
10183 If @command{configure} is interrupted at the right time when it updates
10184 a cache file outside of the build directory where the @command{configure}
10185 script is run, it may leave behind a temporary file named after the
10186 cache file with digits following it.  You may safely delete such a file.
10189 @node Cache Checkpointing
10190 @subsection Cache Checkpointing
10192 If your configure script, or a macro called from @file{configure.ac}, happens
10193 to abort the configure process, it may be useful to checkpoint the cache
10194 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10195 reduces the amount of time it takes to rerun the configure script with
10196 (hopefully) the error that caused the previous abort corrected.
10198 @c FIXME: Do we really want to document this guy?
10199 @defmac AC_CACHE_LOAD
10200 @acindex{CACHE_LOAD}
10201 Loads values from existing cache file, or creates a new cache file if a
10202 cache file is not found.  Called automatically from @code{AC_INIT}.
10203 @end defmac
10205 @defmac AC_CACHE_SAVE
10206 @acindex{CACHE_SAVE}
10207 Flushes all cached values to the cache file.  Called automatically from
10208 @code{AC_OUTPUT}, but it can be quite useful to call
10209 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10210 @end defmac
10212 For instance:
10214 @example
10215 @r{ @dots{} AC_INIT, etc. @dots{}}
10216 @group
10217 # Checks for programs.
10218 AC_PROG_CC
10219 AC_PROG_AWK
10220 @r{ @dots{} more program checks @dots{}}
10221 AC_CACHE_SAVE
10222 @end group
10224 @group
10225 # Checks for libraries.
10226 AC_CHECK_LIB([nsl], [gethostbyname])
10227 AC_CHECK_LIB([socket], [connect])
10228 @r{ @dots{} more lib checks @dots{}}
10229 AC_CACHE_SAVE
10230 @end group
10232 @group
10233 # Might abort@dots{}
10234 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10235 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10236 @end group
10237 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10238 @end example
10240 @node Printing Messages
10241 @section Printing Messages
10242 @cindex Messages, from @command{configure}
10244 @command{configure} scripts need to give users running them several kinds
10245 of information.  The following macros print messages in ways appropriate
10246 for each kind.  The arguments to all of them get enclosed in shell
10247 double quotes, so the shell performs variable and back-quote
10248 substitution on them.
10250 These macros are all wrappers around the @command{echo} shell command.
10251 They direct output to the appropriate file descriptor (@pxref{File
10252 Descriptor Macros}).
10253 @command{configure} scripts should rarely need to run @command{echo} directly
10254 to print messages for the user.  Using these macros makes it easy to
10255 change how and when each kind of message is printed; such changes need
10256 only be made to the macro definitions and all the callers change
10257 automatically.
10259 To diagnose static issues, i.e., when @command{autoconf} is run, see
10260 @ref{Diagnostic Macros}.
10262 @defmac AC_MSG_CHECKING (@var{feature-description})
10263 @acindex{MSG_CHECKING}
10264 Notify the user that @command{configure} is checking for a particular
10265 feature.  This macro prints a message that starts with @samp{checking }
10266 and ends with @samp{...} and no newline.  It must be followed by a call
10267 to @code{AC_MSG_RESULT} to print the result of the check and the
10268 newline.  The @var{feature-description} should be something like
10269 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10270 _Alignof}.
10272 This macro prints nothing if @command{configure} is run with the
10273 @option{--quiet} or @option{--silent} option.
10274 @end defmac
10276 @anchor{AC_MSG_RESULT}
10277 @defmac AC_MSG_RESULT (@var{result-description})
10278 @acindex{MSG_RESULT}
10279 Notify the user of the results of a check.  @var{result-description} is
10280 almost always the value of the cache variable for the check, typically
10281 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10282 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10283 the completion of the message printed by the call to
10284 @code{AC_MSG_CHECKING}.
10286 This macro prints nothing if @command{configure} is run with the
10287 @option{--quiet} or @option{--silent} option.
10288 @end defmac
10290 @anchor{AC_MSG_NOTICE}
10291 @defmac AC_MSG_NOTICE (@var{message})
10292 @acindex{MSG_NOTICE}
10293 Deliver the @var{message} to the user.  It is useful mainly to print a
10294 general description of the overall purpose of a group of feature checks,
10295 e.g.,
10297 @example
10298 AC_MSG_NOTICE([checking if stack overflow is detectable])
10299 @end example
10301 This macro prints nothing if @command{configure} is run with the
10302 @option{--quiet} or @option{--silent} option.
10303 @end defmac
10305 @anchor{AC_MSG_ERROR}
10306 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10307 @acindex{MSG_ERROR}
10308 Notify the user of an error that prevents @command{configure} from
10309 completing.  This macro prints an error message to the standard error
10310 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10311 by default, except that @samp{0} is converted to @samp{1}).
10312 @var{error-description} should be something like @samp{invalid value
10313 $HOME for \$HOME}.
10315 The @var{error-description} should start with a lower-case letter, and
10316 ``cannot'' is preferred to ``can't''.
10317 @end defmac
10319 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10320 @acindex{MSG_FAILURE}
10321 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10322 prevents @command{configure} from completing @emph{and} that additional
10323 details are provided in @file{config.log}.  This is typically used when
10324 abnormal results are found during a compilation.
10325 @end defmac
10327 @anchor{AC_MSG_WARN}
10328 @defmac AC_MSG_WARN (@var{problem-description})
10329 @acindex{MSG_WARN}
10330 Notify the @command{configure} user of a possible problem.  This macro
10331 prints the message to the standard error output; @command{configure}
10332 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10333 provide a default (back-up) behavior for the situations they warn about.
10334 @var{problem-description} should be something like @samp{ln -s seems to
10335 make hard links}.
10336 @end defmac
10340 @c ====================================================== Programming in M4.
10342 @node Programming in M4
10343 @chapter Programming in M4
10344 @cindex M4
10346 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10347 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10348 provides macros dedicated to shell script generation.
10350 As of this version of Autoconf, these two layers still contain
10351 experimental macros, whose interface might change in the future.  As a
10352 matter of fact, @emph{anything that is not documented must not be used}.
10354 @menu
10355 * M4 Quotation::                Protecting macros from unwanted expansion
10356 * Using autom4te::              The Autoconf executables backbone
10357 * Programming in M4sugar::      Convenient pure M4 macros
10358 * Debugging via autom4te::      Figuring out what M4 was doing
10359 @end menu
10361 @node M4 Quotation
10362 @section M4 Quotation
10363 @cindex M4 quotation
10364 @cindex quotation
10366 The most common problem with existing macros is an improper quotation.
10367 This section, which users of Autoconf can skip, but which macro writers
10368 @emph{must} read, first justifies the quotation scheme that was chosen
10369 for Autoconf and then ends with a rule of thumb.  Understanding the
10370 former helps one to follow the latter.
10372 @menu
10373 * Active Characters::           Characters that change the behavior of M4
10374 * One Macro Call::              Quotation and one macro call
10375 * Quoting and Parameters::      M4 vs. shell parameters
10376 * Quotation and Nested Macros::  Macros calling macros
10377 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10378 * Quadrigraphs::                Another way to escape special characters
10379 * Balancing Parentheses::       Dealing with unbalanced parentheses
10380 * Quotation Rule Of Thumb::     One parenthesis, one quote
10381 @end menu
10383 @node Active Characters
10384 @subsection Active Characters
10386 To fully understand where proper quotation is important, you first need
10387 to know what the special characters are in Autoconf: @samp{#} introduces
10388 a comment inside which no macro expansion is performed, @samp{,}
10389 separates arguments, @samp{[} and @samp{]} are the quotes
10390 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10391 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10392 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10393 @samp{$} inside a macro definition.
10395 In order to understand the delicate case of macro calls, we first have
10396 to present some obvious failures.  Below they are ``obvious-ified'',
10397 but when you find them in real life, they are usually in disguise.
10399 Comments, introduced by a hash and running up to the newline, are opaque
10400 tokens to the top level: active characters are turned off, and there is
10401 no macro expansion:
10403 @example
10404 # define([def], ine)
10405 @result{}# define([def], ine)
10406 @end example
10408 Each time there can be a macro expansion, there is a quotation
10409 expansion, i.e., one level of quotes is stripped:
10411 @example
10412 int tab[10];
10413 @result{}int tab10;
10414 [int tab[10];]
10415 @result{}int tab[10];
10416 @end example
10418 Without this in mind, the reader might try hopelessly to use her macro
10419 @code{array}:
10421 @example
10422 define([array], [int tab[10];])
10423 array
10424 @result{}int tab10;
10425 [array]
10426 @result{}array
10427 @end example
10429 @noindent
10430 How can you correctly output the intended results@footnote{Using
10431 @code{defn}.}?
10434 @node One Macro Call
10435 @subsection One Macro Call
10437 Let's proceed on the interaction between active characters and macros
10438 with this small macro, which just returns its first argument:
10440 @example
10441 define([car], [$1])
10442 @end example
10444 @noindent
10445 The two pairs of quotes above are not part of the arguments of
10446 @code{define}; rather, they are understood by the top level when it
10447 tries to find the arguments of @code{define}.  Therefore, assuming
10448 @code{car} is not already defined, it is equivalent to write:
10450 @example
10451 define(car, $1)
10452 @end example
10454 @noindent
10455 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10456 quotes, it is bad practice for Autoconf macros which must both be more
10457 robust and also advocate perfect style.
10459 At the top level, there are only two possibilities: either you
10460 quote or you don't:
10462 @example
10463 car(foo, bar, baz)
10464 @result{}foo
10465 [car(foo, bar, baz)]
10466 @result{}car(foo, bar, baz)
10467 @end example
10469 Let's pay attention to the special characters:
10471 @example
10472 car(#)
10473 @error{}EOF in argument list
10474 @end example
10476 The closing parenthesis is hidden in the comment; with a hypothetical
10477 quoting, the top level understood it this way:
10479 @example
10480 car([#)]
10481 @end example
10483 @noindent
10484 Proper quotation, of course, fixes the problem:
10486 @example
10487 car([#])
10488 @result{}#
10489 @end example
10491 Here are more examples:
10493 @example
10494 car(foo, bar)
10495 @result{}foo
10496 car([foo, bar])
10497 @result{}foo, bar
10498 car((foo, bar))
10499 @result{}(foo, bar)
10500 car([(foo], [bar)])
10501 @result{}(foo
10502 define([a], [b])
10503 @result{}
10504 car(a)
10505 @result{}b
10506 car([a])
10507 @result{}b
10508 car([[a]])
10509 @result{}a
10510 car([[[a]]])
10511 @result{}[a]
10512 @end example
10514 @node Quoting and Parameters
10515 @subsection Quoting and Parameters
10517 When M4 encounters @samp{$} within a macro definition, followed
10518 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10519 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10520 expansion.  This happens regardless of how many layers of quotes the
10521 parameter expansion is nested within, or even if it occurs in text that
10522 will be rescanned as a comment.
10524 @example
10525 define([none], [$1])
10526 @result{}
10527 define([one], [[$1]])
10528 @result{}
10529 define([two], [[[$1]]])
10530 @result{}
10531 define([comment], [# $1])
10532 @result{}
10533 define([active], [ACTIVE])
10534 @result{}
10535 none([active])
10536 @result{}ACTIVE
10537 one([active])
10538 @result{}active
10539 two([active])
10540 @result{}[active]
10541 comment([active])
10542 @result{}# active
10543 @end example
10545 On the other hand, since autoconf generates shell code, you often want
10546 to output shell variable expansion, rather than performing M4 parameter
10547 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10548 from the next character in the definition of your macro.  If the macro
10549 definition occurs in single-quoted text, then insert another level of
10550 quoting; if the usage is already inside a double-quoted string, then
10551 split it into concatenated strings.
10553 @example
10554 define([single], [a single-quoted $[]1 definition])
10555 @result{}
10556 define([double], [[a double-quoted $][1 definition]])
10557 @result{}
10558 single
10559 @result{}a single-quoted $1 definition
10560 double
10561 @result{}a double-quoted $1 definition
10562 @end example
10564 Posix states that M4 implementations are free to provide implementation
10565 extensions when @samp{$@{} is encountered in a macro definition.
10566 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10567 extensions that will be available in the future GNU M4 2.0,
10568 but guarantees that all other instances of @samp{$@{} will be output
10569 literally.  Therefore, this idiom can also be used to output shell code
10570 parameter references:
10572 @example
10573 define([first], [$@{1@}])first
10574 @result{}$@{1@}
10575 @end example
10577 Posix also states that @samp{$11} should expand to the first parameter
10578 concatenated with a literal @samp{1}, although some versions of
10579 GNU M4 expand the eleventh parameter instead.  For
10580 portability, you should only use single-digit M4 parameter expansion.
10582 With this in mind, we can explore the cases where macros invoke
10583 macros@enddots{}
10585 @node Quotation and Nested Macros
10586 @subsection Quotation and Nested Macros
10588 The examples below use the following macros:
10590 @example
10591 define([car], [$1])
10592 define([active], [ACT, IVE])
10593 define([array], [int tab[10]])
10594 @end example
10596 Each additional embedded macro call introduces other possible
10597 interesting quotations:
10599 @example
10600 car(active)
10601 @result{}ACT
10602 car([active])
10603 @result{}ACT, IVE
10604 car([[active]])
10605 @result{}active
10606 @end example
10608 In the first case, the top level looks for the arguments of @code{car},
10609 and finds @samp{active}.  Because M4 evaluates its arguments
10610 before applying the macro, @samp{active} is expanded, which results in:
10612 @example
10613 car(ACT, IVE)
10614 @result{}ACT
10615 @end example
10617 @noindent
10618 In the second case, the top level gives @samp{active} as first and only
10619 argument of @code{car}, which results in:
10621 @example
10622 active
10623 @result{}ACT, IVE
10624 @end example
10626 @noindent
10627 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10628 In the third case, @code{car} receives @samp{[active]}, which results in:
10630 @example
10631 [active]
10632 @result{}active
10633 @end example
10635 @noindent
10636 exactly as we already saw above.
10638 The example above, applied to a more realistic example, gives:
10640 @example
10641 car(int tab[10];)
10642 @result{}int tab10;
10643 car([int tab[10];])
10644 @result{}int tab10;
10645 car([[int tab[10];]])
10646 @result{}int tab[10];
10647 @end example
10649 @noindent
10650 Huh?  The first case is easily understood, but why is the second wrong,
10651 and the third right?  To understand that, you must know that after
10652 M4 expands a macro, the resulting text is immediately subjected
10653 to macro expansion and quote removal.  This means that the quote removal
10654 occurs twice---first before the argument is passed to the @code{car}
10655 macro, and second after the @code{car} macro expands to the first
10656 argument.
10658 As the author of the Autoconf macro @code{car}, you then consider it to
10659 be incorrect that your users have to double-quote the arguments of
10660 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10661 quoted car:
10663 @example
10664 define([qar], [[$1]])
10665 @end example
10667 @noindent
10668 and check that @code{qar} is properly fixed:
10670 @example
10671 qar([int tab[10];])
10672 @result{}int tab[10];
10673 @end example
10675 @noindent
10676 Ahhh!  That's much better.
10678 But note what you've done: now that the result of @code{qar} is always
10679 a literal string, the only time a user can use nested macros is if she
10680 relies on an @emph{unquoted} macro call:
10682 @example
10683 qar(active)
10684 @result{}ACT
10685 qar([active])
10686 @result{}active
10687 @end example
10689 @noindent
10690 leaving no way for her to reproduce what she used to do with @code{car}:
10692 @example
10693 car([active])
10694 @result{}ACT, IVE
10695 @end example
10697 @noindent
10698 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10699 macros:
10701 @example
10702 define([my_includes], [#include <stdio.h>])
10703 car([my_includes])
10704 @result{}#include <stdio.h>
10705 qar(my_includes)
10706 @error{}EOF in argument list
10707 @end example
10709 This macro, @code{qar}, because it double quotes its arguments, forces
10710 its users to leave their macro calls unquoted, which is dangerous.
10711 Commas and other active symbols are interpreted by M4 before
10712 they are given to the macro, often not in the way the users expect.
10713 Also, because @code{qar} behaves differently from the other macros,
10714 it's an exception that should be avoided in Autoconf.
10716 @node Changequote is Evil
10717 @subsection @code{changequote} is Evil
10718 @cindex @code{changequote}
10720 The temptation is often high to bypass proper quotation, in particular
10721 when it's late at night.  Then, many experienced Autoconf hackers
10722 finally surrender to the dark side of the force and use the ultimate
10723 weapon: @code{changequote}.
10725 The M4 builtin @code{changequote} belongs to a set of primitives that
10726 allow one to adjust the syntax of the language to adjust it to one's
10727 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10728 quotes, but in the context of shell programming (and actually of most
10729 programming languages), that's about the worst choice one can make:
10730 because of strings and back-quoted expressions in shell code (such as
10731 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10732 programming languages (as in @samp{'0'}), there are many unbalanced
10733 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10734 not impossible.  In order to make M4 useful in such a context, its
10735 designers have equipped it with @code{changequote}, which makes it
10736 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10737 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10738 because they are unlikely characters, but @emph{because they are
10739 characters unlikely to be unbalanced}.
10741 There are other magic primitives, such as @code{changecom} to specify
10742 what syntactic forms are comments (it is common to see
10743 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10744 @code{changeword} and @code{changesyntax} to change other syntactic
10745 details (such as the character to denote the @var{n}th argument, @samp{$} by
10746 default, the parentheses around arguments, etc.).
10748 These primitives are really meant to make M4 more useful for specific
10749 domains: they should be considered like command line options:
10750 @option{--quotes}, @option{--comments}, @option{--words}, and
10751 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10752 it makes M4 libraries self contained (no need for additional options).
10754 There lies the problem@enddots{}
10756 @sp 1
10758 The problem is that it is then tempting to use them in the middle of an
10759 M4 script, as opposed to its initialization.  This, if not carefully
10760 thought out, can lead to disastrous effects: @emph{you are changing the
10761 language in the middle of the execution}.  Changing and restoring the
10762 syntax is often not enough: if you happened to invoke macros in between,
10763 these macros are lost, as the current syntax is probably not
10764 the one they were implemented with.
10766 @c FIXME: I've been looking for a short, real case example, but I
10767 @c lost them all :(
10770 @node Quadrigraphs
10771 @subsection Quadrigraphs
10772 @cindex quadrigraphs
10773 @cindex @samp{@@S|@@}
10774 @cindex @samp{@@&t@@}
10775 @c Info cannot handle `:' in index entries.
10776 @ifnotinfo
10777 @cindex @samp{@@<:@@}
10778 @cindex @samp{@@:>@@}
10779 @cindex @samp{@@%:@@}
10780 @cindex @samp{@@@{:@@}
10781 @cindex @samp{@@:@}@@}
10782 @end ifnotinfo
10784 When writing an Autoconf macro you may occasionally need to generate
10785 special characters that are difficult to express with the standard
10786 Autoconf quoting rules.  For example, you may need to output the regular
10787 expression @samp{[^[]}, which matches any character other than @samp{[}.
10788 This expression contains unbalanced brackets so it cannot be put easily
10789 into an M4 macro.
10791 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10792 and @code{m4_expand}) which internally use special markers in addition
10793 to the regular quoting characters.  If the arguments to these macros
10794 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10795 might behave incorrectly.
10797 You can work around these problems by using one of the following
10798 @dfn{quadrigraphs}:
10800 @table @samp
10801 @item @@<:@@
10802 @samp{[}
10803 @item @@:>@@
10804 @samp{]}
10805 @item @@S|@@
10806 @samp{$}
10807 @item @@%:@@
10808 @samp{#}
10809 @item @@@{:@@
10810 @samp{(}
10811 @item @@:@}@@
10812 @samp{)}
10813 @item @@&t@@
10814 Expands to nothing.
10815 @end table
10817 Quadrigraphs are replaced at a late stage of the translation process,
10818 after @command{m4} is run, so they do not get in the way of M4 quoting.
10819 For example, the string @samp{^@@<:@@}, independently of its quotation,
10820 appears as @samp{^[} in the output.
10822 The empty quadrigraph can be used:
10824 @itemize @minus
10825 @item to mark trailing spaces explicitly
10827 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10829 @item to produce quadrigraphs and other strings reserved by m4sugar
10831 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10832 contrived example:
10834 @example
10835 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10836 m4_split([a )@}>=- b -=<@{( c])
10837 @result{}[a], [], [B], [], [c]
10838 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10839 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10840 @end example
10842 @item to escape @emph{occurrences} of forbidden patterns
10844 For instance you might want to mention @code{AC_FOO} in a comment, while
10845 still being sure that @command{autom4te} still catches unexpanded
10846 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10847 @end itemize
10849 The name @samp{@@&t@@} was suggested by Paul Eggert:
10851 @quotation
10852 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10853 own invention, but the @samp{t} came from the source code of the
10854 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10855 and which used @samp{mt} to denote the empty string.  In C, it would
10856 have looked like something like:
10858 @example
10859 char const mt[] = "";
10860 @end example
10862 @noindent
10863 but of course the source code was written in Algol 68.
10865 I don't know where he got @samp{mt} from: it could have been his own
10866 invention, and I suppose it could have been a common pun around the
10867 Cambridge University computer lab at the time.
10868 @end quotation
10871 @node Balancing Parentheses
10872 @subsection Dealing with unbalanced parentheses
10873 @cindex balancing parentheses
10874 @cindex parentheses, balancing
10875 @cindex unbalanced parentheses, managing
10877 One of the pitfalls of portable shell programming is that @command{case}
10878 statements require unbalanced parentheses (@pxref{case, , Limitations of
10879 Shell Builtins}).  With syntax highlighting
10880 editors, the presence of unbalanced @samp{)} can interfere with editors
10881 that perform syntax highlighting of macro contents based on finding the
10882 matching @samp{(}.  Another concern is how much editing must be done
10883 when transferring code snippets between shell scripts and macro
10884 definitions.  But most importantly, the presence of unbalanced
10885 parentheses can introduce expansion bugs.
10887 For an example, here is an underquoted attempt to use the macro
10888 @code{my_case}, which happens to expand to a portable @command{case}
10889 statement:
10891 @example
10892 AC_DEFUN([my_case],
10893 [case $file_name in
10894   *.c) echo "C source code";;
10895 esac])
10896 AS_IF(:, my_case)
10897 @end example
10899 @noindent
10900 In the above example, the @code{AS_IF} call underquotes its arguments.
10901 As a result, the unbalanced @samp{)} generated by the premature
10902 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10903 truncated parameter, and the expansion is syntactically invalid:
10905 @example
10906 if :; then
10907   case $file_name in
10908   *.c
10909 fi echo "C source code";;
10910 esac)
10911 @end example
10913 If nothing else, this should emphasize the importance of the quoting
10914 arguments to macro calls.  On the other hand, there are several
10915 variations for defining @code{my_case} to be more robust, even when used
10916 without proper quoting, each with some benefits and some drawbacks.
10918 @itemize @w{}
10919 @item Creative literal shell comment
10920 @example
10921 AC_DEFUN([my_case],
10922 [case $file_name in #(
10923   *.c) echo "C source code";;
10924 esac])
10925 @end example
10926 @noindent
10927 This version provides balanced parentheses to several editors, and can
10928 be copied and pasted into a terminal as is.  Unfortunately, it is still
10929 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10930 that masks the normal properties of @samp{(}.
10932 @item Quadrigraph shell comment
10933 @example
10934 AC_DEFUN([my_case],
10935 [case $file_name in @@%:@@(
10936   *.c) echo "C source code";;
10937 esac])
10938 @end example
10939 @noindent
10940 This version provides balanced parentheses to even more editors, and can
10941 be used as a balanced Autoconf argument.  Unfortunately, it requires
10942 some editing before it can be copied and pasted into a terminal, and the
10943 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10945 @item Quoting just the parenthesis
10946 @example
10947 AC_DEFUN([my_case],
10948 [case $file_name in
10949   *.c[)] echo "C source code";;
10950 esac])
10951 @end example
10952 @noindent
10953 This version quotes the @samp{)}, so that it can be used as a balanced
10954 Autoconf argument.  As written, this is not balanced to an editor, but
10955 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10956 still requires some edits before it can be copied and pasted into a
10957 terminal.
10959 @item Double-quoting the entire statement
10960 @example
10961 AC_DEFUN([my_case],
10962 [[case $file_name in #(
10963   *.c) echo "C source code";;
10964 esac]])
10965 @end example
10966 @noindent
10967 Since the entire macro is double-quoted, there is no problem with using
10968 this as an Autoconf argument; and since the double-quoting is over the
10969 entire statement, this code can be easily copied and pasted into a
10970 terminal.  However, the double quoting prevents the expansion of any
10971 macros inside the case statement, which may cause its own set of
10972 problems.
10974 @item Using @code{AS_CASE}
10975 @example
10976 AC_DEFUN([my_case],
10977 [AS_CASE([$file_name],
10978   [*.c], [echo "C source code"])])
10979 @end example
10980 @noindent
10981 This version avoids the balancing issue altogether, by relying on
10982 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10983 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10984 statement, rather than within a branch of the case statement that might
10985 not be taken.  However, the abstraction comes with a penalty that it is
10986 no longer a quick copy, paste, and edit to get back to shell code.
10987 @end itemize
10990 @node Quotation Rule Of Thumb
10991 @subsection Quotation Rule Of Thumb
10993 To conclude, the quotation rule of thumb is:
10995 @center @emph{One pair of quotes per pair of parentheses.}
10997 Never over-quote, never under-quote, in particular in the definition of
10998 macros.  In the few places where the macros need to use brackets
10999 (usually in C program text or regular expressions), properly quote
11000 @emph{the arguments}!
11002 It is common to read Autoconf programs with snippets like:
11004 @example
11005 AC_TRY_LINK(
11006 changequote(<<, >>)dnl
11007 <<#include <time.h>
11008 #ifndef tzname /* For SGI.  */
11009 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11010 #endif>>,
11011 changequote([, ])dnl
11012 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11013 @end example
11015 @noindent
11016 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11017 double quoting, so you just need:
11019 @example
11020 AC_TRY_LINK(
11021 [#include <time.h>
11022 #ifndef tzname /* For SGI.  */
11023 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11024 #endif],
11025             [atoi (*tzname);],
11026             [ac_cv_var_tzname=yes],
11027             [ac_cv_var_tzname=no])
11028 @end example
11030 @noindent
11031 The M4-fluent reader might note that these two examples are rigorously
11032 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11033 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11034 quotes are not part of the arguments!
11036 Simplified, the example above is just doing this:
11038 @example
11039 changequote(<<, >>)dnl
11040 <<[]>>
11041 changequote([, ])dnl
11042 @end example
11044 @noindent
11045 instead of simply:
11047 @example
11048 [[]]
11049 @end example
11051 With macros that do not double quote their arguments (which is the
11052 rule), double-quote the (risky) literals:
11054 @example
11055 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11056 [[#include <time.h>
11057 #ifndef tzname /* For SGI.  */
11058 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11059 #endif]],
11060                                 [atoi (*tzname);])],
11061                [ac_cv_var_tzname=yes],
11062                [ac_cv_var_tzname=no])
11063 @end example
11065 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11066 should be using @code{AC_LINK_IFELSE} instead.
11068 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11069 where quoting does not suffice.
11071 When you create a @command{configure} script using newly written macros,
11072 examine it carefully to check whether you need to add more quotes in
11073 your macros.  If one or more words have disappeared in the M4
11074 output, you need more quotes.  When in doubt, quote.
11076 However, it's also possible to put on too many layers of quotes.  If
11077 this happens, the resulting @command{configure} script may contain
11078 unexpanded macros.  The @command{autoconf} program checks for this problem
11079 by looking for the string @samp{AC_} in @file{configure}.  However, this
11080 heuristic does not work in general: for example, it does not catch
11081 overquoting in @code{AC_DEFINE} descriptions.
11084 @c ---------------------------------------- Using autom4te
11086 @node Using autom4te
11087 @section Using @command{autom4te}
11089 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11090 to Autoconf per se, heavily rely on M4.  All these different uses
11091 revealed common needs factored into a layer over M4:
11092 @command{autom4te}@footnote{
11094 Yet another great name from Lars J. Aas.
11098 @command{autom4te} is a preprocessor that is like @command{m4}.
11099 It supports M4 extensions designed for use in tools like Autoconf.
11101 @menu
11102 * autom4te Invocation::         A GNU M4 wrapper
11103 * Customizing autom4te::        Customizing the Autoconf package
11104 @end menu
11106 @node autom4te Invocation
11107 @subsection Invoking @command{autom4te}
11109 The command line arguments are modeled after M4's:
11111 @example
11112 autom4te @var{options} @var{files}
11113 @end example
11115 @noindent
11116 @evindex M4
11117 where the @var{files} are directly passed to @command{m4}.  By default,
11118 GNU M4 is found during configuration, but the environment
11119 variable
11120 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11121 to the regular expansion, it handles the replacement of the quadrigraphs
11122 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11123 output.  It supports an extended syntax for the @var{files}:
11125 @table @file
11126 @item @var{file}.m4f
11127 This file is an M4 frozen file.  Note that @emph{all the previous files
11128 are ignored}.  See the option @option{--melt} for the rationale.
11130 @item @var{file}?
11131 If found in the library path, the @var{file} is included for expansion,
11132 otherwise it is ignored instead of triggering a failure.
11133 @end table
11135 @sp 1
11137 Of course, it supports the Autoconf common subset of options:
11139 @table @option
11140 @item --help
11141 @itemx -h
11142 Print a summary of the command line options and exit.
11144 @item --version
11145 @itemx -V
11146 Print the version number of Autoconf and exit.
11148 @item --verbose
11149 @itemx -v
11150 Report processing steps.
11152 @item --debug
11153 @itemx -d
11154 Don't remove the temporary files and be even more verbose.
11156 @item --include=@var{dir}
11157 @itemx -I @var{dir}
11158 Also look for input files in @var{dir}.  Multiple invocations
11159 accumulate.
11161 @item --output=@var{file}
11162 @itemx -o @var{file}
11163 Save output (script or trace) to @var{file}.  The file @option{-} stands
11164 for the standard output.
11165 @end table
11167 @sp 1
11169 As an extension of @command{m4}, it includes the following options:
11171 @table @option
11172 @item --warnings=@var{category}
11173 @itemx -W @var{category}
11174 @evindex WARNINGS
11175 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11176 Report the warnings related to @var{category} (which can actually be a
11177 comma separated list).  @xref{Reporting Messages}, macro
11178 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11179 values include:
11181 @table @samp
11182 @item all
11183 report all the warnings
11185 @item none
11186 report none
11188 @item error
11189 treats warnings as errors
11191 @item no-@var{category}
11192 disable warnings falling into @var{category}
11193 @end table
11195 Warnings about @samp{syntax} are enabled by default, and the environment
11196 variable @env{WARNINGS}, a comma separated list of categories, is
11197 honored.  @samp{autom4te -W @var{category}} actually
11198 behaves as if you had run:
11200 @example
11201 autom4te --warnings=syntax,$WARNINGS,@var{category}
11202 @end example
11204 @noindent
11205 For example, if you want to disable defaults and @env{WARNINGS}
11206 of @command{autom4te}, but enable the warnings about obsolete
11207 constructs, you would use @option{-W none,obsolete}.
11209 @cindex Back trace
11210 @cindex Macro invocation stack
11211 @command{autom4te} displays a back trace for errors, but not for
11212 warnings; if you want them, just pass @option{-W error}.
11214 @item --melt
11215 @itemx -M
11216 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11217 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11218 are executed only when the files are frozen, typically
11219 @code{m4_define}.  For instance, running:
11221 @example
11222 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11223 @end example
11225 @noindent
11226 is roughly equivalent to running:
11228 @example
11229 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11230 @end example
11232 @noindent
11233 while
11235 @example
11236 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11237 @end example
11239 @noindent
11240 is equivalent to:
11242 @example
11243 m4 --reload-state=4.m4f input.m4
11244 @end example
11246 @item --freeze
11247 @itemx -F
11248 Produce a frozen state file.  @command{autom4te} freezing is stricter
11249 than M4's: it must produce no warnings, and no output other than empty
11250 lines (a line with white space is @emph{not} empty) and comments
11251 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11252 this option takes no argument:
11254 @example
11255 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11256 @end example
11258 @noindent
11259 corresponds to
11261 @example
11262 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11263 @end example
11265 @item --mode=@var{octal-mode}
11266 @itemx -m @var{octal-mode}
11267 Set the mode of the non-traces output to @var{octal-mode}; by default
11268 @samp{0666}.
11269 @end table
11271 @sp 1
11273 @cindex @file{autom4te.cache}
11274 As another additional feature over @command{m4}, @command{autom4te}
11275 caches its results.  GNU M4 is able to produce a regular
11276 output and traces at the same time.  Traces are heavily used in the
11277 GNU Build System: @command{autoheader} uses them to build
11278 @file{config.h.in}, @command{autoreconf} to determine what
11279 GNU Build System components are used, @command{automake} to
11280 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11281 traces are cached while performing regular expansion,
11282 and conversely.  This cache is (actually, the caches are) stored in
11283 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11284 at any moment (especially if for some reason @command{autom4te}
11285 considers it trashed).
11287 @table @option
11288 @item --cache=@var{directory}
11289 @itemx -C @var{directory}
11290 Specify the name of the directory where the result should be cached.
11291 Passing an empty value disables caching.  Be sure to pass a relative
11292 file name, as for the time being, global caches are not supported.
11294 @item --no-cache
11295 Don't cache the results.
11297 @item --force
11298 @itemx -f
11299 If a cache is used, consider it obsolete (but update it anyway).
11300 @end table
11302 @sp 1
11304 Because traces are so important to the GNU Build System,
11305 @command{autom4te} provides high level tracing features as compared to
11306 M4, and helps exploiting the cache:
11308 @table @option
11309 @item --trace=@var{macro}[:@var{format}]
11310 @itemx -t @var{macro}[:@var{format}]
11311 Trace the invocations of @var{macro} according to the @var{format}.
11312 Multiple @option{--trace} arguments can be used to list several macros.
11313 Multiple @option{--trace} arguments for a single macro are not
11314 cumulative; instead, you should just make @var{format} as long as
11315 needed.
11317 The @var{format} is a regular string, with newlines if desired, and
11318 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11319 use the following special escapes:
11321 @table @samp
11322 @item $$
11323 @c $$ restore font-lock
11324 The character @samp{$}.
11326 @item $f
11327 The file name from which @var{macro} is called.
11329 @item $l
11330 The line number from which @var{macro} is called.
11332 @item $d
11333 The depth of the @var{macro} call.  This is an M4 technical detail that
11334 you probably don't want to know about.
11336 @item $n
11337 The name of the @var{macro}.
11339 @item $@var{num}
11340 The @var{num}th argument of the call to @var{macro}.
11342 @item $@@
11343 @itemx $@var{sep}@@
11344 @itemx $@{@var{separator}@}@@
11345 All the arguments passed to @var{macro}, separated by the character
11346 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11347 argument is quoted, i.e., enclosed in a pair of square brackets.
11349 @item $*
11350 @itemx $@var{sep}*
11351 @itemx $@{@var{separator}@}*
11352 As above, but the arguments are not quoted.
11354 @item $%
11355 @itemx $@var{sep}%
11356 @itemx $@{@var{separator}@}%
11357 As above, but the arguments are not quoted, all new line characters in
11358 the arguments are smashed, and the default separator is @samp{:}.
11360 The escape @samp{$%} produces single-line trace outputs (unless you put
11361 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11362 not.
11363 @end table
11365 @xref{autoconf Invocation}, for examples of trace uses.
11367 @item --preselect=@var{macro}
11368 @itemx -p @var{macro}
11369 Cache the traces of @var{macro}, but do not enable traces.  This is
11370 especially important to save CPU cycles in the future.  For instance,
11371 when invoked, @command{autoconf} preselects all the macros that
11372 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11373 trace, so that running @command{m4} is not needed to trace them: the
11374 cache suffices.  This results in a huge speed-up.
11375 @end table
11377 @sp 1
11379 @cindex Autom4te Library
11380 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11381 libraries}.  They consists in a powerful yet extremely simple feature:
11382 sets of combined command line arguments:
11384 @table @option
11385 @item --language=@var{language}
11386 @itemx -l @var{language}
11387 Use the @var{language} Autom4te library.  Current languages include:
11389 @table @code
11390 @item M4sugar
11391 create M4sugar output.
11393 @item M4sh
11394 create M4sh executable shell scripts.
11396 @item Autotest
11397 create Autotest executable test suites.
11399 @item Autoconf-without-aclocal-m4
11400 create Autoconf executable configure scripts without
11401 reading @file{aclocal.m4}.
11403 @item Autoconf
11404 create Autoconf executable configure scripts.  This language inherits
11405 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11406 additionally reads @file{aclocal.m4}.
11407 @end table
11409 @item --prepend-include=@var{dir}
11410 @itemx -B @var{dir}
11411 Prepend directory @var{dir} to the search path.  This is used to include
11412 the language-specific files before any third-party macros.
11414 @end table
11416 @cindex @file{autom4te.cfg}
11417 As an example, if Autoconf is installed in its default location,
11418 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11419 strictly equivalent to the command:
11421 @example
11422 autom4te --prepend-include /usr/local/share/autoconf \
11423   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11424 @end example
11426 @noindent
11427 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11428 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11429 foo.m4}, i.e.:
11431 @example
11432 autom4te --prepend-include /usr/local/share/autoconf \
11433   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11434 @end example
11436 @noindent
11437 The definition of the languages is stored in @file{autom4te.cfg}.
11439 @node Customizing autom4te
11440 @subsection Customizing @command{autom4te}
11442 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11443 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11444 as found in the directory from which @command{autom4te} is run).  The
11445 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11446 then @file{./.autom4te.cfg}, and finally the command line arguments.
11448 In these text files, comments are introduced with @code{#}, and empty
11449 lines are ignored.  Customization is performed on a per-language basis,
11450 wrapped in between a @samp{begin-language: "@var{language}"},
11451 @samp{end-language: "@var{language}"} pair.
11453 Customizing a language stands for appending options (@pxref{autom4te
11454 Invocation}) to the current definition of the language.  Options, and
11455 more generally arguments, are introduced by @samp{args:
11456 @var{arguments}}.  You may use the traditional shell syntax to quote the
11457 @var{arguments}.
11459 As an example, to disable Autoconf caches (@file{autom4te.cache})
11460 globally, include the following lines in @file{~/.autom4te.cfg}:
11462 @verbatim
11463 ## ------------------ ##
11464 ## User Preferences.  ##
11465 ## ------------------ ##
11467 begin-language: "Autoconf-without-aclocal-m4"
11468 args: --no-cache
11469 end-language: "Autoconf-without-aclocal-m4"
11470 @end verbatim
11473 @node Programming in M4sugar
11474 @section Programming in M4sugar
11476 @cindex M4sugar
11477 M4 by itself provides only a small, but sufficient, set of all-purpose
11478 macros.  M4sugar introduces additional generic macros.  Its name was
11479 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11480 M4sugar''.
11482 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11483 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11484 define your own macros into these namespaces.
11486 @menu
11487 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11488 * Diagnostic Macros::           Diagnostic messages from M4sugar
11489 * Diversion support::           Diversions in M4sugar
11490 * Conditional constructs::      Conditions in M4
11491 * Looping constructs::          Iteration in M4
11492 * Evaluation Macros::           More quotation and evaluation control
11493 * Text processing Macros::      String manipulation in M4
11494 * Number processing Macros::    Arithmetic computation in M4
11495 * Set manipulation Macros::     Set manipulation in M4
11496 * Forbidden Patterns::          Catching unexpanded macros
11497 @end menu
11499 @node Redefined M4 Macros
11500 @subsection Redefined M4 Macros
11502 @msindex{builtin}
11503 @msindex{changecom}
11504 @msindex{changequote}
11505 @msindex{debugfile}
11506 @msindex{debugmode}
11507 @msindex{decr}
11508 @msindex{define}
11509 @msindex{divnum}
11510 @msindex{errprint}
11511 @msindex{esyscmd}
11512 @msindex{eval}
11513 @msindex{format}
11514 @msindex{ifdef}
11515 @msindex{incr}
11516 @msindex{index}
11517 @msindex{indir}
11518 @msindex{len}
11519 @msindex{pushdef}
11520 @msindex{shift}
11521 @msindex{substr}
11522 @msindex{syscmd}
11523 @msindex{sysval}
11524 @msindex{traceoff}
11525 @msindex{traceon}
11526 @msindex{translit}
11527 With a few exceptions, all the M4 native macros are moved in the
11528 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11529 @code{m4_define} etc.
11531 The list of macros unchanged from M4, except for their name, is:
11532 @itemize @minus
11533 @item m4_builtin
11534 @item m4_changecom
11535 @item m4_changequote
11536 @item m4_debugfile
11537 @item m4_debugmode
11538 @item m4_decr
11539 @item m4_define
11540 @item m4_divnum
11541 @item m4_errprint
11542 @item m4_esyscmd
11543 @item m4_eval
11544 @item m4_format
11545 @item m4_ifdef
11546 @item m4_incr
11547 @item m4_index
11548 @item m4_indir
11549 @item m4_len
11550 @item m4_pushdef
11551 @item m4_shift
11552 @item m4_substr
11553 @item m4_syscmd
11554 @item m4_sysval
11555 @item m4_traceoff
11556 @item m4_traceon
11557 @item m4_translit
11558 @end itemize
11560 Some M4 macros are redefined, and are slightly incompatible with their
11561 native equivalent.
11563 @defmac __file__
11564 @defmacx __line__
11565 @MSindex __file__
11566 @MSindex __line__
11567 All M4 macros starting with @samp{__} retain their original name: for
11568 example, no @code{m4__file__} is defined.
11569 @end defmac
11571 @defmac __oline__
11572 @MSindex __oline__
11573 This is not technically a macro, but a feature of Autom4te.  The
11574 sequence @code{__oline__} can be used similarly to the other m4sugar
11575 location macros, but rather than expanding to the location of the input
11576 file, it is translated to the line number where it appears in the output
11577 file after all other M4 expansions.
11578 @end defmac
11580 @defmac dnl
11581 @MSindex dnl
11582 This macro kept its original name: no @code{m4_dnl} is defined.
11583 @end defmac
11585 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11586 @msindex{bpatsubst}
11587 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11588 is kept for future versions of M4sugar, once GNU M4 2.0 is
11589 released and supports extended regular expression syntax.
11590 @end defmac
11592 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11593 @msindex{bregexp}
11594 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11595 is kept for future versions of M4sugar, once GNU M4 2.0 is
11596 released and supports extended regular expression syntax.
11597 @end defmac
11599 @defmac m4_copy (@var{source}, @var{dest})
11600 @defmacx m4_copy_force (@var{source}, @var{dest})
11601 @defmacx m4_rename (@var{source}, @var{dest})
11602 @defmacx m4_rename_force (@var{source}, @var{dest})
11603 @msindex{copy}
11604 @msindex{copy_force}
11605 @msindex{rename}
11606 @msindex{rename_force}
11607 These macros aren't directly builtins, but are closely related to
11608 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11609 @code{m4_rename} ensure that @var{dest} is undefined, while
11610 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11611 definition.  All four macros then proceed to copy the entire pushdef
11612 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11613 and @code{m4_copy_force} preserve the source (including in the special
11614 case where @var{source} is undefined), while @code{m4_rename} and
11615 @code{m4_rename_force} undefine the original macro name (making it an
11616 error to rename an undefined @var{source}).
11618 Note that attempting to invoke a renamed macro might not work, since the
11619 macro may have a dependence on helper macros accessed via composition of
11620 @samp{$0} but that were not also renamed; likewise, other macros may
11621 have a hard-coded dependence on @var{source} and could break if
11622 @var{source} has been deleted.  On the other hand, it is always safe to
11623 rename a macro to temporarily move it out of the way, then rename it
11624 back later to restore original semantics.
11625 @end defmac
11627 @defmac m4_defn (@var{macro}@dots{})
11628 @msindex{defn}
11629 This macro fails if @var{macro} is not defined, even when using older
11630 versions of M4 that did not warn.  See @code{m4_undefine}.
11631 Unfortunately, in order to support these older versions of M4, there are
11632 some situations involving unbalanced quotes where concatenating multiple
11633 macros together will work in newer M4 but not in m4sugar; use
11634 quadrigraphs to work around this.
11635 @end defmac
11637 @defmac m4_divert (@var{diversion})
11638 @msindex{divert}
11639 M4sugar relies heavily on diversions, so rather than behaving as a
11640 primitive, @code{m4_divert} behaves like:
11641 @example
11642 m4_divert_pop()m4_divert_push([@var{diversion}])
11643 @end example
11644 @noindent
11645 @xref{Diversion support}, for more details about the use of the
11646 diversion stack.  In particular, this implies that @var{diversion}
11647 should be a named diversion rather than a raw number.  But be aware that
11648 it is seldom necessary to explicitly change the diversion stack, and
11649 that when done incorrectly, it can lead to syntactically invalid
11650 scripts.
11651 @end defmac
11653 @defmac m4_dumpdef (@var{name}@dots{})
11654 @defmacx m4_dumpdefs (@var{name}@dots{})
11655 @msindex{dumpdef}
11656 @msindex{dumpdefs}
11657 @code{m4_dumpdef} is like the M4 builtin, except that this version
11658 requires at least one argument, output always goes to standard error
11659 rather than the current debug file, no sorting is done on multiple
11660 arguments, and an error is issued if any
11661 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11662 calls @code{m4_dumpdef} for all of the
11663 @code{m4_pushdef} stack of definitions, starting with the current, and
11664 silently does nothing if @var{name} is undefined.
11666 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11667 builtin is output as the empty string.  This behavior is rectified by
11668 using M4 1.6 or newer.  However, this behavior difference means that
11669 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11670 and never in the final published form of a macro.
11671 @end defmac
11673 @defmac m4_esyscmd_s (@var{command})
11674 @msindex{esyscmd_s}
11675 Like @code{m4_esyscmd}, this macro expands to the result of running
11676 @var{command} in a shell.  The difference is that any trailing newlines
11677 are removed, so that the output behaves more like shell command
11678 substitution.
11679 @end defmac
11681 @defmac m4_exit (@var{exit-status})
11682 @msindex{exit}
11683 This macro corresponds to @code{m4exit}.
11684 @end defmac
11686 @defmac m4_if (@var{comment})
11687 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11688 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11689   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11690 @msindex{if}
11691 This macro corresponds to @code{ifelse}.  @var{string-1} and
11692 @var{string-2} are compared literally, so usually one of the two
11693 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11694 conditional idioms.
11695 @end defmac
11697 @defmac m4_include (@var{file})
11698 @defmacx m4_sinclude (@var{file})
11699 @msindex{include}
11700 @msindex{sinclude}
11701 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11702 @end defmac
11704 @defmac m4_mkstemp (@var{template})
11705 @defmacx m4_maketemp (@var{template})
11706 @msindex{maketemp}
11707 @msindex{mkstemp}
11708 Posix requires @code{maketemp} to replace the trailing @samp{X}
11709 characters in @var{template} with the process id, without regards to the
11710 existence of a file by that name, but this a security hole.  When this
11711 was pointed out to the Posix folks, they agreed to invent a new macro
11712 @code{mkstemp} that always creates a uniquely named file, but not all
11713 versions of GNU M4 support the new macro.  In M4sugar,
11714 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11715 and both have the secure semantics regardless of which macro the
11716 underlying M4 provides.
11717 @end defmac
11719 @defmac m4_popdef (@var{macro}@dots{})
11720 @msindex{popdef}
11721 This macro fails if @var{macro} is not defined, even when using older
11722 versions of M4 that did not warn.  See @code{m4_undefine}.
11723 @end defmac
11725 @defmac m4_undefine (@var{macro}@dots{})
11726 @msindex{undefine}
11727 This macro fails if @var{macro} is not defined, even when using older
11728 versions of M4 that did not warn.  Use
11730 @example
11731 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11732 @end example
11734 @noindent
11735 if you are not sure whether @var{macro} is defined.
11736 @end defmac
11738 @defmac m4_undivert (@var{diversion}@dots{})
11739 @msindex{undivert}
11740 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11741 Also, since the M4sugar diversion stack prefers named
11742 diversions, the use of @code{m4_undivert} to include files is risky.
11743 @xref{Diversion support}, for more details about the use of the
11744 diversion stack.  But be aware that it is seldom necessary to explicitly
11745 change the diversion stack, and that when done incorrectly, it can lead
11746 to syntactically invalid scripts.
11747 @end defmac
11749 @defmac m4_wrap (@var{text})
11750 @defmacx m4_wrap_lifo (@var{text})
11751 @msindex{wrap}
11752 @msindex{wrap_lifo}
11753 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11754 multiple wrap calls to be reprocessed at EOF in the same order
11755 as the original calls (first-in, first-out).  GNU M4 versions
11756 through 1.4.10, however, reprocess them in reverse order (last-in,
11757 first-out).  Both orders are useful, therefore, you can rely on
11758 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11759 LIFO semantics, regardless of the underlying GNU M4 version.
11761 Unlike the GNU M4 builtin, these macros only recognize one
11762 argument, and avoid token pasting between consecutive invocations.  On
11763 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11764 work just as in the builtin.
11765 @end defmac
11768 @node Diagnostic Macros
11769 @subsection Diagnostic messages from M4sugar
11770 @cindex Messages, from @command{M4sugar}
11772 When macros statically diagnose abnormal situations, benign or fatal,
11773 they should report them using these macros.  For issuing dynamic issues,
11774 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11776 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11777 @msindex{assert}
11778 Assert that the arithmetic @var{expression} evaluates to non-zero.
11779 Otherwise, issue a fatal error, and exit @command{autom4te} with
11780 @var{exit-status}.
11781 @end defmac
11783 @defmac m4_errprintn (@var{message})
11784 @msindex{errprintn}
11785 Similar to the builtin @code{m4_errprint}, except that a newline is
11786 guaranteed after @var{message}.
11787 @end defmac
11789 @anchor{m4_fatal}
11790 @defmac m4_fatal (@var{message})
11791 @msindex{fatal}
11792 Report a severe error @var{message} prefixed with the current location,
11793 and have @command{autom4te} die.
11794 @end defmac
11796 @defmac m4_location
11797 @msindex{location}
11798 Useful as a prefix in a message line.  Short for:
11799 @example
11800 __file__:__line__
11801 @end example
11802 @end defmac
11804 @anchor{m4_warn}
11805 @defmac m4_warn (@var{category}, @var{message})
11806 @msindex{warn}
11807 Report @var{message} as a warning (or as an error if requested by the
11808 user) if warnings of the @var{category} are turned on.  If the message
11809 is emitted, it is prefixed with the current location, and followed by a
11810 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11811 current expansion.  You are encouraged to use standard categories, which
11812 currently include:
11814 @table @samp
11815 @item all
11816 messages that don't fall into one of the following categories.  Use of an
11817 empty @var{category} is equivalent.
11819 @item cross
11820 related to cross compilation issues.
11822 @item obsolete
11823 use of an obsolete construct.
11825 @item syntax
11826 dubious syntactic constructs, incorrectly ordered macro calls.
11827 @end table
11828 @end defmac
11831 @node Diversion support
11832 @subsection Diversion support
11834 M4sugar makes heavy use of diversions under the hood, because it is
11835 often the case that
11836 text that must appear early in the output is not discovered until late
11837 in the input.  Additionally, some of the topological sorting algorithms
11838 used in resolving macro dependencies use diversions.  However, most
11839 macros should not need to change diversions directly, but rather rely on
11840 higher-level M4sugar macros to manage diversions transparently.  If you
11841 change diversions improperly, you risk generating a syntactically
11842 invalid script, because an incorrect diversion will violate assumptions
11843 made by many macros about whether prerequisite text has been previously
11844 output.  In short, if you manually change the diversion, you should not
11845 expect any macros provided by the Autoconf package to work until you
11846 have restored the diversion stack back to its original state.
11848 In the rare case that it is necessary to write a macro that explicitly
11849 outputs text to a different diversion, it is important to be aware of an
11850 M4 limitation regarding diversions: text only goes to a diversion if it
11851 is not part of argument collection.  Therefore, any macro that changes
11852 the current diversion cannot be used as an unquoted argument to another
11853 macro, but must be expanded at the top level.  The macro
11854 @code{m4_expand} will diagnose any attempt to change diversions, since
11855 it is generally useful only as an argument to another macro.  The
11856 following example shows what happens when diversion manipulation is
11857 attempted within macro arguments:
11859 @example
11860 m4_do([normal text]
11861 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11862 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11863 @result{}normal text
11864 @result{}unwanted
11865 @end example
11867 @noindent
11868 Notice that the unquoted text @code{unwanted} is output, even though it
11869 was processed while the current diversion was @code{KILL}, because it
11870 was collected as part of the argument to @code{m4_do}.  However, the
11871 text @code{discarded} disappeared as desired, because the diversion
11872 changes were single-quoted, and were not expanded until the top-level
11873 rescan of the output of @code{m4_do}.
11875 To make diversion management easier, M4sugar uses the concept of named
11876 diversions.  Rather than using diversion numbers directly, it is nicer
11877 to associate a name with each diversion.  The diversion number associated
11878 with a particular diversion name is an implementation detail, and a
11879 syntax warning is issued if a diversion number is used instead of a
11880 name.  In general, you should not output text
11881 to a named diversion until after calling the appropriate initialization
11882 routine for your language (@code{m4_init}, @code{AS_INIT},
11883 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11884 below.
11886 M4sugar defines two named diversions.
11887 @table @code
11888 @item KILL
11889 Text written to this diversion is discarded.  This is the default
11890 diversion once M4sugar is initialized.
11891 @item GROW
11892 This diversion is used behind the scenes by topological sorting macros,
11893 such as @code{AC_REQUIRE}.
11894 @end table
11896 M4sh adds several more named diversions.
11897 @table @code
11898 @item BINSH
11899 This diversion is reserved for the @samp{#!} interpreter line.
11900 @item HEADER-REVISION
11901 This diversion holds text from @code{AC_REVISION}.
11902 @item HEADER-COMMENT
11903 This diversion holds comments about the purpose of a file.
11904 @item HEADER-COPYRIGHT
11905 This diversion is managed by @code{AC_COPYRIGHT}.
11906 @item M4SH-SANITIZE
11907 This diversion contains M4sh sanitization code, used to ensure M4sh is
11908 executing in a reasonable shell environment.
11909 @item M4SH-INIT
11910 This diversion contains M4sh initialization code, initializing variables
11911 that are required by other M4sh macros.
11912 @item BODY
11913 This diversion contains the body of the shell code, and is the default
11914 diversion once M4sh is initialized.
11915 @end table
11917 Autotest inherits diversions from M4sh, and changes the default
11918 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11919 more named diversions, with the following subset designed for developer
11920 use.
11921 @table @code
11922 @item PREPARE_TESTS
11923 This diversion contains initialization sequences which are executed
11924 after @file{atconfig} and @file{atlocal}, and after all command line
11925 arguments have been parsed, but prior to running any tests.  It can be
11926 used to set up state that is required across all tests.  This diversion
11927 will work even before @code{AT_INIT}.
11928 @end table
11930 Autoconf inherits diversions from M4sh, and adds the following named
11931 diversions which developers can utilize.
11932 @table @code
11933 @item DEFAULTS
11934 This diversion contains shell variable assignments to set defaults that
11935 must be in place before arguments are parsed.  This diversion is placed
11936 early enough in @file{configure} that it is unsafe to expand any
11937 autoconf macros into this diversion.
11938 @item HELP_ENABLE
11939 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11940 diversion will be included as part of a quoted here-doc providing all of
11941 the @option{--help} output of @file{configure} related to options
11942 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11943 @item INIT_PREPARE
11944 This diversion occurs after all command line options have been parsed,
11945 but prior to the main body of the @file{configure} script.  This
11946 diversion is the last chance to insert shell code such as variable
11947 assignments or shell function declarations that will used by the
11948 expansion of other macros.
11949 @end table
11951 For now, the remaining named diversions of Autoconf, Autoheader, and
11952 Autotest are not documented.  In other words,
11953 intentionally outputting text into an undocumented diversion is subject
11954 to breakage in a future release of Autoconf.
11956 @defmac m4_cleardivert (@var{diversion}@dots{})
11957 @msindex{cleardivert}
11958 Permanently discard any text that has been diverted into
11959 @var{diversion}.
11960 @end defmac
11962 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11963 @msindex{divert_once}
11964 Similar to @code{m4_divert_text}, except that @var{content} is only
11965 output to @var{diversion} if this is the first time that
11966 @code{m4_divert_once} has been called with its particular arguments.
11967 @end defmac
11969 @defmac m4_divert_pop (@ovar{diversion})
11970 @msindex{divert_pop}
11971 If provided, check that the current diversion is indeed @var{diversion}.
11972 Then change to the diversion located earlier on the stack, giving an
11973 error if an attempt is made to pop beyond the initial m4sugar diversion
11974 of @code{KILL}.
11975 @end defmac
11977 @defmac m4_divert_push (@var{diversion})
11978 @msindex{divert_push}
11979 Remember the former diversion on the diversion stack, and output
11980 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11981 stack, and issues an error if there is not a matching pop for every
11982 push.
11983 @end defmac
11985 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11986 @msindex{divert_text}
11987 Output @var{content} and a newline into @var{diversion}, without
11988 affecting the current diversion.  Shorthand for:
11989 @example
11990 m4_divert_push([@var{diversion}])@var{content}
11991 m4_divert_pop([@var{diversion}])dnl
11992 @end example
11994 One use of @code{m4_divert_text} is to develop two related macros, where
11995 macro @samp{MY_A} does the work, but adjusts what work is performed
11996 based on whether the optional macro @samp{MY_B} has also been expanded.
11997 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11998 require that @samp{MY_B} occurs first, if it occurs at all.  But this
11999 imposes an ordering restriction on the user; it would be nicer if macros
12000 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12001 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12002 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12003 expanded.
12005 @example
12006 AC_DEFUN([MY_A],
12007 [# various actions
12008 if test -n "$b_was_used"; then
12009   # extra action
12010 fi])
12011 AC_DEFUN([MY_B],
12012 [AC_REQUIRE([MY_A])dnl
12013 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12014 @end example
12016 @end defmac
12018 @defmac m4_init
12019 @msindex{init}
12020 Initialize the M4sugar environment, setting up the default named
12021 diversion to be @code{KILL}.
12022 @end defmac
12024 @node Conditional constructs
12025 @subsection Conditional constructs
12027 The following macros provide additional conditional constructs as
12028 convenience wrappers around @code{m4_if}.
12030 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12031   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12032 @msindex{bmatch}
12033 The string @var{string} is repeatedly compared against a series of
12034 @var{regex} arguments; if a match is found, the expansion is the
12035 corresponding @var{value}, otherwise, the macro moves on to the next
12036 @var{regex}.  If no @var{regex} match, then the result is the optional
12037 @var{default}, or nothing.
12038 @end defmac
12040 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12041   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12042 @msindex{bpatsubsts}
12043 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12044 as if by:
12045 @example
12046 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12047 @end example
12049 @noindent
12050 The result of the substitution is then passed through the next set of
12051 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12052 deletion of any matched portions in the current string.  Note that this
12053 macro over-quotes @var{string}; this behavior is intentional, so that
12054 the result of each step of the recursion remains as a quoted string.
12055 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12056 will line up with the extra quotations, and not the characters of the
12057 original string.  The overquoting is removed after the final
12058 substitution.
12059 @end defmac
12061 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12062   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12063 @msindex{case}
12064 Test @var{string} against multiple @var{value} possibilities, resulting
12065 in the first @var{if-value} for a match, or in the optional
12066 @var{default}.  This is shorthand for:
12067 @example
12068 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12069       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12070       [@var{default}])
12071 @end example
12072 @end defmac
12074 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12075   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12076 @msindex{cond}
12077 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12078 except that each @var{test} is expanded only when it is encountered.
12079 This is useful for short-circuiting expensive tests; while @code{m4_if}
12080 requires all its strings to be expanded up front before doing
12081 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12082 tests have failed.
12084 For an example, these two sequences give the same result, but in the
12085 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12086 version only expands @code{m4_index} once, instead of five times, for
12087 faster computation if this is a common case for @samp{$1}.  Notice that
12088 every third argument is unquoted for @code{m4_if}, and quoted for
12089 @code{m4_cond}:
12091 @example
12092 m4_if(m4_index([$1], [\]), [-1], [$2],
12093       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12094       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12095       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12096       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12097       [$2])
12098 m4_cond([m4_index([$1], [\])], [-1], [$2],
12099         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12100         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12101         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12102         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12103         [$2])
12104 @end example
12105 @end defmac
12107 @defmac m4_default (@var{expr-1}, @var{expr-2})
12108 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12109 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12110 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12111 @msindex{default}
12112 @msindex{default_quoted}
12113 @msindex{default_nblank}
12114 @msindex{default_nblank_quoted}
12115 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12116 @code{m4_default} expands the result, while @code{m4_default_quoted}
12117 does not.  Useful for providing a fixed default if the expression that
12118 results in @var{expr-1} would otherwise be empty.  The difference
12119 between @code{m4_default} and @code{m4_default_nblank} is whether an
12120 argument consisting of just blanks (space, tab, newline) is
12121 significant.  When using the expanding versions, note that an argument
12122 may contain text but still expand to an empty string.
12124 @example
12125 m4_define([active], [ACTIVE])dnl
12126 m4_define([empty], [])dnl
12127 m4_define([demo1], [m4_default([$1], [$2])])dnl
12128 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12129 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12130 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12131 demo1([active], [default])
12132 @result{}ACTIVE
12133 demo1([], [active])
12134 @result{}ACTIVE
12135 demo1([empty], [text])
12136 @result{}
12137 -demo1([ ], [active])-
12138 @result{}- -
12139 demo2([active], [default])
12140 @result{}active
12141 demo2([], [active])
12142 @result{}active
12143 demo2([empty], [text])
12144 @result{}empty
12145 -demo2([ ], [active])-
12146 @result{}- -
12147 demo3([active], [default])
12148 @result{}ACTIVE
12149 demo3([], [active])
12150 @result{}ACTIVE
12151 demo3([empty], [text])
12152 @result{}
12153 -demo3([ ], [active])-
12154 @result{}-ACTIVE-
12155 demo4([active], [default])
12156 @result{}active
12157 demo4([], [active])
12158 @result{}active
12159 demo4([empty], [text])
12160 @result{}empty
12161 -demo4([ ], [active])-
12162 @result{}-active-
12163 @end example
12164 @end defmac
12166 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12167 @msindex{define_default}
12168 If @var{macro} does not already have a definition, then define it to
12169 @var{default-definition}.
12170 @end defmac
12172 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12173 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12174 @msindex{ifblank}
12175 @msindex{ifnblank}
12176 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12177 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12178 variants exist, in order to make it easier to select the correct logical
12179 sense when using only two parameters.  Note that this is more efficient
12180 than the equivalent behavior of:
12181 @example
12182 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12183 @end example
12184 @end defmac
12186 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12187 @msindex{ifndef}
12188 This is shorthand for:
12189 @example
12190 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12191 @end example
12192 @end defmac
12194 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12195 @msindex{ifset}
12196 If @var{macro} is undefined, or is defined as the empty string, expand
12197 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12198 @example
12199 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12200 @end example
12201 @noindent
12202 except that it is not an error if @var{macro} is undefined.
12203 @end defmac
12205 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12206 @msindex{ifval}
12207 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12208 @var{if-false}.  This is shorthand for:
12209 @example
12210 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12211 @end example
12212 @end defmac
12214 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12215 @msindex{ifvaln}
12216 Similar to @code{m4_ifval}, except guarantee that a newline is present
12217 after any non-empty expansion.  Often followed by @code{dnl}.
12218 @end defmac
12220 @defmac m4_n (@var{text})
12221 @msindex{n}
12222 Expand to @var{text}, and add a newline if @var{text} is not empty.
12223 Often followed by @code{dnl}.
12224 @end defmac
12227 @node Looping constructs
12228 @subsection Looping constructs
12230 The following macros are useful in implementing recursive algorithms in
12231 M4, including loop operations.  An M4 list is formed by quoting a list
12232 of quoted elements; generally the lists are comma-separated, although
12233 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12234 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12235 It is common to see lists with unquoted elements when those elements are
12236 not likely to be macro names, as in @samp{[fputc_unlocked,
12237 fgetc_unlocked]}.
12239 Although not generally recommended, it is possible for quoted lists to
12240 have side effects; all side effects are expanded only once, and prior to
12241 visiting any list element.  On the other hand, the fact that unquoted
12242 macros are expanded exactly once means that macros without side effects
12243 can be used to generate lists.  For example,
12245 @example
12246 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12247 @error{}hi
12248 @result{}123
12249 m4_define([list], [[1], [2], [3]])
12250 @result{}
12251 m4_foreach([i], [list], [i])
12252 @result{}123
12253 @end example
12255 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12256 @msindex{argn}
12257 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12258 If there are too few arguments, the empty string is used.  For any
12259 @var{n} besides 1, this is more efficient than the similar
12260 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12261 @end defmac
12263 @defmac m4_car (@var{arg}@dots{})
12264 @msindex{car}
12265 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12266 to recursively iterate
12267 through a list.  Generally, when using quoted lists of quoted elements,
12268 @code{m4_car} should be called without any extra quotes.
12269 @end defmac
12271 @defmac m4_cdr (@var{arg}@dots{})
12272 @msindex{cdr}
12273 Expands to a quoted list of all but the first @var{arg}, or the empty
12274 string if there was only one argument.  Generally, when using quoted
12275 lists of quoted elements, @code{m4_cdr} should be called without any
12276 extra quotes.
12278 For example, this is a simple implementation of @code{m4_map}; note how
12279 each iteration checks for the end of recursion, then merely applies the
12280 first argument to the first element of the list, then repeats with the
12281 rest of the list.  (The actual implementation in M4sugar is a bit more
12282 involved, to gain some speed and share code with @code{m4_map_sep}, and
12283 also to avoid expanding side effects in @samp{$2} twice).
12284 @example
12285 m4_define([m4_map], [m4_ifval([$2],
12286   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12287 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12288 @result{} 1 2 a
12289 @end example
12290 @end defmac
12292 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12293   @var{expression})
12294 @msindex{for}
12295 Loop over the numeric values between @var{first} and @var{last}
12296 including bounds by increments of @var{step}.  For each iteration,
12297 expand @var{expression} with the numeric value assigned to @var{var}.
12298 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12299 on the order of the limits.  If given, @var{step} has to match this
12300 order.  The number of iterations is determined independently from
12301 definition of @var{var}; iteration cannot be short-circuited or
12302 lengthened by modifying @var{var} from within @var{expression}.
12303 @end defmac
12305 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12306 @msindex{foreach}
12307 Loop over the comma-separated M4 list @var{list}, assigning each value
12308 to @var{var}, and expand @var{expression}.  The following example
12309 outputs two lines:
12311 @example
12312 m4_foreach([myvar], [[foo], [bar, baz]],
12313            [echo myvar
12314 ])dnl
12315 @result{}echo foo
12316 @result{}echo bar, baz
12317 @end example
12319 Note that for some forms of @var{expression}, it may be faster to use
12320 @code{m4_map_args}.
12321 @end defmac
12323 @anchor{m4_foreach_w}
12324 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12325 @msindex{foreach_w}
12326 Loop over the white-space-separated list @var{list}, assigning each value
12327 to @var{var}, and expand @var{expression}.  If @var{var} is only
12328 referenced once in @var{expression}, it is more efficient to use
12329 @code{m4_map_args_w}.
12331 The deprecated macro @code{AC_FOREACH} is an alias of
12332 @code{m4_foreach_w}.
12333 @end defmac
12335 @defmac m4_map (@var{macro}, @var{list})
12336 @defmacx m4_mapall (@var{macro}, @var{list})
12337 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12338 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12339 @msindex{map}
12340 @msindex{mapall}
12341 @msindex{map_sep}
12342 @msindex{mapall_sep}
12343 Loop over the comma separated quoted list of argument descriptions in
12344 @var{list}, and invoke @var{macro} with the arguments.  An argument
12345 description is in turn a comma-separated quoted list of quoted elements,
12346 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12347 @code{m4_map_sep} ignore empty argument descriptions, while
12348 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12349 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12350 additionally expand @var{separator} between invocations of @var{macro}.
12352 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12353 separating output with commas, this means that the map result can be
12354 used as a series of arguments, by using a single-quoted comma as
12355 @var{separator}, or as a single string, by using a double-quoted comma.
12357 @example
12358 m4_map([m4_count], [])
12359 @result{}
12360 m4_map([ m4_count], [[],
12361                      [[1]],
12362                      [[1], [2]]])
12363 @result{} 1 2
12364 m4_mapall([ m4_count], [[],
12365                         [[1]],
12366                         [[1], [2]]])
12367 @result{} 0 1 2
12368 m4_map_sep([m4_eval], [,], [[[1+2]],
12369                             [[10], [16]]])
12370 @result{}3,a
12371 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12372 @result{}a,b
12373 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12374 @result{}2
12375 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12376 @result{}a,b
12377 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12378 @result{}1
12379 @end example
12380 @end defmac
12382 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12383 @msindex{map_args}
12384 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12385 argument.  In the following example, three solutions are presented with
12386 the same expansion; the solution using @code{m4_map_args} is the most
12387 efficient.
12388 @example
12389 m4_define([active], [ACTIVE])dnl
12390 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12391 @result{} plain active
12392 m4_map([ m4_echo], [[[plain]], [[active]]])
12393 @result{} plain active
12394 m4_map_args([ m4_echo], [plain], [active])
12395 @result{} plain active
12396 @end example
12398 In cases where it is useful to operate on additional parameters besides
12399 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12400 to supply the argument currying necessary to generate the desired
12401 argument list.  In the following example, @code{list_add_n} is more
12402 efficient than @code{list_add_x}.  On the other hand, using
12403 @code{m4_map_args_sep} can be even more efficient.
12405 @example
12406 m4_define([list], [[1], [2], [3]])dnl
12407 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12408 dnl list_add_n(N, ARG...)
12409 dnl Output a list consisting of each ARG added to N
12410 m4_define([list_add_n],
12411 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12412 list_add_n([1], list)
12413 @result{}2,3,4
12414 list_add_n([2], list)
12415 @result{}3,4,5
12416 m4_define([list_add_x],
12417 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12418   [,add([$1],m4_defn([var]))]))])dnl
12419 list_add_x([1], list)
12420 @result{}2,3,4
12421 @end example
12422 @end defmac
12424 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12425   @var{arg}@dots{})
12426 @msindex{map_args_pair}
12427 For every pair of arguments @var{arg}, invoke @var{macro} with two
12428 arguments.  If there is an odd number of arguments, invoke
12429 @var{macro-end}, which defaults to @var{macro}, with the remaining
12430 argument.
12432 @example
12433 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12434 @result{}, 2, 1, 3
12435 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12436 @result{}, 2, 1, [3]
12437 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12438 @result{}, 2, 1, 4, 3
12439 @end example
12440 @end defmac
12442 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12443 @msindex{map_args_sep}
12444 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12445 argument, additionally expanding @var{sep} between arguments.  One
12446 common use of this macro is constructing a macro call, where the opening
12447 and closing parentheses are split between @var{pre} and @var{post}; in
12448 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12449 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12450 macro provides the most efficient means for iterating over an arbitrary
12451 list of arguments, particularly when repeatedly constructing a macro
12452 call with more arguments than @var{arg}.
12453 @end defmac
12455 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12456 @msindex{map_args_w}
12457 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12458 the whitespace-separated @var{string}, additionally expanding @var{sep}
12459 between words.  This macro provides the most efficient means for
12460 iterating over a whitespace-separated string.  In particular,
12461 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12462 efficient than @code{m4_foreach_w([var], [@var{string}],
12463 [@var{action}(m4_defn([var]))])}.
12464 @end defmac
12466 @defmac m4_shiftn (@var{count}, @dots{})
12467 @defmacx m4_shift2 (@dots{})
12468 @defmacx m4_shift3 (@dots{})
12469 @msindex{shift2}
12470 @msindex{shift3}
12471 @msindex{shiftn}
12472 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12473 along with validation that enough arguments were passed in to match the
12474 shift count, and that the count is positive.  @code{m4_shift2} and
12475 @code{m4_shift3} are specializations
12476 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12477 for two and three shifts, respectively.
12478 @end defmac
12480 @defmac m4_stack_foreach (@var{macro}, @var{action})
12481 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12482 @msindex{stack_foreach}
12483 @msindex{stack_foreach_lifo}
12484 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12485 @var{action} with the single argument of a definition of @var{macro}.
12486 @code{m4_stack_foreach} starts with the oldest definition, while
12487 @code{m4_stack_foreach_lifo} starts with the current definition.
12488 @var{action} should not push or pop definitions of @var{macro}, nor is
12489 there any guarantee that the current definition of @var{macro} matches
12490 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12491 can be used if @var{action} needs more than one argument, although in
12492 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12494 Due to technical limitations, there are a few low-level m4sugar
12495 functions, such as @code{m4_pushdef}, that cannot be used as the
12496 @var{macro} argument.
12498 @example
12499 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12500 m4_stack_foreach([a], [ m4_incr])
12501 @result{} 2 3
12502 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12503 @result{} cd bcd
12504 @end example
12505 @end defmac
12507 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12508 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12509   @ovar{sep})
12510 @msindex{stack_foreach_sep}
12511 @msindex{stack_foreach_sep_lifo}
12512 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12513 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12514 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12515 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12516 the current definition first.  This macro provides the most efficient
12517 means for iterating over a pushdef stack.  In particular,
12518 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12519 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12520 @end defmac
12522 @node Evaluation Macros
12523 @subsection Evaluation Macros
12525 The following macros give some control over the order of the evaluation
12526 by adding or removing levels of quotes.
12528 @defmac m4_apply (@var{macro}, @var{list})
12529 @msindex{apply}
12530 Apply the elements of the quoted, comma-separated @var{list} as the
12531 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12532 without arguments.  Note the difference between @code{m4_indir}, which
12533 expects its first argument to be a macro name but can use names that are
12534 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12535 other text, but must end in a valid macro name.
12536 @example
12537 m4_apply([m4_count], [])
12538 @result{}0
12539 m4_apply([m4_count], [[]])
12540 @result{}1
12541 m4_apply([m4_count], [[1], [2]])
12542 @result{}2
12543 m4_apply([m4_join], [[|], [1], [2]])
12544 @result{}1|2
12545 @end example
12546 @end defmac
12548 @defmac m4_count (@var{arg}, @dots{})
12549 @msindex{count}
12550 This macro returns the decimal count of the number of arguments it was
12551 passed.
12552 @end defmac
12554 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12555 @msindex{curry}
12556 This macro performs argument currying.  The expansion of this macro is
12557 another macro name that expects exactly one argument; that argument is
12558 then appended to the @var{arg} list, and then @var{macro} is expanded
12559 with the resulting argument list.
12561 @example
12562 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12563 @result{}3, 2, 1
12564 @end example
12566 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12567 pass the definition of a builtin macro as the argument to the output of
12568 @code{m4_curry}; the empty string is used instead of the builtin token.
12569 This behavior is rectified by using M4 1.6 or newer.
12570 @end defmac
12572 @defmac m4_do (@var{arg}, @dots{})
12573 @msindex{do}
12574 This macro loops over its arguments and expands each @var{arg} in
12575 sequence.  Its main use is for readability; it allows the use of
12576 indentation and fewer @code{dnl} to result in the same expansion.  This
12577 macro guarantees that no expansion will be concatenated with subsequent
12578 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12579 @var{arg@dots{}}))}.
12581 @example
12582 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12583 m4_do([a],[b])c
12584 @result{}abc
12585 m4_unquote(m4_join([],[a],[b]))c
12586 @result{}3
12587 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12588 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12589 m4_do([a],[b])c
12590 @result{}ABC
12591 m4_unquote(m4_join([],[a],[b]))c
12592 @result{}3
12593 @end example
12594 @end defmac
12596 @defmac m4_dquote (@var{arg}, @dots{})
12597 @msindex{dquote}
12598 Return the arguments as a quoted list of quoted arguments.
12599 Conveniently, if there is just one @var{arg}, this effectively adds a
12600 level of quoting.
12601 @end defmac
12603 @defmac m4_dquote_elt (@var{arg}, @dots{})
12604 @msindex{dquote_elt}
12605 Return the arguments as a series of double-quoted arguments.  Whereas
12606 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12607 as many arguments as it was passed.
12608 @end defmac
12610 @defmac m4_echo (@var{arg}, @dots{})
12611 @msindex{echo}
12612 Return the arguments, with the same level of quoting.  Other than
12613 discarding whitespace after unquoted commas, this macro is a no-op.
12614 @end defmac
12616 @defmac m4_expand (@var{arg})
12617 @msindex{expand}
12618 Return the expansion of @var{arg} as a quoted string.  Whereas
12619 @code{m4_quote} is designed to collect expanded text into a single
12620 argument, @code{m4_expand} is designed to perform one level of expansion
12621 on quoted text.  One distinction is in the treatment of whitespace
12622 following a comma in the original @var{arg}.  Any time multiple
12623 arguments are collected into one with @code{m4_quote}, the M4 argument
12624 collection rules discard the whitespace.  However, with @code{m4_expand},
12625 whitespace is preserved, even after the expansion of macros contained in
12626 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12627 would involve an unterminated comment, whereas expanding that same text
12628 as the argument to @code{m4_quote} runs into difficulty in finding the
12629 end of the argument.  Since manipulating diversions during argument
12630 collection is inherently unsafe, @code{m4_expand} issues an error if
12631 @var{arg} attempts to change the current diversion (@pxref{Diversion
12632 support}).
12634 @example
12635 m4_define([active], [ACT, IVE])dnl
12636 m4_define([active2], [[ACT, IVE]])dnl
12637 m4_quote(active, active)
12638 @result{}ACT,IVE,ACT,IVE
12639 m4_expand([active, active])
12640 @result{}ACT, IVE, ACT, IVE
12641 m4_quote(active2, active2)
12642 @result{}ACT, IVE,ACT, IVE
12643 m4_expand([active2, active2])
12644 @result{}ACT, IVE, ACT, IVE
12645 m4_expand([# m4_echo])
12646 @result{}# m4_echo
12647 m4_quote(# m4_echo)
12649 @result{}# m4_echo)
12650 @result{}
12651 @end example
12653 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12654 literal unbalanced quotes, but that quadrigraphs can be used when
12655 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12656 be supplied with double quoting or a quadrigraph.
12658 @example
12659 m4_define([pattern], [[!@@<:@@]])dnl
12660 m4_define([bar], [BAR])dnl
12661 m4_expand([case $foo in
12662   m4_defn([pattern])@@:@}@@ bar ;;
12663   *[)] blah ;;
12664 esac])
12665 @result{}case $foo in
12666 @result{}  [![]) BAR ;;
12667 @result{}  *) blah ;;
12668 @result{}esac
12669 @end example
12670 @end defmac
12672 @defmac m4_ignore (@dots{})
12673 @msindex{ignore}
12674 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12675 ignoring all of its arguments.  By itself, this isn't very useful.
12676 However, it can be used to conditionally ignore an arbitrary number of
12677 arguments, by deciding which macro name to apply to a list of arguments.
12678 @example
12679 dnl foo outputs a message only if [debug] is defined.
12680 m4_define([foo],
12681 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12682 @end example
12684 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12685 serve the same purpose, although it is less readable.
12686 @end defmac
12688 @defmac m4_make_list (@var{arg}, @dots{})
12689 @msindex{make_list}
12690 This macro exists to aid debugging of M4sugar algorithms.  Its net
12691 effect is similar to @code{m4_dquote}---it produces a quoted list of
12692 quoted arguments, for each @var{arg}.  The difference is that this
12693 version uses a comma-newline separator instead of just comma, to improve
12694 readability of the list; with the result that it is less efficient than
12695 @code{m4_dquote}.
12696 @example
12697 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12698 m4_dquote(zero, [one], [[two]])
12699 @result{}[0],[one],[[two]]
12700 m4_make_list(zero, [one], [[two]])
12701 @result{}[0],
12702 @result{}[one],
12703 @result{}[[two]]
12704 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12705 @result{} 0 1 two
12706 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12707 @result{} 0 1 two
12708 @end example
12709 @end defmac
12711 @c m4_noquote is too dangerous to document - it invokes macros that
12712 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12713 @c user should generally prefer m4_unquote instead.
12715 @defmac m4_quote (@var{arg}, @dots{})
12716 @msindex{quote}
12717 Return the arguments as a single entity, i.e., wrap them into a pair of
12718 quotes.  This effectively collapses multiple arguments into one,
12719 although it loses whitespace after unquoted commas in the process.
12720 @end defmac
12722 @defmac m4_reverse (@var{arg}, @dots{})
12723 @msindex{reverse}
12724 Outputs each argument with the same level of quoting, but in reverse
12725 order, and with space following each comma for readability.
12727 @example
12728 m4_define([active], [ACT,IVE])
12729 @result{}
12730 m4_reverse(active, [active])
12731 @result{}active, IVE, ACT
12732 @end example
12733 @end defmac
12735 @defmac m4_unquote (@var{arg}, @dots{})
12736 @msindex{unquote}
12737 This macro was introduced in Autoconf 2.62.  Expand each argument,
12738 separated by commas.  For a single @var{arg}, this effectively removes a
12739 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12740 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12741 this results in an unquoted list of expansions.  This is commonly used
12742 with @code{m4_split}, in order to convert a single quoted list into a
12743 series of quoted elements.
12744 @end defmac
12746 The following example aims at emphasizing the difference between several
12747 scenarios: not using these macros, using @code{m4_defn}, using
12748 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12750 @example
12751 $ @kbd{cat example.m4}
12752 dnl Overquote, so that quotes are visible.
12753 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12754 m4_define([a], [A])
12755 m4_define([mkargs], [1, 2[,] 3])
12756 m4_define([arg1], [[$1]])
12757 m4_divert([0])dnl
12758 show(a, b)
12759 show([a, b])
12760 show(m4_quote(a, b))
12761 show(m4_dquote(a, b))
12762 show(m4_expand([a, b]))
12764 arg1(mkargs)
12765 arg1([mkargs])
12766 arg1(m4_defn([mkargs]))
12767 arg1(m4_quote(mkargs))
12768 arg1(m4_dquote(mkargs))
12769 arg1(m4_expand([mkargs]))
12770 $ @kbd{autom4te -l m4sugar example.m4}
12771 $1 = A, $@@ = [A],[b]
12772 $1 = a, b, $@@ = [a, b]
12773 $1 = A,b, $@@ = [A,b]
12774 $1 = [A],[b], $@@ = [[A],[b]]
12775 $1 = A, b, $@@ = [A, b]
12778 mkargs
12779 1, 2[,] 3
12780 1,2, 3
12781 [1],[2, 3]
12782 1, 2, 3
12783 @end example
12786 @node Text processing Macros
12787 @subsection String manipulation in M4
12789 The following macros may be used to manipulate strings in M4.  Many of
12790 the macros in this section intentionally result in quoted strings as
12791 output, rather than subjecting the arguments to further expansions.  As
12792 a result, if you are manipulating text that contains active M4
12793 characters, the arguments are passed with single quoting rather than
12794 double.
12796 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12797 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12798   @ovar{if-uniq}, @ovar{if-duplicate})
12799 @msindex{append}
12800 @msindex{append_uniq}
12801 Redefine @var{macro-name} to its former contents with @var{separator}
12802 and @var{string} added at the end.  If @var{macro-name} was undefined
12803 before (but not if it was defined but empty), then no @var{separator} is
12804 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12805 are expanded during this macro; instead, they are expanded when
12806 @var{macro-name} is invoked.
12808 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12809 to grow strings without duplicating substrings.  Additionally,
12810 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12811 @var{if-uniq} is expanded if @var{string} was appended, and
12812 @var{if-duplicate} is expanded if @var{string} was already present.
12813 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12814 occurs within @var{string}, since that can lead to duplicates.
12816 Note that @code{m4_append} can scale linearly in the length of the final
12817 string, depending on the quality of the underlying M4 implementation,
12818 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12819 If an algorithm can tolerate duplicates in the final string, use the
12820 former for speed.  If duplicates must be avoided, consider using
12821 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12823 @example
12824 m4_define([active], [ACTIVE])dnl
12825 m4_append([sentence], [This is an])dnl
12826 m4_append([sentence], [ active ])dnl
12827 m4_append([sentence], [symbol.])dnl
12828 sentence
12829 @result{}This is an ACTIVE symbol.
12830 m4_undefine([active])dnl
12831 @result{}This is an active symbol.
12832 m4_append_uniq([list], [one], [, ], [new], [existing])
12833 @result{}new
12834 m4_append_uniq([list], [one], [, ], [new], [existing])
12835 @result{}existing
12836 m4_append_uniq([list], [two], [, ], [new], [existing])
12837 @result{}new
12838 m4_append_uniq([list], [three], [, ], [new], [existing])
12839 @result{}new
12840 m4_append_uniq([list], [two], [, ], [new], [existing])
12841 @result{}existing
12842 list
12843 @result{}one, two, three
12844 m4_dquote(list)
12845 @result{}[one],[two],[three]
12846 m4_append([list2], [one], [[, ]])dnl
12847 m4_append_uniq([list2], [two], [[, ]])dnl
12848 m4_append([list2], [three], [[, ]])dnl
12849 list2
12850 @result{}one, two, three
12851 m4_dquote(list2)
12852 @result{}[one, two, three]
12853 @end example
12854 @end defmac
12856 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12857 @msindex{append_uniq_w}
12858 This macro was introduced in Autoconf 2.62.  It is similar to
12859 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12860 separated list of words to append, and only appends unique words.
12861 @var{macro-name} is updated with a single space between new words.
12862 @example
12863 m4_append_uniq_w([numbers], [1 1 2])dnl
12864 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12865 numbers
12866 @result{}1 2 3
12867 @end example
12868 @end defmac
12870 @defmac m4_chomp (@var{string})
12871 @defmacx m4_chomp_all (@var{string})
12872 @msindex{chomp}
12873 @msindex{chomp_all}
12874 Output @var{string} in quotes, but without a trailing newline.  The
12875 macro @code{m4_chomp} is slightly faster, and removes at most one
12876 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12877 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12878 and backslash does not influence the result.
12879 @end defmac
12881 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12882   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12883 @msindex{combine}
12884 This macro produces a quoted string containing the pairwise combination
12885 of every element of the quoted, comma-separated @var{prefix-list}, and
12886 every element from the @var{suffix} arguments.  Each pairwise
12887 combination is joined with @var{infix} in the middle, and successive
12888 pairs are joined by @var{separator}.  No expansion occurs on any of the
12889 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12890 list is empty, but the lists can contain empty elements.
12891 @example
12892 m4_define([a], [oops])dnl
12893 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12894 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12895 m4_combine([, ], [[a], [b]], [-])
12896 @result{}
12897 m4_combine([, ], [[a], [b]], [-], [])
12898 @result{}a-, b-
12899 m4_combine([, ], [], [-], [1], [2])
12900 @result{}
12901 m4_combine([, ], [[]], [-], [1], [2])
12902 @result{}-1, -2
12903 @end example
12904 @end defmac
12906 @defmac m4_escape (@var{string})
12907 @msindex{escape}
12908 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12909 within @var{string} into their respective quadrigraphs.  The result is
12910 still a quoted string.
12911 @end defmac
12913 @defmac m4_flatten (@var{string})
12914 @msindex{flatten}
12915 Flatten @var{string} into a single line.  Delete all backslash-newline
12916 pairs, and replace all remaining newlines with a space.  The result is
12917 still a quoted string.
12918 @end defmac
12920 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12921 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12922 @msindex{join}
12923 @msindex{joinall}
12924 Concatenate each @var{arg}, separated by @var{separator}.
12925 @code{joinall} uses every argument, while @code{join} omits empty
12926 arguments so that there are no back-to-back separators in the output.
12927 The result is a quoted string.
12928 @example
12929 m4_define([active], [ACTIVE])dnl
12930 m4_join([|], [one], [], [active], [two])
12931 @result{}one|active|two
12932 m4_joinall([|], [one], [], [active], [two])
12933 @result{}one||active|two
12934 @end example
12936 Note that if all you intend to do is join @var{args} with commas between
12937 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12938 efficient to use @code{m4_dquote}.
12939 @end defmac
12941 @defmac m4_newline (@ovar{text})
12942 @msindex{newline}
12943 This macro was introduced in Autoconf 2.62, and expands to a newline,
12944 followed by any @var{text}.
12945 It is primarily useful for maintaining macro formatting, and ensuring
12946 that M4 does not discard leading whitespace during argument collection.
12947 @end defmac
12949 @defmac m4_normalize (@var{string})
12950 @msindex{normalize}
12951 Remove leading and trailing spaces and tabs, sequences of
12952 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12953 with a single space.  This is a combination of @code{m4_flatten} and
12954 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12955 that would be removed by @code{m4_normalize}, you can use
12956 @code{m4_ifblank}.
12957 @end defmac
12959 @defmac m4_re_escape (@var{string})
12960 @msindex{re_escape}
12961 Backslash-escape all characters in @var{string} that are active in
12962 regexps.
12963 @end defmac
12965 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12966 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12967 @msindex{split}
12968 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12969 @samp{]}, while keeping white space at the beginning and at the end.
12970 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12971 If @var{string} is empty, the result is an empty list.
12972 @end defmac
12974 @defmac m4_strip (@var{string})
12975 @msindex{strip}
12976 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12977 reduced to a single space, then leading and trailing spaces are removed.
12978 The result is still a quoted string.  Note that this does not interfere
12979 with newlines; if you want newlines stripped as well, consider
12980 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12981 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12982 @end defmac
12984 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12985 @msindex{text_box}
12986 Add a text box around @var{message}, using @var{frame} as the border
12987 character above and below the message.  The @var{frame} argument must be
12988 a single byte, and does not support quadrigraphs.
12989 The frame correctly accounts for
12990 the subsequent expansion of @var{message}.  For example:
12991 @example
12992 m4_define([macro], [abc])dnl
12993 m4_text_box([macro])
12994 @result{}## --- ##
12995 @result{}## abc ##
12996 @result{}## --- ##
12997 @end example
12999 The @var{message} must contain balanced quotes and parentheses, although
13000 quadrigraphs can be used to work around this.
13001 @end defmac
13003 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13004   @dvarv{prefix1, prefix}, @dvar{width, 79})
13005 @msindex{text_wrap}
13006 Break @var{string} into a series of whitespace-separated words, then
13007 output those words separated by spaces, and wrapping lines any time the
13008 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13009 the first line, and @var{prefix} begins all wrapped lines.  If
13010 @var{prefix1} is longer than @var{prefix}, then the first line consists
13011 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13012 padding is inserted so that the first word of @var{string} begins at the
13013 same indentation as all wrapped lines.  Note that using literal tab
13014 characters in any of the arguments will interfere with the calculation
13015 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13016 words of @var{string}, although quadrigraphs are recognized.
13018 For some examples:
13019 @example
13020 m4_text_wrap([Short string */], [   ], [/* ], [20])
13021 @result{}/* Short string */
13022 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13023 @result{}/* Much longer
13024 @result{}   string */
13025 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13026 @result{}  --short Short doc.
13027 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13028 @result{}  --too-wide
13029 @result{}          Short doc.
13030 m4_text_wrap([Super long documentation.], [     ],
13031              [  --too-wide ], 30)
13032 @result{}  --too-wide
13033 @result{}     Super long
13034 @result{}     documentation.
13035 @end example
13036 @end defmac
13038 @defmac m4_tolower (@var{string})
13039 @defmacx m4_toupper (@var{string})
13040 @msindex{tolower}
13041 @msindex{toupper}
13042 Return @var{string} with letters converted to upper or lower case,
13043 respectively.
13044 @end defmac
13046 @node Number processing Macros
13047 @subsection Arithmetic computation in M4
13049 The following macros facilitate integer arithmetic operations.
13050 Where a parameter is documented as taking an arithmetic expression, you
13051 can use anything that can be parsed by @code{m4_eval}.
13053 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13054 @msindex{cmp}
13055 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13056 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13057 equal, and @samp{1} if @var{expr-1} is larger.
13058 @end defmac
13060 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13061 @msindex{list_cmp}
13062 Compare the two M4 lists consisting of comma-separated arithmetic
13063 expressions, left to right.  Expand to @samp{-1} for the first element
13064 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13065 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13066 same values.  If one list is shorter than the other, the remaining
13067 elements of the longer list are compared against zero.
13068 @example
13069 m4_list_cmp([1, 0],       [1])
13070 @result{}0
13071 m4_list_cmp([1, [1 * 0]], [1, 0])
13072 @result{}0
13073 m4_list_cmp([1, 2],       [1, 0])
13074 @result{}1
13075 m4_list_cmp([1, [1+1], 3],[1, 2])
13076 @result{}1
13077 m4_list_cmp([1, 2, -3],   [1, 2])
13078 @result{}-1
13079 m4_list_cmp([1, 0],       [1, 2])
13080 @result{}-1
13081 m4_list_cmp([1],          [1, 2])
13082 @result{}-1
13083 @end example
13084 @end defmac
13086 @defmac m4_max (@var{arg}, @dots{})
13087 @msindex{max}
13088 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13089 of the maximum arithmetic expression among all the arguments.
13090 @end defmac
13092 @defmac m4_min (@var{arg}, @dots{})
13093 @msindex{min}
13094 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13095 of the minimum arithmetic expression among all the arguments.
13096 @end defmac
13098 @defmac m4_sign (@var{expr})
13099 @msindex{sign}
13100 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13101 @samp{1} if it is positive, and @samp{0} if it is zero.
13102 @end defmac
13104 @anchor{m4_version_compare}
13105 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13106 @msindex{version_compare}
13107 This macro was introduced in Autoconf 2.53, but had a number of
13108 usability limitations that were not lifted until Autoconf 2.62.  Compare
13109 the version strings @var{version-1} and @var{version-2}, and expand to
13110 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13111 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13112 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13113 element is a number along with optional case-insensitive letters
13114 designating beta releases.  The comparison stops at the leftmost element
13115 that contains a difference, although a 0 element compares equal to a
13116 missing element.
13118 It is permissible to include commit identifiers in @var{version}, such
13119 as an abbreviated SHA1 of the commit, provided there is still a
13120 monotonically increasing prefix to allow for accurate version-based
13121 comparisons.  For example, this paragraph was written when the
13122 development snapshot of autoconf claimed to be at version
13123 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13124 abbreviated commit identification of @samp{dc51}.
13126 @example
13127 m4_version_compare([1.1], [2.0])
13128 @result{}-1
13129 m4_version_compare([2.0b], [2.0a])
13130 @result{}1
13131 m4_version_compare([1.1.1], [1.1.1a])
13132 @result{}-1
13133 m4_version_compare([1.2], [1.1.1a])
13134 @result{}1
13135 m4_version_compare([1.0], [1])
13136 @result{}0
13137 m4_version_compare([1.1pre], [1.1PRE])
13138 @result{}0
13139 m4_version_compare([1.1a], [1,10])
13140 @result{}-1
13141 m4_version_compare([2.61a], [2.61a-248-dc51])
13142 @result{}-1
13143 m4_version_compare([2.61b], [2.61a-248-dc51])
13144 @result{}1
13145 @end example
13146 @end defmac
13148 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13149   @dvar{if-old, m4_fatal})
13150 @msindex{version_prereq}
13151 Compares @var{version} against the version of Autoconf currently
13152 running.  If the running version is at @var{version} or newer, expand
13153 @var{if-new-enough}, but if @var{version} is larger than the version
13154 currently executing, expand @var{if-old}, which defaults to printing an
13155 error message and exiting m4sugar with status 63.  When given only one
13156 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13157 Remember that the autoconf philosophy favors feature checks over version
13158 checks.
13159 @end defmac
13161 @node Set manipulation Macros
13162 @subsection Set manipulation in M4
13163 @cindex Set manipulation
13164 @cindex Data structure, set
13165 @cindex Unordered set manipulation
13167 Sometimes, it is necessary to track a set of data, where the order does
13168 not matter and where there are no duplicates in the set.  The following
13169 macros facilitate set manipulations.  Each set is an opaque object,
13170 which can only be accessed via these basic operations.  The underlying
13171 implementation guarantees linear scaling for set creation, which is more
13172 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13173 names and values can be arbitrary strings, except for unbalanced quotes.
13174 This implementation ties up memory for removed elements until the next
13175 operation that must traverse all the elements of a set; and although
13176 that may slow down some operations until the memory for removed elements
13177 is pruned, it still guarantees linear performance.
13179 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13180 @msindex{set_add}
13181 Adds the string @var{value} as a member of set @var{set}.  Expand
13182 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13183 previously in the set.  Operates in amortized constant time, so that set
13184 creation scales linearly.
13185 @end defmac
13187 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13188 @msindex{set_add_all}
13189 Adds each @var{value} to the set @var{set}.  This is slightly more
13190 efficient than repeatedly invoking @code{m4_set_add}.
13191 @end defmac
13193 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13194  @ovar{if-absent})
13195 @msindex{set_contains}
13196 Expands @var{if-present} if the string @var{value} is a member of
13197 @var{set}, otherwise @var{if-absent}.
13199 @example
13200 m4_set_contains([a], [1], [yes], [no])
13201 @result{}no
13202 m4_set_add([a], [1], [added], [dup])
13203 @result{}added
13204 m4_set_add([a], [1], [added], [dup])
13205 @result{}dup
13206 m4_set_contains([a], [1], [yes], [no])
13207 @result{}yes
13208 m4_set_remove([a], [1], [removed], [missing])
13209 @result{}removed
13210 m4_set_contains([a], [1], [yes], [no])
13211 @result{}no
13212 m4_set_remove([a], [1], [removed], [missing])
13213 @result{}missing
13214 @end example
13215 @end defmac
13217 @defmac m4_set_contents (@var{set}, @ovar{sep})
13218 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13219 @msindex{set_contents}
13220 @msindex{set_dump}
13221 Expands to a single string consisting of all the members of the set
13222 @var{set}, each separated by @var{sep}, which is not expanded.
13223 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13224 memory occupied by removed elements, while @code{m4_set_dump} is a
13225 faster one-shot action that also deletes the set.  No provision is made
13226 for disambiguating members that contain a non-empty @var{sep} as a
13227 substring; use @code{m4_set_empty} to distinguish between an empty set
13228 and the set containing only the empty string.  The order of the output
13229 is unspecified; in the current implementation, part of the speed of
13230 @code{m4_set_dump} results from using a different output order than
13231 @code{m4_set_contents}.  These macros scale linearly in the size of the
13232 set before memory pruning, and @code{m4_set_contents([@var{set}],
13233 [@var{sep}])} is faster than
13234 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13236 @example
13237 m4_set_add_all([a], [1], [2], [3])
13238 @result{}
13239 m4_set_contents([a], [-])
13240 @result{}1-2-3
13241 m4_joinall([-]m4_set_listc([a]))
13242 @result{}1-2-3
13243 m4_set_dump([a], [-])
13244 @result{}3-2-1
13245 m4_set_contents([a])
13246 @result{}
13247 m4_set_add([a], [])
13248 @result{}
13249 m4_set_contents([a], [-])
13250 @result{}
13251 @end example
13252 @end defmac
13254 @defmac m4_set_delete (@var{set})
13255 @msindex{set_delete}
13256 Delete all elements and memory associated with @var{set}.  This is
13257 linear in the set size, and faster than removing one element at a time.
13258 @end defmac
13260 @defmac m4_set_difference (@var{seta}, @var{setb})
13261 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13262 @defmacx m4_set_union (@var{seta}, @var{setb})
13263 @msindex{set_difference}
13264 @msindex{set_intersection}
13265 @msindex{set_union}
13266 Compute the relation between @var{seta} and @var{setb}, and output the
13267 result as a list of quoted arguments without duplicates and with a
13268 leading comma.  Set difference selects the elements in @var{seta} but
13269 not @var{setb}, intersection selects only elements in both sets, and
13270 union selects elements in either set.  These actions are linear in the
13271 sum of the set sizes.  The leading comma is necessary to distinguish
13272 between no elements and the empty string as the only element.
13274 @example
13275 m4_set_add_all([a], [1], [2], [3])
13276 @result{}
13277 m4_set_add_all([b], [3], [], [4])
13278 @result{}
13279 m4_set_difference([a], [b])
13280 @result{},1,2
13281 m4_set_difference([b], [a])
13282 @result{},,4
13283 m4_set_intersection([a], [b])
13284 @result{},3
13285 m4_set_union([a], [b])
13286 @result{},1,2,3,,4
13287 @end example
13288 @end defmac
13290 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13291 @msindex{set_empty}
13292 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13293 expand @var{if-elements}.  This macro operates in constant time.  Using
13294 this macro can help disambiguate output from @code{m4_set_contents} or
13295 @code{m4_set_list}.
13296 @end defmac
13298 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13299 @msindex{set_foreach}
13300 For each element in the set @var{set}, expand @var{action} with the
13301 macro @var{variable} defined as the set element.  Behavior is
13302 unspecified if @var{action} recursively lists the contents of @var{set}
13303 (although listing other sets is acceptable), or if it modifies the set
13304 in any way other than removing the element currently contained in
13305 @var{variable}.  This macro is faster than the corresponding
13306 @code{m4_foreach([@var{variable}],
13307 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13308 although @code{m4_set_map} might be faster still.
13310 @example
13311 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13312 @result{}
13313 m4_set_contents([a])
13314 @result{}12345
13315 m4_set_foreach([a], [i],
13316   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13317 @result{}24
13318 m4_set_contents([a])
13319 @result{}135
13320 @end example
13321 @end defmac
13323 @defmac m4_set_list (@var{set})
13324 @defmacx m4_set_listc (@var{set})
13325 @msindex{set_list}
13326 @msindex{set_listc}
13327 Produce a list of arguments, where each argument is a quoted element
13328 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13329 by adding a leading comma if there are any set elements, whereas the
13330 variant @code{m4_set_list} cannot distinguish between an empty set and a
13331 set containing only the empty string.  These can be directly used in
13332 macros that take multiple arguments, such as @code{m4_join} or
13333 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13334 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13335 memory occupied by removed elements is reclaimed during these macros.
13337 @example
13338 m4_set_add_all([a], [1], [2], [3])
13339 @result{}
13340 m4_set_list([a])
13341 @result{}1,2,3
13342 m4_set_list([b])
13343 @result{}
13344 m4_set_listc([b])
13345 @result{}
13346 m4_count(m4_set_list([b]))
13347 @result{}1
13348 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13349 @result{}0
13350 m4_set_add([b], [])
13351 @result{}
13352 m4_set_list([b])
13353 @result{}
13354 m4_set_listc([b])
13355 @result{},
13356 m4_count(m4_set_list([b]))
13357 @result{}1
13358 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13359 @result{}1
13360 @end example
13361 @end defmac
13363 @defmac m4_set_map (@var{set}, @var{action})
13364 @msindex{set_map}
13365 For each element in the set @var{set}, expand @var{action} with a single
13366 argument of the set element.  Behavior is unspecified if @var{action}
13367 recursively lists the contents of @var{set} (although listing other sets
13368 is acceptable), or if it modifies the set in any way other than removing
13369 the element passed as an argument.  This macro is faster than either
13370 corresponding counterpart of
13371 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13372 @code{m4_set_foreach([@var{set}], [var],
13373 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13374 if more than one argument is needed for @var{action}, although it is
13375 more efficient to use @code{m4_set_map_sep} in that case.
13376 @end defmac
13378 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13379 @msindex{set_map_sep}
13380 For each element in the set @var{set}, expand
13381 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13382 between elements.  Behavior is unspecified if the expansion recursively
13383 lists the contents of @var{set} (although listing other sets
13384 is acceptable), or if it modifies the set in any way other than removing
13385 the element visited by the expansion.  This macro provides the most
13386 efficient means for non-destructively visiting the elements of a set; in
13387 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13388 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13389 @end defmac
13391 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13392  @ovar{if-absent})
13393 @msindex{set_remove}
13394 If @var{value} is an element in the set @var{set}, then remove it and
13395 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13396 operates in constant time so that multiple removals will scale linearly
13397 rather than quadratically; but when used outside of
13398 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13399 until the set is later
13400 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13401 other set operations are then less efficient between the time of element
13402 removal and subsequent memory compaction, but still maintain their
13403 guaranteed scaling performance.
13404 @end defmac
13406 @defmac m4_set_size (@var{set})
13407 @msindex{set_size}
13408 Expand to the size of the set @var{set}.  This implementation operates
13409 in constant time, and is thus more efficient than
13410 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13411 @end defmac
13414 @node Forbidden Patterns
13415 @subsection Forbidden Patterns
13416 @cindex Forbidden patterns
13417 @cindex Patterns, forbidden
13419 M4sugar provides a means to define suspicious patterns, patterns
13420 describing tokens which should not be found in the output.  For
13421 instance, if an Autoconf @file{configure} script includes tokens such as
13422 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13423 wrong (typically a macro was not evaluated because of overquotation).
13425 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13426 Additional layers, such as M4sh and Autoconf, add additional forbidden
13427 patterns to the list.
13429 @defmac m4_pattern_forbid (@var{pattern})
13430 @msindex{pattern_forbid}
13431 Declare that no token matching @var{pattern} must be found in the output.
13432 Comments are not checked; this can be a problem if, for instance, you
13433 have some macro left unexpanded after an @samp{#include}.  No consensus
13434 is currently found in the Autoconf community, as some people consider it
13435 should be valid to name macros in comments (which doesn't make sense to
13436 the authors of this documentation: input, such as macros, should be
13437 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13438 document the output).
13439 @end defmac
13441 Of course, you might encounter exceptions to these generic rules, for
13442 instance you might have to refer to @samp{$m4_flags}.
13444 @defmac m4_pattern_allow (@var{pattern})
13445 @msindex{pattern_allow}
13446 Any token matching @var{pattern} is allowed, including if it matches an
13447 @code{m4_pattern_forbid} pattern.
13448 @end defmac
13450 @node Debugging via autom4te
13451 @section Debugging via autom4te
13452 @cindex debugging tips
13453 @cindex autom4te debugging tips
13454 @cindex m4sugar debugging tips
13455 At times, it is desirable to see what was happening inside m4, to see
13456 why output was not matching expectations.  However, post-processing done
13457 by @command{autom4te} means that directly using the m4 builtin
13458 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13459 diversion changes and the concept of forbidden tokens make it difficult
13460 to use @code{m4_defn} to generate inline comments in the final output.
13462 There are a couple of tools to help with this.  One is the use of the
13463 @option{--trace} option provided by @command{autom4te} (as well as each
13464 of the programs that wrap @command{autom4te}, such as
13465 @command{autoconf}), in order to inspect when a macro is called and with
13466 which arguments.  For example, when this paragraph was written, the
13467 autoconf version could be found by:
13469 @example
13470 $ @kbd{autoconf --trace=AC_INIT}
13471 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13472 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13473 version is 2.63b.95-3963
13474 @end example
13476 Another trick is to print out the expansion of various m4 expressions to
13477 standard error or to an independent file, with no further m4 expansion,
13478 and without interfering with diversion changes or the post-processing
13479 done to standard output.  @code{m4_errprintn} shows a given expression
13480 on standard error.  For example, if you want to see the expansion of an
13481 autoconf primitive or of one of your autoconf macros, you can do it like
13482 this:
13484 @example
13485 $ @kbd{cat <<\EOF > configure.ac}
13486 AC_INIT
13487 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13488 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13489 AC_OUTPUT
13491 $ @kbd{autoconf}
13492 @error{}The definition of AC_DEFINE_UNQUOTED:
13493 @error{}_AC_DEFINE_Q([], $@@)
13494 @end example
13496 @node Programming in M4sh
13497 @chapter Programming in M4sh
13499 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13500 scripts.  This name was coined by Lars J. Aas, who notes that,
13501 according to the Webster's Revised Unabridged Dictionary (1913):
13503 @quotation
13504 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13505 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13507 @enumerate 1
13508 @item
13509 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13510 pressure@enddots{}
13512 @item
13513 A mixture of meal or bran and water fed to animals.
13515 @item
13516 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13517 @end enumerate
13518 @end quotation
13520 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13521 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13522 and environment variable namespace @samp{^as_}, and the here-document
13523 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13524 define your own macros or output shell code that conflicts with these
13525 namespaces.
13527 @menu
13528 * Common Shell Constructs::     Portability layer for common shell constructs
13529 * Polymorphic Variables::       Support for indirect variable names
13530 * Initialization Macros::       Macros to establish a sane shell environment
13531 * File Descriptor Macros::      File descriptor macros for input and output
13532 @end menu
13534 @node Common Shell Constructs
13535 @section Common Shell Constructs
13537 M4sh provides portable alternatives for some common shell constructs
13538 that unfortunately are not portable in practice.
13540 @c Deprecated, to be replaced by a better API
13541 @ignore
13542 @defmac AS_BASENAME (@var{file-name})
13543 @asindex{BASENAME}
13544 Output the non-directory portion of @var{file-name}.  For example,
13545 if @code{$file} is @samp{/one/two/three}, the command
13546 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13547 @end defmac
13548 @end ignore
13550 @defmac AS_BOX (@var{text}, @dvar{char, -})
13551 @asindex{BOX}
13552 Expand into shell code that will output @var{text} surrounded by a box
13553 with @var{char} in the top and bottom border.  @var{text} should not
13554 contain a newline, but may contain shell expansions valid for unquoted
13555 here-documents.  @var{char} defaults to @samp{-}, but can be any
13556 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13557 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13558 log files to separate distinct phases of script operation.
13559 @end defmac
13561 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13562   @dots{}, @ovar{default})
13563 @asindex{CASE}
13564 Expand into a shell @samp{case} statement, where @var{word} is matched
13565 against one or more patterns.  @var{if-matched} is run if the
13566 corresponding pattern matched @var{word}, else @var{default} is run.
13567 Avoids several portability issues (@pxref{case, , Limitations of Shell
13568 Builtins}).
13569 @end defmac
13571 @c Deprecated, to be replaced by a better API
13572 @defmac AS_DIRNAME (@var{file-name})
13573 @asindex{DIRNAME}
13574 Output the directory portion of @var{file-name}.  For example,
13575 if @code{$file} is @samp{/one/two/three}, the command
13576 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13578 This interface may be improved in the future to avoid forks and losing
13579 trailing newlines.
13580 @end defmac
13582 @defmac AS_ECHO (@var{word})
13583 @asindex{ECHO}
13584 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13585 must be a single shell word (typically a quoted string).  The bytes of
13586 @var{word} are output as-is, even if it starts with "-" or contains "\".
13587 Redirections can be placed outside the macro invocation.  This is much
13588 more portable than using @command{echo} (@pxref{echo, , Limitations of
13589 Shell Builtins}).
13590 @end defmac
13592 @defmac AS_ECHO_N (@var{word})
13593 @asindex{ECHO_N}
13594 Emits @var{word} to the standard output, without a following newline.
13595 @var{word} must be a single shell word (typically a quoted string) and,
13596 for portability, should not include more than one newline.  The bytes of
13597 @var{word} are output as-is, even if it starts with "-" or contains "\".
13598 Redirections can be placed outside the macro invocation.
13599 @end defmac
13601 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13602 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13603 @asindex{ESCAPE}
13604 Expands to @var{string}, with any characters in @var{chars} escaped with
13605 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13606 and only contain characters from the set @samp{`\"$}; however,
13607 characters may be safely listed more than once in @var{chars} for the
13608 sake of syntax highlighting editors.  The current implementation expands
13609 @var{string} after adding escapes; if @var{string} contains macro calls
13610 that in turn expand to text needing shell quoting, you can use
13611 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13613 The default for @var{chars} (@samp{\"$`}) is the set of characters
13614 needing escapes when @var{string} will be used literally within double
13615 quotes.  One common variant is the set of characters to protect when
13616 @var{string} will be used literally within back-ticks or an unquoted
13617 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13618 be used to form a double-quoted string containing the same expansions
13619 that would have occurred if @var{string} were expanded in an unquoted
13620 here-document; however, when using this variant, care must be taken that
13621 @var{string} does not use double quotes within complex variable
13622 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13623 with improper escapes.
13625 This macro is often used with @code{AS_ECHO}.  For an example, observe
13626 the output generated by the shell code generated from this snippet:
13628 @example
13629 foo=bar
13630 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13631 @result{}"$foo" = "bar"
13632 m4_define([macro], [a, [\b]])
13633 AS_ECHO(["AS_ESCAPE([[macro]])"])
13634 @result{}macro
13635 AS_ECHO(["AS_ESCAPE([macro])"])
13636 @result{}a, b
13637 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13638 @result{}a, \b
13639 @end example
13641 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13642 @comment the case of @var{string} that does not contain '.
13643 To escape a string that will be placed within single quotes, use:
13645 @example
13646 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13647 @end example
13648 @end defmac
13650 @defmac AS_EXECUTABLE_P (@var{file})
13651 @asindex{EXECUTABLE_P}
13652 Emit code to probe whether @var{file} is a regular file with executable
13653 permissions (and not a directory with search permissions).  The caller
13654 is responsible for quoting @var{file}.
13655 @end defmac
13657 @defmac AS_EXIT (@dvar{status, $?})
13658 @asindex{EXIT}
13659 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13660 This macro
13661 works around shells that see the exit status of the command prior to
13662 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13663 of Shell Builtins}).
13664 @end defmac
13666 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13667 @asindex{IF}
13668 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13669 run shell code @var{run-if-true1}, else examine further tests.  If no test
13670 exits with a zero status, run shell code @var{run-if-false}, with
13671 simplifications if either @var{run-if-true1} or @var{run-if-false}
13672 is empty.  For example,
13674 @example
13675 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13676       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13677       [echo foo not specified])
13678 @end example
13680 @noindent
13681 ensures any required macros of @code{HANDLE_FOO}
13682 are expanded before the first test.
13683 @end defmac
13685 @defmac AS_MKDIR_P (@var{file-name})
13686 @asindex{MKDIR_P}
13687 Make the directory @var{file-name}, including intervening directories
13688 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13689 except that it is portable to older versions of @command{mkdir} that
13690 lack support for the @option{-p} option or for the @option{--}
13691 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13692 @code{AS_MKDIR_P}
13693 succeeds if @var{file-name} is a symbolic link to an existing directory,
13694 even though Posix is unclear whether @samp{mkdir -p} should
13695 succeed in that case.  If creation of @var{file-name} fails, exit the
13696 script.
13698 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13699 @end defmac
13701 @defmac AS_SET_STATUS (@var{status})
13702 @asindex{SET_STATUS}
13703 Emit shell code to set the value of @samp{$?} to @var{status}, as
13704 efficiently as possible.  However, this is not guaranteed to abort a
13705 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13706 Builtins}).  This should also be used at the end of a complex shell
13707 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13708 a DJGPP shell bug.
13709 @end defmac
13711 @defmac AS_TR_CPP (@var{expression})
13712 @asindex{TR_CPP}
13713 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13714 For example:
13716 @example
13717 # This outputs "#define HAVE_CHAR_P 1".
13718 # Notice the m4 quoting around #, to prevent an m4 comment
13719 type="char *"
13720 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13721 @end example
13722 @end defmac
13724 @defmac AS_TR_SH (@var{expression})
13725 @asindex{TR_SH}
13726 Transform @var{expression} into shell code that generates a valid shell
13727 variable name.  The result is literal when possible at m4 time, but must
13728 be used with @code{eval} if @var{expression} causes shell indirections.
13729 For example:
13731 @example
13732 # This outputs "Have it!".
13733 header="sys/some file.h"
13734 eval AS_TR_SH([HAVE_$header])=yes
13735 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13736 @end example
13737 @end defmac
13739 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13740 @asindex{SET_CATFILE}
13741 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13742 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13743 @var{file} is absolute, etc.).
13744 @end defmac
13746 @defmac AS_UNSET (@var{var})
13747 @asindex{UNSET}
13748 Unsets the shell variable @var{var}, working around bugs in older
13749 shells (@pxref{unset, , Limitations of Shell
13750 Builtins}).  @var{var} can be a literal or indirect variable name.
13751 @end defmac
13753 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13754   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13755 @asindex{VERSION_COMPARE}
13756 Compare two strings @var{version-1} and @var{version-2}, possibly
13757 containing shell variables, as version strings, and expand
13758 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13759 depending upon the result.
13760 The algorithm to compare is similar to the one used by strverscmp in
13761 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13762 The GNU C Library}).
13763 @end defmac
13765 @node Polymorphic Variables
13766 @section Support for indirect variable names
13767 @cindex variable name indirection
13768 @cindex polymorphic variable name
13769 @cindex indirection, variable name
13771 Often, it is convenient to write a macro that will emit shell code
13772 operating on a shell variable.  The simplest case is when the variable
13773 name is known.  But a more powerful idiom is writing shell code that can
13774 work through an indirection, where another variable or command
13775 substitution produces the name of the variable to actually manipulate.
13776 M4sh supports the notion of polymorphic shell variables, making it easy
13777 to write a macro that can deal with either literal or indirect variable
13778 names and output shell code appropriate for both use cases.  Behavior is
13779 undefined if expansion of an indirect variable does not result in a
13780 literal variable name.
13782 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13783   @dvarv{if-simple-ref, if-not})
13784 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13785   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
13786 @asindex{LITERAL_IF}
13787 @asindex{LITERAL_WORD_IF}
13788 If the expansion of @var{expression} is definitely a shell literal,
13789 expand @var{if-literal}.  If the expansion of @var{expression} looks
13790 like it might contain shell indirections (such as @code{$var} or
13791 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13792 possible to output optimized code if @var{expression} consists only of
13793 shell variable expansions (such as @code{$@{var@}}), in which case
13794 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13795 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13796 @var{if-literal} if @var{expression} looks like a single shell word,
13797 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13798 in @var{expression}.
13800 In order to reduce the time spent recognizing whether an
13801 @var{expression} qualifies as a literal or a simple indirection, the
13802 implementation is somewhat conservative: @var{expression} must be a
13803 single shell word (possibly after stripping whitespace), consisting only
13804 of bytes that would have the same meaning whether unquoted or enclosed
13805 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13806 even though it is not a valid shell variable name; while both @samp{'a'}
13807 and @samp{[$]} result in @var{if-not}, because they behave differently
13808 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13809 for recognizing portable file names (such as in the implementation of
13810 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13811 valid variable names (such as in the implementation of @code{AS_TR_SH},
13812 which uses an additional @code{m4_translit} to convert @samp{.} to
13813 @samp{_}).
13815 This example shows how to read the contents of the shell variable
13816 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13817 results in a script that will output the line @samp{hello} three times.
13819 @example
13820 AC_DEFUN([MY_ACTION],
13821 [AS_LITERAL_IF([$1],
13822   [echo "$$1"],
13823 @c $$
13824   [AS_VAR_COPY([var], [$1])
13825    echo "$var"],
13826   [eval 'echo "$'"$1"\"])])
13827 foo=bar bar=hello
13828 MY_ACTION([bar])
13829 MY_ACTION([`echo bar`])
13830 MY_ACTION([$foo])
13831 @end example
13832 @end defmac
13834 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13835 @asindex{VAR_APPEND}
13836 Emit shell code to append the shell expansion of @var{text} to the end
13837 of the current contents of the polymorphic shell variable @var{var},
13838 taking advantage of shells that provide the @samp{+=} extension for more
13839 efficient scaling.
13841 For situations where the final contents of @var{var} are relatively
13842 short (less than 256 bytes), it is more efficient to use the simpler
13843 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13844 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13845 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13846 when the script will be repeatedly appending text into @code{var},
13847 issues of scaling start to become apparent.  A naive implementation
13848 requires execution time linear to the length of the current contents of
13849 @var{var} as well as the length of @var{text} for a single append, for
13850 an overall quadratic scaling with multiple appends.  This macro takes
13851 advantage of shells which provide the extension
13852 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13853 for a single append, for an overall linear scaling with multiple
13854 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13855 @var{text} be quoted properly to avoid field splitting and file name
13856 expansion.
13857 @end defmac
13859 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13860 @asindex{VAR_ARITH}
13861 Emit shell code to compute the arithmetic expansion of @var{expression},
13862 assigning the result as the contents of the polymorphic shell variable
13863 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13864 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13865 syntax for a valid @var{expression} is rather limited: all operators
13866 must occur as separate shell arguments and with proper quoting, there is
13867 no portable equality operator, all variables containing numeric values
13868 must be expanded prior to the computation, all numeric values must be
13869 provided in decimal without leading zeroes, and the first shell argument
13870 should not be a negative number.  In the following example, this snippet
13871 will print @samp{(2+3)*4 == 20}.
13873 @example
13874 bar=3
13875 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13876 echo "(2+$bar)*4 == $foo"
13877 @end example
13878 @end defmac
13880 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13881 @asindex{VAR_COPY}
13882 Emit shell code to assign the contents of the polymorphic shell variable
13883 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13884 executing this M4sh snippet will output @samp{bar hi}:
13886 @example
13887 foo=bar bar=hi
13888 AS_VAR_COPY([a], [foo])
13889 AS_VAR_COPY([b], [$foo])
13890 echo "$a $b"
13891 @end example
13893 When it is necessary to access the contents of an indirect variable
13894 inside a shell double-quoted context, the recommended idiom is to first
13895 copy the contents into a temporary literal shell variable.
13897 @smallexample
13898 for header in stdint_h inttypes_h ; do
13899   AS_VAR_COPY([var], [ac_cv_header_$header])
13900   echo "$header detected: $var"
13901 done
13902 @end smallexample
13903 @end defmac
13905 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13906 @comment trailing newlines uniformly, and forks too much.
13908 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13909   @ovar{if-not-equal})
13910 @asindex{VAR_IF}
13911 Output a shell conditional statement.  If the contents of the
13912 polymorphic shell variable @var{var} match the string @var{word},
13913 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13914 must be a single shell word (typically a quoted string).  Avoids
13915 shell bugs if an interrupt signal arrives while a command substitution
13916 in @var{var} is being expanded.
13917 @end defmac
13919 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13920 @defmacx AS_VAR_POPDEF (@var{m4-name})
13921 @asindex{VAR_PUSHDEF}
13922 @asindex{VAR_POPDEF}
13923 @cindex composing variable names
13924 @cindex variable names, composing
13925 A common M4sh idiom involves composing shell variable names from an m4
13926 argument (for example, writing a macro that uses a cache variable).
13927 @var{value} can be an arbitrary string, which will be transliterated
13928 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13929 composed variable name based on @var{value}, it is easier to declare a
13930 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13931 that macro as the argument to subsequent @code{AS_VAR} macros as a
13932 polymorphic variable name, and finally free the temporary macro with
13933 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13934 to avoid excess newlines in the output.
13936 Here is an involved example, that shows the power of writing macros that
13937 can handle composed shell variable names:
13939 @example
13940 m4_define([MY_CHECK_HEADER],
13941 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13942 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13943 AS_VAR_POPDEF([my_Header])dnl
13945 MY_CHECK_HEADER([stdint.h])
13946 for header in inttypes.h stdlib.h ; do
13947   MY_CHECK_HEADER([$header])
13948 done
13949 @end example
13951 @noindent
13952 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13953 variable names.  In the first invocation, the m4 argument is
13954 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13955 As a result, the temporary macro @code{my_Header} expands to the literal
13956 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13957 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13958 temporary macro @code{my_Header} expands to the indirect shell name
13959 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13960 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13961 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13962 platform where all three headers have been previously detected, the
13963 output of the script will include:
13965 @smallexample
13966 header stdint.h detected
13967 header inttypes.h detected
13968 header stdlib.h detected
13969 @end smallexample
13970 @end defmac
13972 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13973 @asindex{VAR_SET}
13974 Emit shell code to assign the contents of the polymorphic shell variable
13975 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13976 subject to field splitting or file name expansion, so if command
13977 substitution is used, it may be done with @samp{`""`} rather than using
13978 an intermediate variable (@pxref{Shell Substitutions}).  However,
13979 @var{value} does undergo rescanning for additional macro names; behavior
13980 is unspecified if late expansion results in any shell meta-characters.
13981 @end defmac
13983 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13984 @asindex{VAR_SET_IF}
13985 Emit a shell conditional statement, which executes @var{if-set} if the
13986 polymorphic shell variable @code{var} is set to any value, and
13987 @var{if-undef} otherwise.
13988 @end defmac
13990 @defmac AS_VAR_TEST_SET (@var{var})
13991 @asindex{VAR_TEST_SET}
13992 Emit a shell statement that results in a successful exit status only if
13993 the polymorphic shell variable @code{var} is set.
13994 @end defmac
13996 @node Initialization Macros
13997 @section Initialization Macros
13999 @defmac AS_BOURNE_COMPATIBLE
14000 @asindex{BOURNE_COMPATIBLE}
14001 Set up the shell to be more compatible with the Bourne shell as
14002 standardized by Posix, if possible.  This may involve setting
14003 environment variables, or setting options, or similar
14004 implementation-specific actions.  This macro is deprecated, since
14005 @code{AS_INIT} already invokes it.
14006 @end defmac
14008 @defmac AS_INIT
14009 @asindex{INIT}
14010 @evindex LC_ALL
14011 @evindex SHELL
14012 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14013 outputs the @code{#! /bin/sh} line, a notice about where the output was
14014 generated from, and code to sanitize the environment for the rest of the
14015 script.  Among other initializations, this sets @env{SHELL} to the shell
14016 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14017 ensure the C locale.  Finally, it changes the current diversion to
14018 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14019 and @code{AT_INIT}, so shell code in @file{configure},
14020 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14021 shell environment.
14022 @end defmac
14024 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14025 @asindex{INIT_GENERATED}
14026 Emit shell code to start the creation of a subsidiary shell script in
14027 @var{file}, including changing @var{file} to be executable.  This macro
14028 populates the child script with information learned from the parent
14029 (thus, the emitted code is equivalent in effect, but more efficient,
14030 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14031 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14032 beginning of the child, prior to the shell initialization code, and is
14033 subject to parameter expansion, command substitution, and backslash
14034 quote removal.  The
14035 parent script should check the exit status after this macro, in case
14036 @var{file} could not be properly created (for example, if the disk was
14037 full).  If successfully created, the parent script can then proceed to
14038 append additional M4sh constructs into the child script.
14040 Note that the child script starts life without a log file open, so if
14041 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14042 must temporarily disable any attempts to use the log file until after
14043 emitting code to open a log within the child.  On the other hand, if the
14044 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14045 @samp{1}, then the child script already has code that copies stdout to
14046 that descriptor.  Currently, the suggested
14047 idiom for writing a M4sh shell script from within another script is:
14049 @example
14050 AS_INIT_GENERATED([@var{file}], [[# My child script.
14051 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14052 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14053 cat >> "@var{file}" <<\__EOF__
14054 # Code to initialize AS_MESSAGE_LOG_FD
14055 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14056 # Additional code
14057 __EOF__
14058 @end example
14060 This, however, may change in the future as the M4sh interface is
14061 stabilized further.
14063 Also, be aware that use of @env{LINENO} within the child script may
14064 report line numbers relative to their location in the parent script,
14065 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14066 unable to locate a shell with working @env{LINENO} support.
14067 @end defmac
14069 @defmac AS_LINENO_PREPARE
14070 @asindex{LINENO_PREPARE}
14071 @evindex LINENO
14072 Find a shell that supports the special variable @env{LINENO}, which
14073 contains the number of the currently executing line.  This macro is
14074 automatically invoked by @code{AC_INIT} in configure scripts.
14075 @end defmac
14077 @defmac AS_ME_PREPARE
14078 @asindex{ME_PREPARE}
14079 Set up variable @env{as_me} to be the basename of the currently executing
14080 script.  This macro is automatically invoked by @code{AC_INIT} in
14081 configure scripts.
14082 @end defmac
14084 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14085 @asindex{TMPDIR}
14086 @evindex TMPDIR
14087 @ovindex tmp
14088 Create, as safely as possible, a temporary sub-directory within
14089 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14090 be 2-4 characters, to make it slightly easier to identify the owner of
14091 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14092 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14093 newly created directory is stored in the shell variable @code{tmp}.  On
14094 error, the script is aborted.
14096 Typically, this macro is coupled with some exit traps to delete the created
14097 directory and its contents on exit or interrupt.  However, there is a
14098 slight window between when the directory is created and when the name is
14099 actually known to the shell, so an interrupt at the right moment might
14100 leave the temporary directory behind.  Hence it is important to use a
14101 @var{prefix} that makes it easier to determine if a leftover temporary
14102 directory from an interrupted script is safe to delete.
14104 The use of the output variable @samp{$tmp} rather than something in the
14105 @samp{as_} namespace is historical; it has the unfortunate consequence
14106 that reusing this otherwise common name for any other purpose inside
14107 your script has the potential to break any cleanup traps designed to
14108 remove the temporary directory.
14109 @end defmac
14111 @defmac AS_SHELL_SANITIZE
14112 @asindex{SHELL_SANITIZE}
14113 Initialize the shell suitably for @command{configure} scripts.  This has
14114 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14115 environment variables for predictable results from configuration tests.
14116 For example, it sets @env{LC_ALL} to change to the default C locale.
14117 @xref{Special Shell Variables}.  This macro is deprecated, since
14118 @code{AS_INIT} already invokes it.
14119 @end defmac
14122 @node File Descriptor Macros
14123 @section File Descriptor Macros
14124 @cindex input
14125 @cindex standard input
14126 @cindex file descriptors
14127 @cindex descriptors
14128 @cindex low-level output
14129 @cindex output, low-level
14131 The following macros define file descriptors used to output messages
14132 (or input values) from @file{configure} scripts.
14133 For example:
14135 @example
14136 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14137 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14138 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14139 @end example
14141 @noindent
14142 However doing so is seldom needed, because Autoconf provides higher
14143 level macros as described below.
14145 @defmac AS_MESSAGE_FD
14146 @asindex{MESSAGE_FD}
14147 The file descriptor for @samp{checking for...}  messages and results.
14148 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14149 clients.  However, @code{AC_INIT} shuffles things around to another file
14150 descriptor, in order to allow the @option{-q} option of
14151 @command{configure} to choose whether messages should go to the script's
14152 standard output or be discarded.
14154 If you want to display some messages, consider using one of the printing
14155 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14156 via these macros are also recorded in @file{config.log}.
14157 @end defmac
14159 @anchor{AS_MESSAGE_LOG_FD}
14160 @defmac AS_MESSAGE_LOG_FD
14161 @asindex{MESSAGE_LOG_FD}
14162 This must either be empty, or expand to a file descriptor for log
14163 messages.  By default, @code{AS_INIT} sets this macro to the empty
14164 string for standalone M4sh clients, thus disabling logging.  However,
14165 @code{AC_INIT} shuffles things around so that both @command{configure}
14166 and @command{config.status} use @file{config.log} for log messages.
14167 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14168 Compiler}), redirect all output to this descriptor.  You may want to do
14169 so if you develop such a low-level macro.
14170 @end defmac
14172 @defmac AS_ORIGINAL_STDIN_FD
14173 @asindex{ORIGINAL_STDIN_FD}
14174 This must expand to a file descriptor for the original standard input.
14175 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14176 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14177 safety.
14179 When @command{configure} runs, it may accidentally execute an
14180 interactive command that has the same name as the non-interactive meant
14181 to be used or checked.  If the standard input was the terminal, such
14182 interactive programs would cause @command{configure} to stop, pending
14183 some user input.  Therefore @command{configure} redirects its standard
14184 input from @file{/dev/null} during its initialization.  This is not
14185 normally a problem, since @command{configure} normally does not need
14186 user input.
14188 In the extreme case where your @file{configure} script really needs to
14189 obtain some values from the original standard input, you can read them
14190 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14191 @end defmac
14194 @c =================================================== Writing Autoconf Macros.
14196 @node Writing Autoconf Macros
14197 @chapter Writing Autoconf Macros
14199 When you write a feature test that could be applicable to more than one
14200 software package, the best thing to do is encapsulate it in a new macro.
14201 Here are some instructions and guidelines for writing Autoconf macros.
14203 @menu
14204 * Macro Definitions::           Basic format of an Autoconf macro
14205 * Macro Names::                 What to call your new macros
14206 * Reporting Messages::          Notifying @command{autoconf} users
14207 * Dependencies Between Macros::  What to do when macros depend on other macros
14208 * Obsoleting Macros::           Warning about old ways of doing things
14209 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14210 @end menu
14212 @node Macro Definitions
14213 @section Macro Definitions
14215 @defmac AC_DEFUN (@var{name}, @ovar{body})
14216 @acindex{DEFUN}
14217 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14218 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14219 named @var{name} and with @var{body} as its expansion.  In addition to
14220 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14221 constrain the order in which macros are called, while avoiding redundant
14222 output (@pxref{Prerequisite Macros}).
14223 @end defmac
14225 An Autoconf macro definition looks like this:
14227 @example
14228 AC_DEFUN(@var{macro-name}, @var{macro-body})
14229 @end example
14231 You can refer to any arguments passed to the macro as @samp{$1},
14232 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
14233 GNU M4}, for more complete information on writing M4 macros.
14235 Most macros fall in one of two general categories.  The first category
14236 includes macros which take arguments, in order to generate output
14237 parameterized by those arguments.  Macros in this category are designed
14238 to be directly expanded, often multiple times, and should not be used as
14239 the argument to @code{AC_REQUIRE}.  The other category includes macros
14240 which are shorthand for a fixed block of text, and therefore do not take
14241 arguments.  For this category of macros, directly expanding the macro
14242 multiple times results in redundant output, so it is more common to use
14243 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14244 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14246 Be sure to properly quote both the @var{macro-body} @emph{and} the
14247 @var{macro-name} to avoid any problems if the macro happens to have
14248 been previously defined.
14250 Each macro should have a header comment that gives its prototype, and a
14251 brief description.  When arguments have default values, display them in
14252 the prototype.  For example:
14254 @example
14255 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14256 # --------------------------------------
14257 m4_define([AC_MSG_ERROR],
14258   [@{ AS_MESSAGE([error: $1], [2])
14259      exit m4_default([$2], [1]); @}])
14260 @end example
14262 Comments about the macro should be left in the header comment.  Most
14263 other comments make their way into @file{configure}, so just keep
14264 using @samp{#} to introduce comments.
14266 @cindex @code{dnl}
14267 If you have some special comments about pure M4 code, comments
14268 that make no sense in @file{configure} and in the header comment, then
14269 use the builtin @code{dnl}: it causes M4 to discard the text
14270 through the next newline.
14272 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14273 @code{dnl} is more useful to get rid of the newlines following macros
14274 that produce no output, such as @code{AC_REQUIRE}.
14276 Public third-party macros need to use @code{AC_DEFUN}, and not
14277 @code{m4_define}, in order to be found by @command{aclocal}
14278 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14279 Additionally, if it is ever determined that a macro should be made
14280 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14281 in order to have @command{autoupdate} assist the user in choosing a
14282 better alternative, but there is no corresponding way to make
14283 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14285 There is another subtle, but important, difference between using
14286 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14287 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14288 block of text with a @code{m4_define} macro that will expand to the same
14289 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14290 the same content does not necessarily give the same results, because it
14291 changes the location where any embedded but unsatisfied
14292 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14293 example of this, see @ref{Expanded Before Required}.
14295 @node Macro Names
14296 @section Macro Names
14298 All of the public Autoconf macros have all-uppercase names in the
14299 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14300 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14301 internal macros.  All shell variables that they use for internal
14302 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14303 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14304 @command{configure}, files produced by Autoconf make heavy use of the
14305 file system namespace @samp{^conf}.
14307 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14308 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14309 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14310 @file{configure.ac} is also designed to be scanned by Autoheader,
14311 Autoscan, Autoupdate, and Automake, you should be aware of the
14312 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14313 the namespace of a package that does not own the macro or shell code you
14314 are writing.
14316 To ensure that your macros don't conflict with present or future
14317 Autoconf macros, you should prefix your own macro names and any shell
14318 variables they use with some other sequence.  Possibilities include your
14319 initials, or an abbreviation for the name of your organization or
14320 software package.  Historically, people have not always followed the
14321 rule of using a namespace appropriate for their package, and this has
14322 made it difficult for determining the origin of a macro (and where to
14323 report bugs about that macro), as well as difficult for the true
14324 namespace owner to add new macros without interference from pre-existing
14325 uses of third-party macros.  Perhaps the best example of this confusion
14326 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14327 to Gettext.
14329 Most of the Autoconf macros' names follow a structured naming convention
14330 that indicates the kind of feature check by the name.  The macro names
14331 consist of several words, separated by underscores, going from most
14332 general to most specific.  The names of their cache variables use the
14333 same convention (@pxref{Cache Variable Names}, for more information on
14334 them).
14336 The first word of the name after the namespace initials (such as
14337 @samp{AC_}) usually tells the category
14338 of the feature being tested.  Here are the categories used in Autoconf for
14339 specific test macros, the kind of macro that you are more likely to
14340 write.  They are also used for cache variables, in all-lowercase.  Use
14341 them where applicable; where they're not, invent your own categories.
14343 @table @code
14344 @item C
14345 C language builtin features.
14346 @item DECL
14347 Declarations of C variables in header files.
14348 @item FUNC
14349 Functions in libraries.
14350 @item GROUP
14351 Posix group owners of files.
14352 @item HEADER
14353 Header files.
14354 @item LIB
14355 C libraries.
14356 @item PROG
14357 The base names of programs.
14358 @item MEMBER
14359 Members of aggregates.
14360 @item SYS
14361 Operating system features.
14362 @item TYPE
14363 C builtin or declared types.
14364 @item VAR
14365 C variables in libraries.
14366 @end table
14368 After the category comes the name of the particular feature being
14369 tested.  Any further words in the macro name indicate particular aspects
14370 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14371 @command{make} sets a variable to its own name.
14373 An internal macro should have a name that starts with an underscore;
14374 Autoconf internals should therefore start with @samp{_AC_}.
14375 Additionally, a macro that is an internal subroutine of another macro
14376 should have a name that starts with an underscore and the name of that
14377 other macro, followed by one or more words saying what the internal
14378 macro does.  For example, @code{AC_PATH_X} has internal macros
14379 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14381 @node Reporting Messages
14382 @section Reporting Messages
14383 @cindex Messages, from @command{autoconf}
14385 When macros statically diagnose abnormal situations, benign or fatal, it
14386 is possible to make @command{autoconf} detect the problem, and refuse to
14387 create @file{configure} in the case of an error.  The macros in this
14388 section are considered obsolescent, and new code should use M4sugar
14389 macros for this purpose, see @ref{Diagnostic Macros}.
14391 On the other hand, it is possible to want to detect errors when
14392 @command{configure} is run, which are dependent on the environment of
14393 the user rather than the maintainer.  For dynamic diagnostics, see
14394 @ref{Printing Messages}.
14396 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14397 @acindex{DIAGNOSE}
14398 Report @var{message} as a warning (or as an error if requested by the
14399 user) if warnings of the @var{category} are turned on.  This macro is
14400 obsolescent; you are encouraged to use:
14401 @example
14402 m4_warn([@var{category}], [@var{message}])
14403 @end example
14404 @noindent
14405 instead.  @xref{m4_warn}, for more details, including valid
14406 @var{category} names.
14407 @end defmac
14409 @defmac AC_WARNING (@var{message})
14410 @acindex{WARNING}
14411 Report @var{message} as a syntax warning.  This macro is obsolescent;
14412 you are encouraged to use:
14413 @example
14414 m4_warn([syntax], [@var{message}])
14415 @end example
14416 @noindent
14417 instead.  @xref{m4_warn}, for more details, as well as better
14418 finer-grained categories of warnings (not all problems have to do with
14419 syntax).
14420 @end defmac
14422 @defmac AC_FATAL (@var{message})
14423 @acindex{FATAL}
14424 Report a severe error @var{message}, and have @command{autoconf} die.
14425 This macro is obsolescent; you are encouraged to use:
14426 @example
14427 m4_fatal([@var{message}])
14428 @end example
14429 @noindent
14430 instead.  @xref{m4_fatal}, for more details.
14431 @end defmac
14433 When the user runs @samp{autoconf -W error}, warnings from
14434 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14435 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14437 @node Dependencies Between Macros
14438 @section Dependencies Between Macros
14439 @cindex Dependencies between macros
14441 Some Autoconf macros depend on other macros having been called first in
14442 order to work correctly.  Autoconf provides a way to ensure that certain
14443 macros are called if needed and a way to warn the user if macros are
14444 called in an order that might cause incorrect operation.
14446 @menu
14447 * Prerequisite Macros::         Ensuring required information
14448 * Suggested Ordering::          Warning about possible ordering problems
14449 * One-Shot Macros::             Ensuring a macro is called only once
14450 @end menu
14452 @node Prerequisite Macros
14453 @subsection Prerequisite Macros
14454 @cindex Prerequisite macros
14455 @cindex Macros, prerequisites
14457 A macro that you write might need to use values that have previously
14458 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14459 examines the output of @code{flex} or @code{lex}, so it depends on
14460 @code{AC_PROG_LEX} having been called first to set the shell variable
14461 @code{LEX}.
14463 Rather than forcing the user of the macros to keep track of the
14464 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14465 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14466 called if it is needed, and only called once.
14468 @defmac AC_REQUIRE (@var{macro-name})
14469 @acindex{REQUIRE}
14470 If the M4 macro @var{macro-name} has not already been called, call it
14471 (without any arguments).  Make sure to quote @var{macro-name} with
14472 square brackets.  @var{macro-name} must have been defined using
14473 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14474 that it has been called.
14476 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14477 must not be called from the top level.  Also, it does not make sense to
14478 require a macro that takes parameters.
14479 @end defmac
14481 @code{AC_REQUIRE} is often misunderstood.  It really implements
14482 dependencies between macros in the sense that if one macro depends upon
14483 another, the latter is expanded @emph{before} the body of the
14484 former.  To be more precise, the required macro is expanded before
14485 the outermost defined macro in the current expansion stack.
14486 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14487 @code{FOO}.  For instance, this definition of macros:
14489 @example
14490 @group
14491 AC_DEFUN([TRAVOLTA],
14492 [test "$body_temperature_in_celsius" -gt "38" &&
14493   dance_floor=occupied])
14494 AC_DEFUN([NEWTON_JOHN],
14495 [test "x$hair_style" = xcurly &&
14496   dance_floor=occupied])
14497 @end group
14499 @group
14500 AC_DEFUN([RESERVE_DANCE_FLOOR],
14501 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14502   AC_REQUIRE([TRAVOLTA])
14503   AC_REQUIRE([NEWTON_JOHN])
14504 fi])
14505 @end group
14506 @end example
14508 @noindent
14509 with this @file{configure.ac}
14511 @example
14512 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14513 RESERVE_DANCE_FLOOR
14514 if test "x$dance_floor" = xoccupied; then
14515   AC_MSG_ERROR([cannot pick up here, let's move])
14517 @end example
14519 @noindent
14520 does not leave you with a better chance to meet a kindred soul at
14521 other times than Saturday night since it expands into:
14523 @example
14524 @group
14525 test "$body_temperature_in_Celsius" -gt "38" &&
14526   dance_floor=occupied
14527 test "x$hair_style" = xcurly &&
14528   dance_floor=occupied
14530 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14534 @end group
14535 @end example
14537 This behavior was chosen on purpose: (i) it prevents messages in
14538 required macros from interrupting the messages in the requiring macros;
14539 (ii) it avoids bad surprises when shell conditionals are used, as in:
14541 @example
14542 @group
14543 if @dots{}; then
14544   AC_REQUIRE([SOME_CHECK])
14546 @dots{}
14547 SOME_CHECK
14548 @end group
14549 @end example
14551 However, this implementation can lead to another class of problems.
14552 Consider the case where an outer macro first expands, then indirectly
14553 requires, an inner macro:
14555 @example
14556 AC_DEFUN([TESTA], [[echo in A
14557 if test -n "$SEEN_A" ; then echo duplicate ; fi
14558 SEEN_A=:]])
14559 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14560 if test -z "$SEEN_A" ; then echo bug ; fi]])
14561 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14562 AC_DEFUN([OUTER], [[echo in OUTER]
14563 TESTA
14564 TESTC])
14565 OUTER
14566 @end example
14568 @noindent
14569 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14570 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14571 of @code{OUTER}, but because @code{TESTA} had already been directly
14572 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14573 @code{TESTB} occurs prior to its prerequisites, leading to the following
14574 output:
14576 @example
14577 in B
14579 in OUTER
14580 in A
14581 in C
14582 @end example
14584 @noindent
14585 Newer Autoconf is smart enough to recognize this situation, and hoists
14586 @code{TESTA} even though it has already been expanded, but issues a
14587 syntax warning in the process.  This is because the hoisted expansion of
14588 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14589 redundant code, and causes its own set of problems if the hoisted macro
14590 is not idempotent:
14592 @example
14593 in A
14594 in B
14595 in OUTER
14596 in A
14597 duplicate
14598 in C
14599 @end example
14601 The bug is not in Autoconf, but in the macro definitions.  If you ever
14602 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14603 that the macro only needs to be expanded once.  But to enforce this,
14604 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14605 this only helps in Autoconf 2.64 or newer), or all
14606 uses of that macro should be through @code{AC_REQUIRE}; directly
14607 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14608 eliminate redundant expansion.  In the example, this rule of thumb was
14609 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14610 directly expands it.  One way of fixing the bug is to factor
14611 @code{TESTA} into two macros, the portion designed for direct and
14612 repeated use (here, named @code{TESTA}), and the portion designed for
14613 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14614 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14615 calling convention according to their needs:
14617 @example
14618 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14619 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14620 if test -n "$SEEN_A" ; then echo duplicate ; fi
14621 SEEN_A=:]])
14622 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14623 if test -z "$SEEN_A" ; then echo bug ; fi]])
14624 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14625 AC_DEFUN([OUTER], [[echo in OUTER]
14626 TESTA
14627 TESTC])
14628 OUTER
14629 @end example
14631 @noindent
14632 the resulting output will then obey all dependency rules and avoid any
14633 syntax warnings, whether the script is built with old or new Autoconf
14634 versions:
14636 @example
14637 in A_PREREQ
14638 in B
14639 in OUTER
14640 in A
14641 in C
14642 @end example
14644 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14645 enforce expansion of required macros outside of shell conditional
14646 constructs.  You are furthermore encouraged, although not required, to
14647 put all @code{AC_REQUIRE} calls
14648 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14649 lines they leave.
14651 @node Suggested Ordering
14652 @subsection Suggested Ordering
14653 @cindex Macros, ordering
14654 @cindex Ordering macros
14656 Some macros should be run before another macro if both are called, but
14657 neither @emph{requires} that the other be called.  For example, a macro
14658 that changes the behavior of the C compiler should be called before any
14659 macros that run the C compiler.  Many of these dependencies are noted in
14660 the documentation.
14662 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14663 with this kind of dependency appear out of order in a
14664 @file{configure.ac} file.  The warning occurs when creating
14665 @command{configure} from @file{configure.ac}, not when running
14666 @command{configure}.
14668 For example, @code{AC_PROG_CPP} checks whether the C compiler
14669 can run the C preprocessor when given the @option{-E} option.  It should
14670 therefore be called after any macros that change which C compiler is
14671 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14673 @example
14674 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14675 @end example
14677 @noindent
14678 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14679 when @code{AC_PROG_CC} is called.
14681 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14682 @acindex{BEFORE}
14683 Make M4 print a warning message to the standard error output if
14684 @var{called-macro-name} has already been called.  @var{this-macro-name}
14685 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14686 macro @var{called-macro-name} must have been defined using
14687 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14688 that it has been called.
14689 @end defmac
14691 @node One-Shot Macros
14692 @subsection One-Shot Macros
14693 @cindex One-shot macros
14694 @cindex Macros, called once
14696 Some macros should be called only once, either because calling them
14697 multiple time is unsafe, or because it is bad style.  For instance
14698 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14699 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14700 sense to run these expensive checks more than once.  Such one-shot
14701 macros can be defined using @code{AC_DEFUN_ONCE}.
14703 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14704 @acindex{DEFUN_ONCE}
14705 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14706 Definitions}), but add additional logic that guarantees that only the
14707 first use of the macro (whether by direct expansion or
14708 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14709 expansion will occur before the start of any enclosing macro defined by
14710 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14711 Generally, it does not make sense for @var{macro-body} to use parameters
14712 such as @code{$1}.
14713 @end defmac
14715 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14716 emit a warning if it was directly expanded a second time, so for
14717 portability, it is better to use @code{AC_REQUIRE} than direct
14718 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14719 (@pxref{Prerequisite Macros}).
14721 @node Obsoleting Macros
14722 @section Obsoleting Macros
14723 @cindex Obsoleting macros
14724 @cindex Macros, obsoleting
14726 Configuration and portability technology has evolved over the years.
14727 Often better ways of solving a particular problem are developed, or
14728 ad-hoc approaches are systematized.  This process has occurred in many
14729 parts of Autoconf.  One result is that some of the macros are now
14730 considered @dfn{obsolete}; they still work, but are no longer considered
14731 the best thing to do, hence they should be replaced with more modern
14732 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14733 with their modern implementation.
14735 Autoconf provides a simple means to obsolete a macro.
14737 @anchor{AU_DEFUN}
14738 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14739 @auindex{DEFUN}
14740 Define @var{old-macro} as @var{implementation}.  The only difference
14741 with @code{AC_DEFUN} is that the user is warned that
14742 @var{old-macro} is now obsolete.
14744 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14745 replaced by the modern @var{implementation}.  @var{message} should
14746 include information on what to do after running @command{autoupdate};
14747 @command{autoupdate} prints it as a warning, and includes it
14748 in the updated @file{configure.ac} file.
14750 The details of this macro are hairy: if @command{autoconf} encounters an
14751 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14752 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14753 macros are expanded here, while all other macros are disabled and
14754 appear literally in the updated @file{configure.ac}.
14755 @end defmac
14757 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14758 @auindex{ALIAS}
14759 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14760 with the same parameters.  This happens for example if the macro was renamed.
14761 @end defmac
14763 @node Coding Style
14764 @section Coding Style
14765 @cindex Coding style
14767 The Autoconf macros follow a strict coding style.  You are encouraged to
14768 follow this style, especially if you intend to distribute your macro,
14769 either by contributing it to Autoconf itself or the
14770 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14771 Archive}, or by other means.
14773 The first requirement is to pay great attention to the quotation.  For
14774 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14776 Do not try to invent new interfaces.  It is likely that there is a macro
14777 in Autoconf that resembles the macro you are defining: try to stick to
14778 this existing interface (order of arguments, default values, etc.).  We
14779 @emph{are} conscious that some of these interfaces are not perfect;
14780 nevertheless, when harmless, homogeneity should be preferred over
14781 creativity.
14783 Be careful about clashes both between M4 symbols and between shell
14784 variables.
14786 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14787 you are unlikely to generate conflicts.  Nevertheless, when you need to
14788 set a special value, @emph{avoid using a regular macro name}; rather,
14789 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14790 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14791 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14792 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14793 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14794 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14795 have been used (yes, with the parentheses).
14796 @c or better yet, high-level macros such as @code{m4_expand_once}
14798 No Autoconf macro should ever enter the user-variable name space; i.e.,
14799 except for the variables that are the actual result of running the
14800 macro, all shell variables should start with @code{ac_}.  In
14801 addition, small macros or any macro that is likely to be embedded in
14802 other macros should be careful not to use obvious names.
14804 @cindex @code{dnl}
14805 Do not use @code{dnl} to introduce comments: most of the comments you
14806 are likely to write are either header comments which are not output
14807 anyway, or comments that should make their way into @file{configure}.
14808 There are exceptional cases where you do want to comment special M4
14809 constructs, in which case @code{dnl} is right, but keep in mind that it
14810 is unlikely.
14812 M4 ignores the leading blanks and newlines before each argument.
14813 Use this feature to
14814 indent in such a way that arguments are (more or less) aligned with the
14815 opening parenthesis of the macro being called.  For instance, instead of
14817 @example
14818 AC_CACHE_CHECK(for EMX OS/2 environment,
14819 ac_cv_emxos2,
14820 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14821 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14822 @end example
14824 @noindent
14825 write
14827 @example
14828 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14829 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14830                    [ac_cv_emxos2=yes],
14831                    [ac_cv_emxos2=no])])
14832 @end example
14834 @noindent
14835 or even
14837 @example
14838 AC_CACHE_CHECK([for EMX OS/2 environment],
14839                [ac_cv_emxos2],
14840                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14841                                                    [return __EMX__;])],
14842                                   [ac_cv_emxos2=yes],
14843                                   [ac_cv_emxos2=no])])
14844 @end example
14846 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14847 cross-compiling, provide a pessimistic value (typically @samp{no}).
14849 Feel free to use various tricks to prevent auxiliary tools, such as
14850 syntax-highlighting editors, from behaving improperly.  For instance,
14851 instead of:
14853 @example
14854 m4_bpatsubst([$1], [$"])
14855 @end example
14857 @noindent
14860 @example
14861 m4_bpatsubst([$1], [$""])
14862 @end example
14864 @noindent
14865 so that Emacsen do not open an endless ``string'' at the first quote.
14866 For the same reasons, avoid:
14868 @example
14869 test $[#] != 0
14870 @end example
14872 @noindent
14873 and use:
14875 @example
14876 test $[@@%:@@] != 0
14877 @end example
14879 @noindent
14880 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14881 breaking the bracket-matching highlighting from Emacsen.  Note the
14882 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14883 not escape when it is unnecessary.  Common examples of useless quotation
14884 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14885 etc.  If you add portability issues to the picture, you'll prefer
14886 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14887 better than hacking Autoconf @code{:-)}.
14889 When using @command{sed}, don't use @option{-e} except for indenting
14890 purposes.  With the @code{s} and @code{y} commands, the preferred
14891 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14892 or replacement, in which case you should use @samp{|}, or optionally
14893 @samp{,} if you know the pattern and replacement cannot contain a file
14894 name.  If none of these characters will do, choose a printable character
14895 that cannot appear in the pattern or replacement.  Characters from the
14896 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14897 replacement might contain a file name, since they have special meaning
14898 to the shell and are less likely to occur in file names.
14900 @xref{Macro Definitions}, for details on how to define a macro.  If a
14901 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14902 of an @code{AC_REQUIRE} directive, and macros required by other macros
14903 inside arguments do not need to be expanded before this macro, then
14904 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14905 Also take into account that public third-party macros need to use
14906 @code{AC_DEFUN} in order to be found by @command{aclocal}
14907 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14908 All the @code{AC_REQUIRE} statements should be at the beginning of the
14909 macro, and each statement should be followed by @code{dnl}.
14911 You should not rely on the number of arguments: instead of checking
14912 whether an argument is missing, test that it is not empty.  It provides
14913 both a simpler and a more predictable interface to the user, and saves
14914 room for further arguments.
14916 Unless the macro is short, try to leave the closing @samp{])} at the
14917 beginning of a line, followed by a comment that repeats the name of the
14918 macro being defined.  This introduces an additional newline in
14919 @command{configure}; normally, that is not a problem, but if you want to
14920 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14921 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14922 is recommended instead of @samp{dnl} to ensure that M4 does not
14923 interpret the @samp{dnl} as being attached to the preceding text or
14924 macro output.  For example, instead of:
14926 @example
14927 AC_DEFUN([AC_PATH_X],
14928 [AC_MSG_CHECKING([for X])
14929 AC_REQUIRE_CPP()
14930 @r{# @dots{}omitted@dots{}}
14931   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14932 fi])
14933 @end example
14935 @noindent
14936 you would write:
14938 @example
14939 AC_DEFUN([AC_PATH_X],
14940 [AC_REQUIRE_CPP()[]dnl
14941 AC_MSG_CHECKING([for X])
14942 @r{# @dots{}omitted@dots{}}
14943   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14944 fi[]dnl
14945 ])# AC_PATH_X
14946 @end example
14948 If the macro is long, try to split it into logical chunks.  Typically,
14949 macros that check for a bug in a function and prepare its
14950 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14951 this setup.  Do not hesitate to introduce auxiliary macros to factor
14952 your code.
14954 In order to highlight the recommended coding style, here is a macro
14955 written the old way:
14957 @example
14958 dnl Check for EMX on OS/2.
14959 dnl _AC_EMXOS2
14960 AC_DEFUN(_AC_EMXOS2,
14961 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14962 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14963 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14964 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14965 @end example
14967 @noindent
14968 and the new way:
14970 @example
14971 # _AC_EMXOS2
14972 # ----------
14973 # Check for EMX on OS/2.
14974 m4_define([_AC_EMXOS2],
14975 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14976 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14977                    [ac_cv_emxos2=yes],
14978                    [ac_cv_emxos2=no])])
14979 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14980 ])# _AC_EMXOS2
14981 @end example
14986 @c ============================================= Portable Shell Programming
14988 @node Portable Shell
14989 @chapter Portable Shell Programming
14990 @cindex Portable shell programming
14992 When writing your own checks, there are some shell-script programming
14993 techniques you should avoid in order to make your code portable.  The
14994 Bourne shell and upward-compatible shells like the Korn shell and Bash
14995 have evolved over the years, and many features added to the original
14996 System7 shell are now supported on all interesting porting targets.
14997 However, the following discussion between Russ Allbery and Robert Lipe
14998 is worth reading:
15000 @noindent
15001 Russ Allbery:
15003 @quotation
15004 The GNU assumption that @command{/bin/sh} is the one and only shell
15005 leads to a permanent deadlock.  Vendors don't want to break users'
15006 existing shell scripts, and there are some corner cases in the Bourne
15007 shell that are not completely compatible with a Posix shell.  Thus,
15008 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15009 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15010 Posix shell.
15011 @end quotation
15013 @noindent
15014 Robert Lipe:
15016 @quotation
15017 This is exactly the problem.  While most (at least most System V's) do
15018 have a Bourne shell that accepts shell functions most vendor
15019 @command{/bin/sh} programs are not the Posix shell.
15021 So while most modern systems do have a shell @emph{somewhere} that meets the
15022 Posix standard, the challenge is to find it.
15023 @end quotation
15025 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15026 is to find such a shell.  But to prevent trouble, if you're not using
15027 M4sh you should not take advantage of features that were added after Unix
15028 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15029 negated character classes, or even @command{unset}.  @code{#} comments,
15030 while not in Unix version 7, were retrofitted in the original Bourne
15031 shell and can be assumed to be part of the least common denominator.
15033 On the other hand, if you're using M4sh you can assume that the shell
15034 has the features that were added in SVR2 (circa 1984), including shell
15035 functions,
15036 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15037 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15038 However, some pitfalls have to be avoided for portable use of these
15039 constructs; these will be documented in the rest of this chapter.
15040 See in particular @ref{Shell Functions} and @ref{Limitations of
15041 Builtins, , Limitations of Shell Builtins}.
15043 Some ancient systems have quite
15044 small limits on the length of the @samp{#!} line; for instance, 32
15045 bytes (not including the newline) on SunOS 4.
15046 However, these ancient systems are no longer of practical concern.
15048 The set of external programs you should run in a @command{configure} script
15049 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15050 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15051 restriction allows users to start out with a fairly small set of
15052 programs and build the rest, avoiding too many interdependencies between
15053 packages.
15055 Some of these external utilities have a portable subset of features; see
15056 @ref{Limitations of Usual Tools}.
15058 There are other sources of documentation about shells.  The
15059 specification for the Posix
15060 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15061 Command Language}, though more generous than the restrictive shell
15062 subset described above, is fairly portable nowadays.  Also please see
15063 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15065 @menu
15066 * Shellology::                  A zoology of shells
15067 * Invoking the Shell::          Invoking the shell as a command
15068 * Here-Documents::              Quirks and tricks
15069 * File Descriptors::            FDs and redirections
15070 * Signal Handling::             Shells, signals, and headaches
15071 * File System Conventions::     File names
15072 * Shell Pattern Matching::      Pattern matching
15073 * Shell Substitutions::         Variable and command expansions
15074 * Assignments::                 Varying side effects of assignments
15075 * Parentheses::                 Parentheses in shell scripts
15076 * Slashes::                     Slashes in shell scripts
15077 * Special Shell Variables::     Variables you should not change
15078 * Shell Functions::             What to look out for if you use them
15079 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15080 * Limitations of Usual Tools::  Portable use of portable tools
15081 @end menu
15083 @node Shellology
15084 @section Shellology
15085 @cindex Shellology
15087 There are several families of shells, most prominently the Bourne family
15088 and the C shell family which are deeply incompatible.  If you want to
15089 write portable shell scripts, avoid members of the C shell family.  The
15090 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15091 Shell difference FAQ} includes a small history of Posix shells, and a
15092 comparison between several of them.
15094 Below we describe some of the members of the Bourne shell family.
15096 @table @asis
15097 @item Ash
15098 @cindex Ash
15099 Ash is often used on GNU/Linux and BSD
15100 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15101 bugs that are fixed in the 0.3.x series, but portable shell scripts
15102 should work around them, since version 0.2 is still shipped with many
15103 GNU/Linux distributions.
15105 To be compatible with Ash 0.2:
15107 @itemize @minus
15108 @item
15109 don't use @samp{$?} after expanding empty or unset variables,
15110 or at the start of an @command{eval}:
15112 @example
15113 foo=
15114 false
15115 $foo
15116 echo "Do not use it: $?"
15117 false
15118 eval 'echo "Do not use it: $?"'
15119 @end example
15121 @item
15122 don't use command substitution within variable expansion:
15124 @example
15125 cat $@{FOO=`bar`@}
15126 @end example
15128 @item
15129 beware that single builtin substitutions are not performed by a
15130 subshell, hence their effect applies to the current shell!  @xref{Shell
15131 Substitutions}, item ``Command Substitution''.
15132 @end itemize
15134 @item Bash
15135 @cindex Bash
15136 To detect whether you are running Bash, test whether
15137 @code{BASH_VERSION} is set.  To require
15138 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15139 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15140 Manual}, for details.
15142 @item Bash 2.05 and later
15143 @cindex Bash 2.05 and later
15144 Versions 2.05 and later of Bash use a different format for the
15145 output of the @command{set} builtin, designed to make evaluating its
15146 output easier.  However, this output is not compatible with earlier
15147 versions of Bash (or with many other shells, probably).  So if
15148 you use Bash 2.05 or higher to execute @command{configure},
15149 you'll need to use Bash 2.05 for all other build tasks as well.
15151 @item Ksh
15152 @cindex Ksh
15153 @cindex Korn shell
15154 @prindex @samp{ksh}
15155 @prindex @samp{ksh88}
15156 @prindex @samp{ksh93}
15157 The Korn shell is compatible with the Bourne family and it mostly
15158 conforms to Posix.  It has two major variants commonly
15159 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15160 release.  It is usually called @command{ksh}, but is called @command{sh}
15161 on some hosts if you set your path appropriately.
15163 Solaris systems have three variants:
15164 @prindex @command{/usr/bin/ksh} on Solaris
15165 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15166 standard on Solaris 2.0 and later.
15167 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15168 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15169 @samp{ksh88}; it is standard on Solaris 9 and later.
15170 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15171 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15172 Variants that are not standard may be parts of optional
15173 packages.  There is no extra charge for these packages, but they are
15174 not part of a minimal OS install and therefore some installations may
15175 not have it.
15177 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15178 is also available as @command{/usr/bin/posix/sh}.  If the environment
15179 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15180 the standard shell conform to Posix.
15182 @item Pdksh
15183 @prindex @samp{pdksh}
15184 A public-domain clone of the Korn shell called @command{pdksh} is widely
15185 available: it has most of the @samp{ksh88} features along with a few of
15186 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15187 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15188 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15189 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15190 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15191 at least one respect, see @ref{Shell Substitutions}.
15193 @item Zsh
15194 @cindex Zsh
15195 To detect whether you are running @command{zsh}, test whether
15196 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15197 compatible with the Bourne shell: you must execute @samp{emulate sh},
15198 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15199 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15200 zsh, The Z Shell Manual}, for details.
15202 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15203 Bash in Mac OS X 10.2.
15204 @end table
15206 @node Invoking the Shell
15207 @section Invoking the Shell
15208 @cindex invoking the shell
15209 @cindex shell invocation
15211 The Korn shell (up to at least version M-12/28/93d) has a bug when
15212 invoked on a file whose name does not contain a slash.  It first
15213 searches for the file's name in @env{PATH}, and if found it executes
15214 that rather than the original file.  For example, assuming there is a
15215 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15216 command in the following example fails because the Korn shell finds
15217 @file{/usr/bin/script} and refuses to execute it as a shell script:
15219 @example
15220 $ @kbd{touch xxyzzyz script}
15221 $ @kbd{ksh xxyzzyz}
15222 $ @kbd{ksh ./script}
15223 $ @kbd{ksh script}
15224 ksh: script: cannot execute
15225 @end example
15227 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15228 option-argument ends in backslash-newline, Bash incorrectly reports a
15229 syntax error.  The problem does not occur if a character follows the
15230 backslash:
15232 @example
15233 $ @kbd{$ bash -c 'echo foo \}
15234 > @kbd{'}
15235 bash: -c: line 2: syntax error: unexpected end of file
15236 $ @kbd{bash -c 'echo foo \}
15237 > @kbd{ '}
15239 @end example
15241 @noindent
15242 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15244 @node Here-Documents
15245 @section Here-Documents
15246 @cindex Here-documents
15247 @cindex Shell here-documents
15249 Don't rely on @samp{\} being preserved just because it has no special
15250 meaning together with the next symbol.  In the native @command{sh}
15251 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15252 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15253 use @samp{\\} to get @samp{\}.
15255 With OpenBSD 2.7's @command{sh}
15257 @example
15258 @group
15259 $ @kbd{cat <<EOF
15260 > \" \\
15261 > EOF}
15262 " \
15263 @end group
15264 @end example
15266 @noindent
15267 and with Bash:
15269 @example
15270 @group
15271 bash-2.04$ @kbd{cat <<EOF
15272 > \" \\
15273 > EOF}
15274 \" \
15275 @end group
15276 @end example
15278 Using command substitutions in a here-document that is fed to a shell
15279 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15281 @example
15282 $ @kbd{kitty () @{ cat; @}}
15283 $ @kbd{kitty <<EOF
15284 > `echo ok`
15285 > EOF}
15286 /tmp/sh199886: cannot open
15287 $ @kbd{echo $?}
15289 @end example
15291 Some shells mishandle large here-documents: for example,
15292 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15293 derived from Korn shell version M-12/28/93d, mishandle braced variable
15294 expansion that crosses a 1024- or 4096-byte buffer boundary
15295 within a here-document.  Only the part of the variable name after the boundary
15296 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15297 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15298 boundary, the shell reports an error, as if you used @code{$@{@}}.
15299 Instead of @code{$@{variable-default@}}, the shell may expand
15300 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15301 be worked around by omitting the braces: @code{$variable}.  The bug was
15302 fixed in
15303 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15304 still shipping older versions with the bug.
15306 Empty here-documents are not portable either; with the following code,
15307 @command{zsh} up to at least version 4.3.10 creates a file with a single
15308 newline, whereas other shells create an empty file:
15310 @example
15311 cat >file <<EOF
15313 @end example
15315 Many shells (including the Bourne shell) implement here-documents
15316 inefficiently.  In particular, some shells can be extremely inefficient when
15317 a single statement contains many here-documents.  For instance if your
15318 @file{configure.ac} includes something like:
15320 @example
15321 @group
15322 if <cross_compiling>; then
15323   assume this and that
15324 else
15325   check this
15326   check that
15327   check something else
15328   @dots{}
15329   on and on forever
15330   @dots{}
15332 @end group
15333 @end example
15335 A shell parses the whole @code{if}/@code{fi} construct, creating
15336 temporary files for each here-document in it.  Some shells create links
15337 for such here-documents on every @code{fork}, so that the clean-up code
15338 they had installed correctly removes them.  It is creating the links
15339 that can take the shell forever.
15341 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15342 @code{if}/@code{fi} constructs, would improve the performance
15343 significantly.  Anyway, this kind of construct is not exactly the
15344 typical use of Autoconf.  In fact, it's even not recommended, because M4
15345 macros can't look into shell conditionals, so we may fail to expand a
15346 macro when it was expanded before in a conditional path, and the
15347 condition turned out to be false at runtime, and we end up not
15348 executing the macro at all.
15350 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15351 behavior is only portable for stripping leading @key{TAB}s, and things
15352 can silently break if an overzealous editor converts to using leading
15353 spaces (not all shells are nice enough to warn about unterminated
15354 here-documents).
15356 @example
15357 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15360 done
15361 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15363   2
15365 done
15366 @end example
15368 @node File Descriptors
15369 @section File Descriptors
15370 @cindex Descriptors
15371 @cindex File descriptors
15372 @cindex Shell file descriptors
15374 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15375 stderr, even for subshells.  This might result in undesirable content
15376 if you meant to capture the standard-error output of the inner command:
15378 @example
15379 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15380 $ @kbd{cat stderr}
15381 + eval echo foo >&2
15382 + echo foo
15384 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15385 $ @kbd{cat stderr}
15386 + eval 'echo foo >&2'
15387 ++ echo foo
15389 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15390 @i{# Traces on startup files deleted here.}
15391 $ @kbd{cat stderr}
15392 +zsh:1> eval echo foo >&2
15393 +zsh:1> echo foo
15395 @end example
15397 @noindent
15398 One workaround is to grep out uninteresting lines, hoping not to remove
15399 good ones.
15401 If you intend to redirect both standard error and standard output,
15402 redirect standard output first.  This works better with HP-UX,
15403 since its shell mishandles tracing if standard error is redirected
15404 first:
15406 @example
15407 $ @kbd{sh -x -c ': 2>err >out'}
15408 + :
15409 + 2> err $ @kbd{cat err}
15410 1> out
15411 @end example
15413 Don't try to redirect the standard error of a command substitution.  It
15414 must be done @emph{inside} the command substitution.  When running
15415 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15416 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15418 On the other hand, some shells, such as Solaris or FreeBSD
15419 @command{/bin/sh}, warn about missing programs before performing
15420 redirections.  Therefore, to silently check whether a program exists, it
15421 is necessary to perform redirections on a subshell or brace group:
15422 @example
15423 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15424 nosuch: not found
15425 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15426 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15427 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15428 @end example
15430 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15431 shell pipeline.
15433 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15434 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15436 Some shells, like @command{ash}, don't recognize bi-directional
15437 redirection (@samp{<>}).  And even on shells that recognize it, it is
15438 not portable to use on fifos: Posix does not require read-write support
15439 for named pipes, and Cygwin does not support it:
15441 @example
15442 $ @kbd{mkfifo fifo}
15443 $ @kbd{exec 5<>fifo}
15444 $ @kbd{echo hi >&5}
15445 bash: echo: write error: Communication error on send
15446 @end example
15448 @noindent
15449 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15450 regular files when using @samp{<>}:
15452 @example
15453 $ @kbd{echo a > file}
15454 $ @kbd{bash -c ': 1<>file'; cat file}
15456 $ @kbd{dash -c ': 1<>file'; cat file}
15457 $ rm a
15458 @end example
15460 When catering to old systems, don't redirect the same file descriptor
15461 several times, as you are doomed to failure under Ultrix.
15463 @example
15464 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15465 UWS V4.4 (Rev. 11)
15466 $ @kbd{eval 'echo matter >fullness' >void}
15467 illegal io
15468 $ @kbd{eval '(echo matter >fullness)' >void}
15469 illegal io
15470 $ @kbd{(eval '(echo matter >fullness)') >void}
15471 Ambiguous output redirect.
15472 @end example
15474 @noindent
15475 In each case the expected result is of course @file{fullness} containing
15476 @samp{matter} and @file{void} being empty.  However, this bug is
15477 probably not of practical concern to modern platforms.
15479 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15480 (even if it is redirected) in a loop after the first iteration, or in a
15481 shell function after the first call:
15483 @example
15484 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15485 $ @kbd{ls x*}
15487 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15488 $ @kbd{ls y*}
15490 @end example
15492 @noindent
15493 As a workaround, @command{echo} or @command{eval} can be used.
15495 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15496 subsidiary program.  If any of these descriptors is closed, the
15497 operating system may open an unspecified file for the descriptor in the
15498 new process image.  Posix 2008 says this may be done only if the
15499 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15500 it even for ordinary programs, and the next version of Posix will allow
15501 HP-UX behavior.
15503 If you want a file descriptor above 2 to be inherited into a child
15504 process, then you must use redirections specific to that command or a
15505 containing subshell or command group, rather than relying on
15506 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15507 @command{sh}, file descriptors above 2 which are opened using
15508 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15509 that involved in the fork-and-exec which runs a program or script):
15511 @example
15512 $ @kbd{echo 'echo hello >&5' >k}
15513 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15514 hello
15515 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15516 hello
15517 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15518 ./k[1]: 5: cannot open [Bad file number]
15519 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15520 hello
15521 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15522 hello
15523 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15524 hello
15525 @end example
15527 Don't rely on duplicating a closed file descriptor to cause an
15528 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15529 ignored, which can cause unintended leaks to the original file
15530 descriptor.  In this example, observe the leak to standard output:
15532 @example
15533 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15534 bash: 3: Bad file descriptor
15536 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15539 @end example
15541 Fortunately, an attempt to close an already closed file descriptor will
15542 portably succeed.  Likewise, it is safe to use either style of
15543 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15544 even if it doesn't match the read/write mode that the file descriptor
15545 was opened with.
15547 DOS variants cannot rename or remove open files, such as in
15548 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15549 perfectly portable among Posix hosts.
15551 A few ancient systems reserved some file descriptors.  By convention,
15552 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15553 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15554 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15555 1990), though we don't now remember what it was.  Both these systems are
15556 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15557 other file descriptors.
15559 On the other hand, you can't portably use multi-digit file descriptors.
15560 Solaris @command{ksh} doesn't understand any file descriptor larger than
15561 @samp{9}:
15563 @example
15564 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15566 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15568 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15569 ksh[1]: exec: 10: not found
15571 @end example
15573 @c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15574 @node Signal Handling
15575 @section Signal Handling
15576 @cindex Signal handling in the shell
15577 @cindex Signals, shells and
15579 Portable handling of signals within the shell is another major source of
15580 headaches.  This is worsened by the fact that various different, mutually
15581 incompatible approaches are possible in this area, each with its
15582 distinctive merits and demerits.  A detailed description of these possible
15583 approaches, as well as of their pros and cons, can be found in
15584 @uref{http://www.cons.org/cracauer/sigint.html, this article}.
15586 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15587 @c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15588 the shell still exits with error upon termination by one of those signals,
15589 but in such a case the exit status might be somewhat unexpected (even if
15590 allowed by POSIX, strictly speaking):
15592 @example
15593 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15594 Hangup
15596 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15597 Terminated
15599 $ @kbd{for sig in 1 2 3 15; do}
15600 > @kbd{  echo $sig:}
15601 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15602 > @kbd{done}
15603 signal 1:
15604 Hangup
15606 signal 2:
15608 signal 3:
15610 signal 15:
15612 @end example
15614 This gets even worse if one is using the POSIX `wait' interface to get
15615 details about the shell process terminations: it will result in the shell
15616 having exited normally, rather than by receiving a signal.
15618 @example
15619 $ @kbd{cat > foo.c <<'END'}
15620 #include <stdio.h>    /* for printf */
15621 #include <stdlib.h>   /* for system */
15622 #include <sys/wait.h> /* for WIF* macros */
15623 int main(void)
15625   int status = system ("kill -15 $$");
15626   printf ("Terminated by signal: %s\n",
15627           WIFSIGNALED (status) ? "yes" : "no");
15628   printf ("Exited normally: %s\n",
15629           WIFEXITED (status) ? "yes" : "no");
15630   return 0;
15633 @c $$ font-lock
15634 $ @kbd{cc -o foo foo.c}
15635 $ @kbd{./a.out} # On GNU/Linux
15636 Terminated by signal: no
15637 Exited normally: yes
15638 $ @kbd{./a.out} # On Solaris 10
15639 Terminated by signal: yes
15640 Exited normally: no
15641 @end example
15643 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15644 if it is not blocked, and even if the shell is not running interactively
15645 (in fact, even if the shell has no attached tty); among these shells
15646 are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15647 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15648 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15649 these shells.  OTOH, some other shells doesn't special-case the handling
15650 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15651 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15653 @c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15654 Some shells (especially Korn shells and derivatives) might try to
15655 propagate to themselves a signal that has killed a child process; this is
15656 not a bug, but a conscious design choice (although its overall value might
15657 be debatable).  The exact details of how this is attained vary from shell
15658 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15659 the perl process has been interrupted AT&T @code{ksh93} (2011) will
15660 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15661 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15662 128 + 2). In any case, if there is an active trap associated with
15663 @code{SIGINT}, those shells will correctly execute it.
15665 @c See: <http://www.austingroupbugs.net/view.php?id=51>
15666 Some Korn shells, when a child process die due receiving a signal with
15667 signal number @var{n}, can leave in @samp{$?} an exit status of
15668 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15669 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15670 Debian:
15672 @example
15673 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15674 /bin/ksh: line 1: 7837: Hangup
15676 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15677 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15679 @end example
15681 @noindent
15682 This @command{ksh} behavior is allowed by POSIX, if implemented with
15683 due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15684 Austin Group discussion} for more background.  However, if it is not
15685 implemented with proper care, such a behavior might cause problems
15686 in some corner cases.  To see why, assume we have a ``wrapper'' script
15687 like this:
15689 @example
15690 #!/bin/sh
15691 # Ignore some signals in the shell only, not in its child processes.
15692 trap : 1 2 13 15
15693 wrapped_command "$@@"
15694 ret=$?
15695 other_command
15696 exit $ret
15697 @end example
15699 @noindent
15700 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15701 has signal number 1), @code{ret} will be set to 257.  Unless the
15702 @command{exit} shell builtin is smart enough to understand that such
15703 a value can only have originated from a signal, and adjust the final
15704 wait status of the shell appropriately, the value 257 will just get
15705 truncated to 1 by the closing @code{exit} call, so that a caller of
15706 the script will have no way to determine that termination by a signal
15707 was involved.  Observe the different behavior of AT&T @code{ksh93}
15708 (2011) and @code{bash} 4.1.5 on Debian:
15710 @example
15711 $ @kbd{cat foo.sh}
15712 #!/bin/sh
15713 sh -c 'kill -1 $$'
15714 ret=$?
15715 echo $ret
15716 exit $ret
15717 $ @kbd{/bin/ksh foo.sh; echo $?}
15718 foo.sh: line 2: 12479: Hangup
15721 $ @kbd{/bin/bash foo.sh; echo $?}
15722 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15725 @end example
15727 @node File System Conventions
15728 @section File System Conventions
15729 @cindex File system conventions
15731 Autoconf uses shell-script processing extensively, so the file names
15732 that it processes should not contain characters that are special to the
15733 shell.  Special characters include space, tab, newline, NUL, and
15734 the following:
15736 @example
15737 " # $ & ' ( ) * ; < = > ? [ \ ` |
15738 @end example
15740 Also, file names should not begin with @samp{~} or @samp{-}, and should
15741 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15742 immediately after @samp{:}.  On Posix-like platforms, directory names
15743 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15744 path separator.
15746 These restrictions apply not only to the files that you distribute, but
15747 also to the absolute file names of your source, build, and destination
15748 directories.
15750 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15751 they should be avoided.
15753 Posix lets implementations treat leading @file{//} specially, but
15754 requires leading @file{///} and beyond to be equivalent to @file{/}.
15755 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15756 @file{//} as a ``super-root'' that can provide access to files that are
15757 not otherwise reachable from @file{/}.  The super-root tradition began
15758 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15759 has revived it.
15761 While @command{autoconf} and friends are usually run on some Posix
15762 variety, they can be used on other systems, most notably DOS
15763 variants.  This impacts several assumptions regarding file names.
15765 @noindent
15766 For example, the following code:
15768 @example
15769 case $foo_dir in
15770   /*) # Absolute
15771      ;;
15772   *)
15773      foo_dir=$dots$foo_dir ;;
15774 esac
15775 @end example
15777 @noindent
15778 fails to properly detect absolute file names on those systems, because
15779 they can use a drivespec, and usually use a backslash as directory
15780 separator.  If you want to be portable to DOS variants (at the
15781 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15782 you can check for absolute file names like this:
15784 @cindex absolute file names, detect
15785 @example
15786 case $foo_dir in
15787   [\\/]* | ?:[\\/]* ) # Absolute
15788      ;;
15789   *)
15790      foo_dir=$dots$foo_dir ;;
15791 esac
15792 @end example
15794 @noindent
15795 Make sure you quote the brackets if appropriate and keep the backslash as
15796 first character (@pxref{case, , Limitations of Shell Builtins}).
15798 Also, because the colon is used as part of a drivespec, these systems don't
15799 use it as path separator.  When creating or accessing paths, you can use the
15800 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15801 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15802 starts up.
15804 File names need extra care as well.  While DOS variants
15805 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15806 are usually able to handle long file names properly, there are still
15807 limitations that can seriously break packages.  Several of these issues
15808 can be easily detected by the
15809 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15810 package.
15812 A short overview follows; problems are marked with SFN/LFN to
15813 indicate where they apply: SFN means the issues are only relevant to
15814 plain DOS, not to DOS under Microsoft Windows
15815 variants, while LFN identifies problems that exist even under
15816 Microsoft Windows variants.
15818 @table @asis
15819 @item No multiple dots (SFN)
15820 DOS cannot handle multiple dots in file names.  This is an especially
15821 important thing to remember when building a portable configure script,
15822 as @command{autoconf} uses a .in suffix for template files.
15824 This is perfectly OK on Posix variants:
15826 @example
15827 AC_CONFIG_HEADERS([config.h])
15828 AC_CONFIG_FILES([source.c foo.bar])
15829 AC_OUTPUT
15830 @end example
15832 @noindent
15833 but it causes problems on DOS, as it requires @samp{config.h.in},
15834 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15835 to DOS-based environments, you should use this instead:
15837 @example
15838 AC_CONFIG_HEADERS([config.h:config.hin])
15839 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15840 AC_OUTPUT
15841 @end example
15843 @item No leading dot (SFN)
15844 DOS cannot handle file names that start with a dot.  This is usually
15845 not important for @command{autoconf}.
15847 @item Case insensitivity (LFN)
15848 DOS is case insensitive, so you cannot, for example, have both a
15849 file called @samp{INSTALL} and a directory called @samp{install}.  This
15850 also affects @command{make}; if there's a file called @samp{INSTALL} in
15851 the directory, @samp{make install} does nothing (unless the
15852 @samp{install} target is marked as PHONY).
15854 @item The 8+3 limit (SFN)
15855 Because the DOS file system only stores the first 8 characters of
15856 the file name and the first 3 of the extension, those must be unique.
15857 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15858 @file{foobar-prettybird.c} all resolve to the same file name
15859 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15860 @file{foo.bartender}.
15862 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15863 uses numeric
15864 tails in the short version of file names to make them unique.  However, a
15865 registry setting can turn this behavior off.  While this makes it
15866 possible to share file trees containing long file names between SFN
15867 and LFN environments, it also means the above problem applies there
15868 as well.
15870 @item Invalid characters (LFN)
15871 Some characters are invalid in DOS file names, and should therefore
15872 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15873 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15874 In a SFN environment, other characters are also invalid.  These
15875 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15877 @item Invalid names (LFN)
15878 Some DOS file names are reserved, and cause problems if you
15879 try to use files with those names.  These names include @file{CON},
15880 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15881 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15882 File names are case insensitive, so even names like
15883 @file{aux/config.guess} are disallowed.
15885 @end table
15887 @node Shell Pattern Matching
15888 @section Shell Pattern Matching
15889 @cindex Shell pattern matching
15891 Nowadays portable patterns can use negated character classes like
15892 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15893 some shells but not others; hence portable scripts should never use
15894 @samp{^} as the first character of a bracket pattern.
15896 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15897 they may match characters that are not lower-case letters.
15899 @node Shell Substitutions
15900 @section Shell Substitutions
15901 @cindex Shell substitutions
15903 Contrary to a persistent urban legend, the Bourne shell does not
15904 systematically split variables and back-quoted expressions, in particular
15905 on the right-hand side of assignments and in the argument of @code{case}.
15906 For instance, the following code:
15908 @example
15909 case "$given_srcdir" in
15910 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15911 *)  top_srcdir="$dots$given_srcdir" ;;
15912 esac
15913 @end example
15915 @noindent
15916 is more readable when written as:
15918 @example
15919 case $given_srcdir in
15920 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15921 *)  top_srcdir=$dots$given_srcdir ;;
15922 esac
15923 @end example
15925 @noindent
15926 and in fact it is even @emph{more} portable: in the first case of the
15927 first attempt, the computation of @code{top_srcdir} is not portable,
15928 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15929 for example Solaris 10 ksh:
15931 @example
15932 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15933 ksh: : cannot execute
15934 ksh: bar | sed 's, ,,': cannot execute
15935 @end example
15937 @noindent
15938 Posix does not specify behavior for this sequence.  On the other hand,
15939 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15940 but in practice, not all shells understand it the same way: pdksh 5.2.14
15941 prints spurious quotes when in Posix mode:
15943 @example
15944 $ @kbd{echo "`echo \"hello\"`"}
15945 hello
15946 $ @kbd{set -o posix}
15947 $ @kbd{echo "`echo \"hello\"`"}
15948 "hello"
15949 @end example
15951 @noindent
15952 There is just no portable way to use double-quoted strings inside
15953 double-quoted back-quoted expressions (pfew!).
15955 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15956 parameter expansions are elided during word splitting.  Meanwhile, zsh
15957 does not perform word splitting except when in Bourne compatibility
15958 mode.  In the example below, the correct behavior is to have five
15959 arguments to the function, and exactly two spaces on either side of the
15960 middle @samp{-}, since word splitting collapses multiple spaces in
15961 @samp{$f} but leaves empty arguments intact.
15963 @example
15964 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15965 3- - -
15966 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15967 5-  -  -
15968 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15969 3-   -   -
15970 $ @kbd{zsh -c 'emulate sh;}
15971 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15972 5-  -  -
15973 @end example
15975 @noindent
15976 You can work around this by doing manual word splitting, such as using
15977 @samp{"$str" $list} rather than @samp{"$str"$list}.
15979 There are also portability pitfalls with particular expansions:
15981 @table @code
15982 @item $@@
15983 @cindex @code{"$@@"}
15984 One of the most famous shell-portability issues is related to
15985 @samp{"$@@"}.  When there are no positional arguments, Posix says
15986 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15987 original Unix version 7 Bourne shell treated it as equivalent to
15988 @samp{""} instead, and this behavior survives in later implementations
15989 like Digital Unix 5.0.
15991 The traditional way to work around this portability problem is to use
15992 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15993 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15994 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15996 @example
15997 zsh $ @kbd{emulate sh}
15998 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15999 Hello World
16001 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16002 Hello
16003 World
16005 @end example
16007 @noindent
16008 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16009 @samp{"$@@"} because of the portability problems mentioned above.
16010 One workaround relies on Zsh's ``global aliases'' to convert
16011 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16013 @example
16014 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
16015 @end example
16017 Zsh only recognizes this alias when a shell word matches it exactly;
16018 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16019 case always yields at least one shell word, use plain @samp{"$@@"}.
16021 A more conservative workaround is to avoid @samp{"$@@"} if it is
16022 possible that there may be no positional arguments.  For example,
16023 instead of:
16025 @example
16026 cat conftest.c "$@@"
16027 @end example
16029 you can use this instead:
16031 @example
16032 case $# in
16033 0) cat conftest.c;;
16034 *) cat conftest.c "$@@";;
16035 esac
16036 @end example
16038 Autoconf macros often use the @command{set} command to update
16039 @samp{$@@}, so if you are writing shell code intended for
16040 @command{configure} you should not assume that the value of @samp{$@@}
16041 persists for any length of time.
16044 @item $@{10@}
16045 @cindex positional parameters
16046 The 10th, 11th, @dots{} positional parameters can be accessed only after
16047 a @code{shift}.  The 7th Edition shell reported an error if given
16048 @code{$@{10@}}, and
16049 Solaris 10 @command{/bin/sh} still acts that way:
16051 @example
16052 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16053 $ @kbd{echo $@{10@}}
16054 bad substitution
16055 @end example
16057 Conversely, not all shells obey the Posix rule that when braces are
16058 omitted, multiple digits beyond a @samp{$} imply the single-digit
16059 positional parameter expansion concatenated with the remaining literal
16060 digits.  To work around the issue, you must use braces.
16062 @example
16063 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16064 a0 a0
16065 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16066 j a0
16067 @end example
16069 @item $@{@var{var}:-@var{value}@}
16070 @c Info cannot handle `:' in index entries.
16071 @ifnotinfo
16072 @cindex @code{$@{@var{var}:-@var{value}@}}
16073 @end ifnotinfo
16074 @cindex @code{$@{@var{var}-@var{value}@}}
16075 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16076 colon for any shell substitution, and complain and die.
16077 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
16078 However, all shells that support functions allow the use of colon in
16079 shell substitution, and since m4sh requires functions, you can portably
16080 use null variable substitution patterns in configure scripts.
16082 @item $@{@var{var}+@var{value}@}
16083 @cindex @code{$@{@var{var}+@var{value}@}}
16084 When using @samp{$@{@var{var}-@var{value}@}} or
16085 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16086 @var{value} must either be a single shell word, quoted, or in the
16087 context of an unquoted here-document.  Solaris
16088 @command{/bin/sh} complains otherwise.
16090 @example
16091 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16092 /bin/sh: bad substitution
16093 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16094 b c
16095 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16096 b c
16097 $ @kbd{/bin/sh -c 'cat <<EOF
16098 $@{a-b c@}
16099 EOF}
16100 b c
16101 @end example
16103 According to Posix, if an expansion occurs inside double quotes, then
16104 the use of unquoted double quotes within @var{value} is unspecified, and
16105 any single quotes become literal characters; in that case, escaping must
16106 be done with backslash.  Likewise, the use of unquoted here-documents is
16107 a case where double quotes have unspecified results:
16109 @example
16110 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16111 /bin/sh: bad substitution
16112 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16113 b c
16114 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16115 b  c
16116 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16117 b  c
16118 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16119 'b  c'
16120 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16121 "b  c"
16122 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16123 b  c
16124 $ @kbd{/bin/sh -c 'cat <<EOF
16125 $@{a-"b  c"@}
16126 EOF'}
16127 "b  c"
16128 $ @kbd{/bin/sh -c 'cat <<EOF
16129 $@{a-'b  c'@}
16130 EOF'}
16131 'b  c'
16132 $ @kbd{bash -c 'cat <<EOF
16133 $@{a-"b  c"@}
16134 EOF'}
16135 b  c
16136 $ @kbd{bash -c 'cat <<EOF
16137 $@{a-'b  c'@}
16138 EOF'}
16139 'b  c'
16140 @end example
16142 Perhaps the easiest way to work around quoting issues in a manner
16143 portable to all shells is to place the results in a temporary variable,
16144 then use @samp{$t} as the @var{value}, rather than trying to inline
16145 the expression needing quoting.
16147 @example
16148 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16149 b  c"'@}\
16150 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16151 b  c"'@}\
16152 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16153 b  c"'@}\
16154 @end example
16156 @item $@{@var{var}=@var{value}@}
16157 @cindex @code{$@{@var{var}=@var{value}@}}
16158 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16159 to @var{var}, remember that even though the assignment to @var{var} does
16160 not undergo file name expansion, the result of the variable expansion
16161 does unless the expansion occurred within double quotes.  In particular,
16162 when using @command{:} followed by unquoted variable expansion for the
16163 side effect of setting a default value, if the final value of
16164 @samp{$var} contains any globbing characters (either from @var{value} or
16165 from prior contents), the shell has to spend time performing file name
16166 expansion and field splitting even though those results will not be
16167 used.  Therefore, it is a good idea to consider double quotes when performing
16168 default initialization; while remembering how this impacts any quoting
16169 characters appearing in @var{value}.
16171 @example
16172 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16173 /usr/bin/*
16175 real    0m0.005s
16176 user    0m0.002s
16177 sys     0m0.003s
16178 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16179 /usr/bin/*
16181 real    0m0.039s
16182 user    0m0.026s
16183 sys     0m0.009s
16184 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16185 /usr/bin/*
16187 real    0m0.031s
16188 user    0m0.020s
16189 sys     0m0.010s
16191 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16192 /usr/bin/*
16194 real    0m0.006s
16195 user    0m0.002s
16196 sys     0m0.003s
16197 @end example
16199 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16200 if the @var{value} contains more than one shell word; either single
16201 quotes for just the @var{value}, or double quotes around the entire
16202 expansion:
16204 @example
16205 $ @kbd{: $@{var1='Some words'@}}
16206 $ @kbd{: "$@{var2=like this@}"}
16207 $ @kbd{echo $var1 $var2}
16208 Some words like this
16209 @end example
16211 @noindent
16212 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16213 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16214 requires that with @samp{=}, quote removal happens prior to the
16215 assignment, and the expansion be the final contents of @var{var} without
16216 quoting (and thus subject to field splitting), in contrast to the
16217 behavior with @samp{-} passing the quoting through to the final
16218 expansion.  However, @command{bash} 4.1 does not obey this rule.
16220 @example
16221 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16222 a  b
16223 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16224 a b
16225 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16226 a  b
16227 @end example
16229 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16230 commands, it is unspecified whether the assignments affect the parent
16231 shell environment.  It is best to perform assignments independently from
16232 commands, to avoid the problems demonstrated in this example:
16234 @example
16235 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16236 +b+b+
16238 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16239 ++b+
16241 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16242 +b+b+
16244 @end example
16246 @item $@{@var{var}=@var{value}@}
16247 @cindex @code{$@{@var{var}=@var{literal}@}}
16248 Solaris @command{/bin/sh} has a frightening bug in its handling of
16249 literal assignments.  Imagine you need set a variable to a string containing
16250 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16251 when the affected variable was already set.  This bug can be exercised
16252 by running:
16254 @example
16255 $ @kbd{unset foo}
16256 $ @kbd{foo=$@{foo='@}'@}}
16257 $ @kbd{echo $foo}
16259 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16260 $ @kbd{echo $foo}
16262 $ @kbd{foo=$@{foo='@}'@}}
16263 $ @kbd{echo $foo}
16264 @}@}
16265  ^ ugh!
16266 @end example
16268 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16269 though it is enclosed in single quotes.  The problem doesn't happen
16270 using double quotes, or when using a temporary variable holding the
16271 problematic string.
16273 @item $@{@var{var}=@var{expanded-value}@}
16274 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16275 On Ultrix,
16276 running
16278 @example
16279 default="yu,yaa"
16280 : $@{var="$default"@}
16281 @end example
16283 @noindent
16284 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16285 each char is set.  You don't observe the phenomenon using a simple
16286 @samp{echo $var} since apparently the shell resets the 8th bit when it
16287 expands $var.  Here are two means to make this shell confess its sins:
16289 @example
16290 $ @kbd{cat -v <<EOF
16291 $var
16292 EOF}
16293 @end example
16295 @noindent
16298 @example
16299 $ @kbd{set | grep '^var=' | cat -v}
16300 @end example
16302 One classic incarnation of this bug is:
16304 @example
16305 default="a b c"
16306 : $@{list="$default"@}
16307 for c in $list; do
16308   echo $c
16309 done
16310 @end example
16312 @noindent
16313 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16314 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16315 bit set, hence no IFS splitting is performed!!!
16317 One piece of good news is that Ultrix works fine with @samp{:
16318 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16319 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16320 @var{default}!
16322 The portable way out consists in using a double assignment, to switch
16323 the 8th bit twice on Ultrix:
16325 @example
16326 list=$@{list="$default"@}
16327 @end example
16329 @noindent
16330 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16331 use:
16333 @example
16334 test "$@{var+set@}" = set || var=@var{@{value@}}
16335 @end example
16337 @item $@{#@var{var}@}
16338 @itemx $@{@var{var}%@var{word}@}
16339 @itemx $@{@var{var}%%@var{word}@}
16340 @itemx $@{@var{var}#@var{word}@}
16341 @itemx $@{@var{var}##@var{word}@}
16342 @cindex @code{$@{#@var{var}@}}
16343 @cindex @code{$@{@var{var}%@var{word}@}}
16344 @cindex @code{$@{@var{var}%%@var{word}@}}
16345 @cindex @code{$@{@var{var}#@var{word}@}}
16346 @cindex @code{$@{@var{var}##@var{word}@}}
16347 Posix requires support for these usages, but they do not work with many
16348 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16350 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16351 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16352 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16353 yields the empty string.
16356 @item `@var{commands}`
16357 @cindex @code{`@var{commands}`}
16358 @cindex Command Substitution
16359 Posix requires shells to trim all trailing newlines from command
16360 output before substituting it, so assignments like
16361 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16362 @samp{$file} ends in a newline.
16364 While in general it makes no sense, do not substitute a single builtin
16365 with side effects, because Ash 0.2, trying to optimize, does not fork a
16366 subshell to perform the command.
16368 For instance, if you wanted to check that @command{cd} is silent, do not
16369 use @samp{test -z "`cd /`"} because the following can happen:
16371 @example
16372 $ @kbd{pwd}
16373 /tmp
16374 $ @kbd{test -z "`cd /`" && pwd}
16376 @end example
16378 @noindent
16379 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16381 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16382 command substitution of a native program, if the end of the substitution
16383 is not aligned with the end of the double quote.  This may be worked
16384 around by inserting another pair of quotes:
16386 @example
16387 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16388 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16389 - broken differ: char 4, line 1
16390 @end example
16392 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16393 replace it with a null string, and wrongly evaluate the enclosing
16394 command before entering the trap or ending the script.  This can lead to
16395 spurious errors:
16397 @example
16398 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16399 $ @kbd{^C}
16400 sh: test: hi: unexpected operator/operand
16401 @end example
16403 @noindent
16404 You can avoid this by assigning the command substitution to a temporary
16405 variable:
16407 @example
16408 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16409          if test "x$res" = xhi; then echo yes; fi'}
16410 $ @kbd{^C}
16411 @end example
16413 @item $(@var{commands})
16414 @cindex @code{$(@var{commands})}
16415 This construct is meant to replace @samp{`@var{commands}`},
16416 and it has most of the problems listed under @code{`@var{commands}`}.
16418 This construct can be
16419 nested while this is impossible to do portably with back quotes.
16420 Unfortunately it is not yet universally supported.  Most notably, even recent
16421 releases of Solaris don't support it:
16423 @example
16424 $ @kbd{showrev -c /bin/sh | grep version}
16425 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
16426 $ @kbd{echo $(echo blah)}
16427 syntax error: `(' unexpected
16428 @end example
16430 @noindent
16431 nor does IRIX 6.5's Bourne shell:
16432 @example
16433 $ @kbd{uname -a}
16434 IRIX firebird-image 6.5 07151432 IP22
16435 $ @kbd{echo $(echo blah)}
16436 $(echo blah)
16437 @end example
16439 If you do use @samp{$(@var{commands})}, make sure that the commands
16440 do not start with a parenthesis, as that would cause confusion with
16441 a different notation @samp{$((@var{expression}))} that in modern
16442 shells is an arithmetic expression not a command.  To avoid the
16443 confusion, insert a space between the two opening parentheses.
16445 Avoid @var{commands} that contain unbalanced parentheses in
16446 here-documents, comments, or case statement patterns, as many shells
16447 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16448 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16450 @example
16451 echo $(case x in x) echo hello;; esac)
16452 @end example
16455 @item $((@var{expression}))
16456 @cindex @code{$((@var{expression}))}
16457 Arithmetic expansion is not portable as some shells (most
16458 notably Solaris 10 @command{/bin/sh}) don't support it.
16460 Among shells that do support @samp{$(( ))}, not all of them obey the
16461 Posix rule that octal and hexadecimal constants must be recognized:
16463 @example
16464 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16466 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16468 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16470 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16471 pdksh:  010 + 0x10 : bad number `0x10'
16472 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16474 @end example
16476 When it is available, using arithmetic expansion provides a noticeable
16477 speedup in script execution; but testing for support requires
16478 @command{eval} to avoid syntax errors.  The following construct is used
16479 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16480 arguments are provided in decimal and without a leading zero, and all
16481 operators are properly quoted and appear as distinct arguments:
16483 @example
16484 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16485   eval 'func_arith ()
16486   @{
16487     func_arith_result=$(( $* ))
16488   @}'
16489 else
16490   func_arith ()
16491   @{
16492     func_arith_result=`expr "$@@"`
16493   @}
16495 func_arith 1 + 1
16496 foo=$func_arith_result
16497 @end example
16500 @item ^
16501 @cindex @code{^} quoting
16502 Always quote @samp{^}, otherwise traditional shells such as
16503 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16505 @end table
16508 @node Assignments
16509 @section Assignments
16510 @cindex Shell assignments
16512 When setting several variables in a row, be aware that the order of the
16513 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16514 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16515 You must use
16516 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16518 Don't rely on the following to find @file{subdir/program}:
16520 @example
16521 PATH=subdir$PATH_SEPARATOR$PATH program
16522 @end example
16524 @noindent
16525 as this does not work with Zsh 3.0.6.  Use something like this
16526 instead:
16528 @example
16529 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16530 @end example
16532 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16533 the status and propagates that of the last statement:
16535 @example
16536 $ @kbd{false || foo=bar; echo $?}
16538 $ @kbd{false || foo=`:`; echo $?}
16540 @end example
16542 @noindent
16543 and to make things even worse, QNX 4.25 just sets the exit status
16544 to 0 in any case:
16546 @example
16547 $ @kbd{foo=`exit 1`; echo $?}
16549 @end example
16551 To assign default values, follow this algorithm:
16553 @enumerate
16554 @item
16555 If the default value is a literal and does not contain any closing
16556 brace, use:
16558 @example
16559 : "$@{var='my literal'@}"
16560 @end example
16562 @item
16563 If the default value contains no closing brace, has to be expanded, and
16564 the variable being initialized is not intended to be IFS-split
16565 (i.e., it's not a list), then use:
16567 @example
16568 : $@{var="$default"@}
16569 @end example
16571 @item
16572 If the default value contains no closing brace, has to be expanded, and
16573 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16574 then use:
16576 @example
16577 var=$@{var="$default"@}
16578 @end example
16580 @item
16581 If the default value contains a closing brace, then use:
16583 @example
16584 test "$@{var+set@}" = set || var="has a '@}'"
16585 @end example
16586 @end enumerate
16588 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16589 doubt, just use the last form.  @xref{Shell Substitutions}, items
16590 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16591 for the rationale.
16593 @node Parentheses
16594 @section Parentheses in Shell Scripts
16595 @cindex Shell parentheses
16597 Beware of two opening parentheses in a row, as many shell
16598 implementations treat them specially, and Posix says that a portable
16599 script cannot use @samp{((} outside the @samp{$((} form used for shell
16600 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16601 @samp{(cat)}; but many shells, including
16602 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16603 expression equivalent to @samp{let "cat"}, and may or may not report an
16604 error when they detect that @samp{cat} is not a number.  As another
16605 example, @samp{pdksh} 5.2.14 does not treat the following code
16606 as a traditional shell would:
16608 @example
16609 if ((true) || false); then
16610   echo ok
16612 @end example
16614 @noindent
16615 To work around this problem, insert a space between the two opening
16616 parentheses.  There is a similar problem and workaround with
16617 @samp{$((}; see @ref{Shell Substitutions}.
16619 @node Slashes
16620 @section Slashes in Shell Scripts
16621 @cindex Shell slashes
16623 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16624 arguments that contain two trailing slashes:
16626 @example
16627 $ @kbd{echo / // /// //// .// //.}
16628 / / // /// ./ //.
16629 $ @kbd{x=//}
16630 $ @kbd{eval "echo \$x"}
16632 $ @kbd{set -x}
16633 $ @kbd{echo abc | tr -t ab //}
16634 + echo abc
16635 + tr -t ab /
16637 @end example
16639 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16640 variable is empty and the second double-quote is followed by a word that
16641 begins and ends with slash:
16643 @example
16644 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16646 + echo //ouch/
16647 //ouch/
16648 @end example
16650 However, our understanding is that patches are available, so perhaps
16651 it's not worth worrying about working around these horrendous bugs.
16653 @node Special Shell Variables
16654 @section Special Shell Variables
16655 @cindex Shell variables
16656 @cindex Special shell variables
16658 Some shell variables should not be used, since they can have a deep
16659 influence on the behavior of the shell.  In order to recover a sane
16660 behavior from the shell, some variables should be unset; M4sh takes
16661 care of this and provides fallback values, whenever needed, to cater
16662 for a very old @file{/bin/sh} that does not support @command{unset}.
16663 (@pxref{Portable Shell, , Portable Shell Programming}).
16665 As a general rule, shell variable names containing a lower-case letter
16666 are safe; you can define and use these variables without worrying about
16667 their effect on the underlying system, and without worrying about
16668 whether the shell changes them unexpectedly.  (The exception is the
16669 shell variable @code{status}, as described below.)
16671 Here is a list of names that are known to cause trouble.  This list is
16672 not exhaustive, but you should be safe if you avoid the name
16673 @code{status} and names containing only upper-case letters and
16674 underscores.
16676 @c Alphabetical order, case insensitive, `A' before `a'.
16677 @table @code
16678 @item ?
16679 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16680 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16681 correctly in shell functions (@pxref{Shell Functions}) or in traps
16682 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16683 @samp{$?} to zero after an empty command.
16685 @example
16686 $ @kbd{bash -c 'false; $empty; echo $?'}
16688 $ @kbd{zsh -c 'false; $empty; echo $?'}
16690 @end example
16692 @item _
16693 @evindex _
16694 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16695 the last command executed.
16697 @item BIN_SH
16698 @evindex BIN_SH
16699 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16700 the standard shell conform to Posix.
16702 @item CDPATH
16703 @evindex CDPATH
16704 When this variable is set it specifies a list of directories to search
16705 when invoking @code{cd} with a relative file name that did not start
16706 with @samp{./} or @samp{../}.  Posix
16707 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16708 is used successfully, @code{cd} prints the resulting absolute
16709 file name.  Unfortunately this output can break idioms like
16710 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16711 Also, many shells do not conform to this part of Posix; for
16712 example, @command{zsh} prints the result only if a directory name
16713 other than @file{.} was chosen from @env{CDPATH}.
16715 In practice the shells that have this problem also support
16716 @command{unset}, so you can work around the problem as follows:
16718 @example
16719 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16720 @end example
16722 You can also avoid output by ensuring that your directory name is
16723 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16725 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16726 possible, so you need not worry about this problem in those scripts.
16728 @item CLICOLOR_FORCE
16729 @evindex CLICOLOR_FORCE
16730 When this variable is set, some implementations of tools like
16731 @command{ls} attempt to add color to their output via terminal escape
16732 sequences, even when the output is not directed to a terminal, and can
16733 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16734 which automatically unsets this variable.
16736 @item DUALCASE
16737 @evindex DUALCASE
16738 In the MKS shell, case statements and file name generation are
16739 case-insensitive unless @env{DUALCASE} is nonzero.
16740 Autoconf-generated scripts export this variable when they start up.
16742 @item ENV
16743 @itemx MAIL
16744 @itemx MAILPATH
16745 @itemx PS1
16746 @itemx PS2
16747 @itemx PS4
16748 @evindex ENV
16749 @evindex MAIL
16750 @evindex MAILPATH
16751 @evindex PS1
16752 @evindex PS2
16753 @evindex PS4
16754 These variables should not matter for shell scripts, since they are
16755 supposed to affect only interactive shells.  However, at least one
16756 shell (the pre-3.0 UWIN Korn shell) gets confused about
16757 whether it is interactive, which means that (for example) a @env{PS1}
16758 with a side effect can unexpectedly modify @samp{$?}.  To work around
16759 this bug, M4sh scripts (including @file{configure} scripts) do something
16760 like this:
16762 @example
16763 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16764 PS1='$ '
16765 PS2='> '
16766 PS4='+ '
16767 @end example
16769 @noindent
16770 (actually, there is some complication due to bugs in @command{unset};
16771 @pxref{unset, , Limitations of Shell Builtins}).
16773 @item FPATH
16774 @evindex FPATH
16775 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16776 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16777 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16778 to find whether a command exists, since they might report the wrong
16779 result if @env{FPATH} is also set.
16781 @item GREP_OPTIONS
16782 @evindex GREP_OPTIONS
16783 When this variable is set, some implementations of @command{grep} honor
16784 these options, even if the options include direction to enable colored
16785 output via terminal escape sequences, and the result can cause spurious
16786 failures when the output is not directed to a terminal.  Configure
16787 scripts use M4sh, which automatically unsets this variable.
16789 @item IFS
16790 @evindex IFS
16791 Long ago, shell scripts inherited @env{IFS} from the environment,
16792 but this caused many problems so modern shells ignore any environment
16793 settings for @env{IFS}.
16795 Don't set the first character of @env{IFS} to backslash.  Indeed,
16796 Bourne shells use the first character (backslash) when joining the
16797 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16798 backslash escapes, so you can end up with backspace and other strange
16799 characters.
16801 The proper value for @env{IFS} (in regular code, not when performing
16802 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16803 especially important, as it is used to join the arguments in @samp{$*};
16804 however, note that traditional shells, but also bash-2.04, fail to adhere
16805 to this and join with a space anyway.
16807 M4sh guarantees that @env{IFS} will have the default value at the
16808 beginning of a script, and many macros within autoconf rely on this
16809 setting.  It is okay to use blocks of shell code that temporarily change
16810 the value of @env{IFS} in order to split on another character, but
16811 remember to restore it before expanding further macros.
16813 Unsetting @code{IFS} instead of resetting it to the default sequence
16814 is not suggested, since code that tries to save and restore the
16815 variable's value will incorrectly reset it to an empty value, thus
16816 disabling field splitting:
16818 @example
16819 unset IFS
16820 # default separators used for field splitting
16822 save_IFS=$IFS
16823 IFS=:
16824 # ...
16825 IFS=$save_IFS
16826 # no field splitting performed
16827 @end example
16829 @item LANG
16830 @itemx LC_ALL
16831 @itemx LC_COLLATE
16832 @itemx LC_CTYPE
16833 @itemx LC_MESSAGES
16834 @itemx LC_MONETARY
16835 @itemx LC_NUMERIC
16836 @itemx LC_TIME
16837 @evindex LANG
16838 @evindex LC_ALL
16839 @evindex LC_COLLATE
16840 @evindex LC_CTYPE
16841 @evindex LC_MESSAGES
16842 @evindex LC_MONETARY
16843 @evindex LC_NUMERIC
16844 @evindex LC_TIME
16846 You should set all these variables to @samp{C} because so much
16847 configuration code assumes the C locale and Posix requires that locale
16848 environment variables be set to @samp{C} if the C locale is desired;
16849 @file{configure} scripts and M4sh do that for you.
16850 Export these variables after setting them.
16852 @c  However, some older, nonstandard
16853 @c  systems (notably SCO) break if locale environment variables
16854 @c  are set to @samp{C}, so when running on these systems
16855 @c  Autoconf-generated scripts unset the variables instead.
16857 @item LANGUAGE
16858 @evindex LANGUAGE
16860 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16861 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16862 should set it too.
16864 @item LC_ADDRESS
16865 @itemx LC_IDENTIFICATION
16866 @itemx LC_MEASUREMENT
16867 @itemx LC_NAME
16868 @itemx LC_PAPER
16869 @itemx LC_TELEPHONE
16870 @evindex LC_ADDRESS
16871 @evindex LC_IDENTIFICATION
16872 @evindex LC_MEASUREMENT
16873 @evindex LC_NAME
16874 @evindex LC_PAPER
16875 @evindex LC_TELEPHONE
16877 These locale environment variables are GNU extensions.  They
16878 are treated like their Posix brethren (@env{LC_COLLATE},
16879 etc.)@: as described above.
16881 @item LINENO
16882 @evindex LINENO
16883 Most modern shells provide the current line number in @code{LINENO}.
16884 Its value is the line number of the beginning of the current command.
16885 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16886 a shell that supports @code{LINENO}.  If no such shell is available, it
16887 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16888 instance of the string @code{$LINENO} (not followed by an alphanumeric
16889 character) with the line's number.  In M4sh scripts you should execute
16890 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16891 your script; configure scripts do this automatically in @code{AC_INIT}.
16893 You should not rely on @code{LINENO} within @command{eval} or shell
16894 functions, as the behavior differs in practice.  The presence of a
16895 quoted newline within simple commands can alter which line number is
16896 used as the starting point for @code{$LINENO} substitutions within that
16897 command.  Also, the possibility of the Sed prepass means that you should
16898 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16899 line continuations are used.  Subshells should be OK, though.  In the
16900 following example, lines 1, 9, and 14 are portable, but the other
16901 instances of @code{$LINENO} do not have deterministic values:
16903 @example
16904 @group
16905 $ @kbd{cat lineno}
16906 echo 1. $LINENO
16907 echo "2. $LINENO
16908 3. $LINENO"
16909 cat <<EOF
16910 5. $LINENO
16911 6. $LINENO
16912 7. \$LINENO
16914 ( echo 9. $LINENO )
16915 eval 'echo 10. $LINENO'
16916 eval 'echo 11. $LINENO
16917 echo 12. $LINENO'
16918 echo 13. '$LINENO'
16919 echo 14. $LINENO '
16920 15.' $LINENO
16921 f () @{ echo $1 $LINENO;
16922 echo $1 $LINENO @}
16923 f 18.
16924 echo 19. \
16925 $LINENO
16926 @end group
16927 @group
16928 $ @kbd{bash-3.2 ./lineno}
16929 1. 1
16930 2. 3
16931 3. 3
16932 5. 4
16933 6. 4
16934 7. $LINENO
16935 9. 9
16936 10. 10
16937 11. 12
16938 12. 13
16939 13. $LINENO
16940 14. 14
16941 15. 14
16942 18. 16
16943 18. 17
16944 19. 19
16945 @end group
16946 @group
16947 $ @kbd{zsh-4.3.4 ./lineno}
16948 1. 1
16949 2. 2
16950 3. 2
16951 5. 4
16952 6. 4
16953 7. $LINENO
16954 9. 9
16955 10. 1
16956 11. 1
16957 12. 2
16958 13. $LINENO
16959 14. 14
16960 15. 14
16961 18. 0
16962 18. 1
16963 19. 19
16964 @end group
16965 @group
16966 $ @kbd{pdksh-5.2.14 ./lineno}
16967 1. 1
16968 2. 2
16969 3. 2
16970 5. 4
16971 6. 4
16972 7. $LINENO
16973 9. 9
16974 10. 0
16975 11. 0
16976 12. 0
16977 13. $LINENO
16978 14. 14
16979 15. 14
16980 18. 16
16981 18. 17
16982 19. 19
16983 @end group
16984 @group
16985 $ @kbd{sed '=' <lineno |}
16986 > @kbd{  sed '}
16987 > @kbd{    N}
16988 > @kbd{    s,$,-,}
16989 > @kbd{    t loop}
16990 > @kbd{    :loop}
16991 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16992 > @kbd{    t loop}
16993 > @kbd{    s,-$,,}
16994 > @kbd{    s,^[0-9]*\n,,}
16995 > @kbd{  ' |}
16996 > @kbd{  sh}
16997 1. 1
16998 2. 2
16999 3. 3
17000 5. 5
17001 6. 6
17002 7. \7
17003 9. 9
17004 10. 10
17005 11. 11
17006 12. 12
17007 13. 13
17008 14. 14
17009 15. 15
17010 18. 16
17011 18. 17
17012 19. 20
17013 @end group
17014 @end example
17016 In particular, note that @file{config.status} (and any other subsidiary
17017 script created by @code{AS_INIT_GENERATED}) might report line numbers
17018 relative to the parent script as a result of the potential Sed pass.
17020 @item NULLCMD
17021 @evindex NULLCMD
17022 When executing the command @samp{>foo}, @command{zsh} executes
17023 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17024 compatibility mode and the @command{zsh} version is newer
17025 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17026 and forget to set @env{NULLCMD},
17027 your script might be suspended waiting for data on its standard input.
17029 @item options
17030 @evindex options
17031 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17032 array even after @code{emulate sh}, so it should not be used.
17034 @item PATH_SEPARATOR
17035 @evindex PATH_SEPARATOR
17036 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17037 variable can be set to either @samp{:} or @samp{;} to control the path
17038 separator Bash uses to set up certain environment variables (such as
17039 @env{PATH}).  You can set this variable to @samp{;} if you want
17040 @command{configure} to use @samp{;} as a separator; this might be useful
17041 if you plan to use non-Posix shells to execute files.  @xref{File System
17042 Conventions}, for more information about @code{PATH_SEPARATOR}.
17044 @item POSIXLY_CORRECT
17045 @evindex POSIXLY_CORRECT
17046 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17047 (even empty) causes programs to try harder to conform to Posix.
17048 Autoconf does not directly manipulate this variable, but @command{bash}
17049 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17050 running in Posix mode.  Therefore, take care when exporting or unsetting
17051 this variable, so as not to change whether @command{bash} is in Posix
17052 mode.
17054 @example
17055 $ @kbd{bash --posix -c 'set -o | grep posix}
17056 > @kbd{unset POSIXLY_CORRECT}
17057 > @kbd{set -o | grep posix'}
17058 posix           on
17059 posix           off
17060 @end example
17062 @item PWD
17063 @evindex PWD
17064 Posix 1003.1-2001 requires that @command{cd} and
17065 @command{pwd} must update the @env{PWD} environment variable to point
17066 to the logical name of the current directory, but traditional shells
17067 do not support this.  This can cause confusion if one shell instance
17068 maintains @env{PWD} but a subsidiary and different shell does not know
17069 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17070 points to the wrong directory.  Use @samp{`pwd`} rather than
17071 @samp{$PWD}.
17073 @item RANDOM
17074 @evindex RANDOM
17075 Many shells provide @code{RANDOM}, a variable that returns a different
17076 integer each time it is used.  Most of the time, its value does not
17077 change when it is not used, but on IRIX 6.5 the value changes all
17078 the time.  This can be observed by using @command{set}.  It is common
17079 practice to use @code{$RANDOM} as part of a file name, but code
17080 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17082 @item status
17083 @evindex status
17084 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17085 hence read-only.  Do not use it.
17086 @end table
17088 @node Shell Functions
17089 @section Shell Functions
17090 @cindex Shell Functions
17092 Nowadays, it is difficult to find a shell that does not support
17093 shell functions at all.  However, some differences should be expected.
17095 When declaring a shell function, you must include whitespace between the
17096 @samp{)} after the function name and the start of the compound
17097 expression, to avoid upsetting @command{ksh}.  While it is possible to
17098 use any compound command, most scripts use @samp{@{@dots{}@}}.
17100 @example
17101 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17103 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17104 ksh: syntax error at line 1: `@}' unexpected
17105 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17107 @end example
17109 Inside a shell function, you should not rely on the error status of a
17110 subshell if the last command of that subshell was @code{exit} or
17111 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17112 find a shell that does not exhibit the bug, zsh might be the only shell
17113 present on the user's machine.
17115 Likewise, the state of @samp{$?} is not reliable when entering a shell
17116 function.  This has the effect that using a function as the first
17117 command in a @command{trap} handler can cause problems.
17119 @example
17120 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17123 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17126 @end example
17128 DJGPP bash 2.04 has a bug in that @command{return} from a
17129 shell function which also used a command substitution causes a
17130 segmentation fault.  To work around the issue, you can use
17131 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17132 in the execution flow of the function (@pxref{Common Shell Constructs}).
17134 Not all shells treat shell functions as simple commands impacted by
17135 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17137 @example
17138 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17139 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17140 oops
17141 @end example
17143 Shell variables and functions may share the same namespace, for example
17144 with Solaris 10 @command{/bin/sh}:
17146 @example
17147 $ @kbd{f () @{ :; @}; f=; f}
17148 f: not found
17149 @end example
17151 @noindent
17152 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17153 uses the prefix @samp{as_fn_} for its functions.
17155 Handling of positional parameters and shell options varies among shells.
17156 For example, Korn shells reset and restore trace output (@samp{set -x})
17157 and other options upon function entry and exit.  Inside a function,
17158 IRIX sh sets @samp{$0} to the function name.
17160 It is not portable to pass temporary environment variables to shell
17161 functions.  Solaris @command{/bin/sh} does not see the variable.
17162 Meanwhile, not all shells follow the Posix rule that the assignment must
17163 affect the current environment in the same manner as special built-ins.
17165 @example
17166 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17167 @result{}
17168 @result{}
17169 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17170 @result{}1
17171 @result{}
17172 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17173 @result{}1
17174 @result{}1
17175 @end example
17177 Some ancient Bourne shell variants with function support did not reset
17178 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17179 arguments of the script were lost after the first function invocation.
17180 It is probably not worth worrying about these shells any more.
17182 With AIX sh, a @command{trap} on 0 installed in a shell function
17183 triggers at function exit rather than at script exit.  @xref{trap, ,
17184 Limitations of Shell Builtins}.
17186 @node Limitations of Builtins
17187 @section Limitations of Shell Builtins
17188 @cindex Shell builtins
17189 @cindex Limitations of shell builtins
17191 No, no, we are serious: some shells do have limitations!  :)
17193 You should always keep in mind that any builtin or command may support
17194 options, and therefore differ in behavior with arguments
17195 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17196 can give unexpected results when @code{word} starts with a dash.  It is
17197 often possible to avoid this problem using @samp{echo "x$word"}, taking
17198 the @samp{x} into account later in the pipe.  Many of these limitations
17199 can be worked around using M4sh (@pxref{Programming in M4sh}).
17201 @c This table includes things like `@command{test} (files)', so we can't
17202 @c use @table @command.
17203 @table @asis
17204 @item @command{.}
17205 @c --------------
17206 @prindex @command{.}
17207 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17208 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17209 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17210 some shells, including bash 3.2, implicitly append the current directory
17211 to this @env{PATH} search, even though Posix forbids it.  So if you want
17212 to use @command{.} on a file @file{foo} in the current directory, you
17213 must use @samp{. ./foo}.
17215 Not all shells gracefully handle syntax errors within a sourced file.
17216 On one extreme, some non-interactive shells abort the entire script.  On
17217 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17218 syntax error.
17220 @example
17221 $ @kbd{echo 'fi' > syntax}
17222 $ @kbd{bash -c '. ./syntax; echo $?'}
17223 ./syntax: line 1: syntax error near unexpected token `fi'
17224 ./syntax: line 1: `fi'
17226 $ @kbd{ash -c '. ./syntax; echo $?'}
17227 ./syntax: 1: Syntax error: "fi" unexpected
17228 $ @kbd{zsh -c '. ./syntax; echo $?'}
17229 ./syntax:1: parse error near `fi'
17231 @end example
17233 @item @command{!}
17234 @c --------------
17235 @prindex @command{!}
17236 The Unix version 7 shell did not support
17237 negating the exit status of commands with @command{!}, and this feature
17238 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17239 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17240 bugs when using @command{!}:
17242 @example
17243 $ @kbd{sh -c '! : | :'; echo $?}
17245 $ @kbd{ash -c '! : | :'; echo $?}
17247 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17249 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17250 @{: not found
17251 Syntax error: "@}" unexpected
17253 @end example
17255 Shell code like this:
17257 @example
17258 if ! cmp file1 file2 >/dev/null 2>&1; then
17259   echo files differ or trouble
17261 @end example
17263 is therefore not portable in practice.  Typically it is easy to rewrite
17264 such code, e.g.:
17266 @example
17267 cmp file1 file2 >/dev/null 2>&1 ||
17268   echo files differ or trouble
17269 @end example
17271 More generally, one can always rewrite @samp{! @var{command}} as:
17273 @example
17274 if @var{command}; then (exit 1); else :; fi
17275 @end example
17278 @item @command{@{...@}}
17279 @c --------------------
17280 @prindex @command{@{...@}}
17281 Bash 3.2 (and earlier versions) sometimes does not properly set
17282 @samp{$?} when failing to write redirected output of a compound command.
17283 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17284 not occur with @samp{(@dots{})}.  For example:
17286 @example
17287 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17288 bash: line 1: /bad: Permission denied
17290 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17291 bash: line 1: /bad: Permission denied
17293 @end example
17295 To work around the bug, prepend @samp{:;}:
17297 @example
17298 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17299 bash: line 1: /bad: Permission denied
17301 @end example
17303 Posix requires a syntax error if a brace list has no contents.  However,
17304 not all shells obey this rule; and on shells where empty lists are
17305 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17306 ensure that a brace list is never empty.
17308 @example
17309 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17310 bash: line 1: syntax error near unexpected token `@}'
17311 bash: line 1: `false; @{ @}; echo $?'
17313 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17315 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17317 @end example
17320 @item @command{break}
17321 @c ------------------
17322 @prindex @command{break}
17323 The use of @samp{break 2} etc.@: is safe.
17326 @anchor{case}
17327 @item @command{case}
17328 @c -----------------
17329 @prindex @command{case}
17330 You don't need to quote the argument; no splitting is performed.
17332 You don't need the final @samp{;;}, but you should use it.
17334 Posix requires support for @code{case} patterns with opening
17335 parentheses like this:
17337 @example
17338 case $file_name in
17339   (*.c) echo "C source code";;
17340 esac
17341 @end example
17343 @noindent
17344 but the @code{(} in this example is not portable to many Bourne
17345 shell implementations, which is a pity for those of us using tools that
17346 rely on balanced parentheses.  For instance, with Solaris
17347 @command{/bin/sh}:
17349 @example
17350 $ @kbd{case foo in (foo) echo foo;; esac}
17351 @error{}syntax error: `(' unexpected
17352 @end example
17354 @noindent
17355 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17356 contexts where unbalanced parentheses cause other problems, such as when
17357 using a syntax-highlighting editor that searches for the balancing
17358 counterpart, or more importantly, when using a case statement as an
17359 underquoted argument to an Autoconf macro.  @xref{Balancing
17360 Parentheses}, for tradeoffs involved in various styles of dealing with
17361 unbalanced @samp{)}.
17363 Zsh handles pattern fragments derived from parameter expansions or
17364 command substitutions as though quoted:
17366 @example
17367 $ pat=\?; case aa in ?$pat) echo match;; esac
17368 $ pat=\?; case a? in ?$pat) echo match;; esac
17369 match
17370 @end example
17372 @noindent
17373 Because of a bug in its @code{fnmatch}, Bash fails to properly
17374 handle backslashes in character classes:
17376 @example
17377 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17378 bash-2.02$
17379 @end example
17381 @noindent
17382 This is extremely unfortunate, since you are likely to use this code to
17383 handle Posix or MS-DOS absolute file names.  To work around this
17384 bug, always put the backslash first:
17386 @example
17387 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17389 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17391 @end example
17393 Many Bourne shells cannot handle closing brackets in character classes
17394 correctly.
17396 Some shells also have problems with backslash escaping in case you do not want
17397 to match the backslash: both a backslash and the escaped character match this
17398 pattern.  To work around this, specify the character class in a variable, so
17399 that quote removal does not apply afterwards, and the special characters don't
17400 have to be backslash-escaped:
17402 @example
17403 $ @kbd{case '\' in [\<]) echo OK;; esac}
17405 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17407 @end example
17409 Even with this, Solaris @command{ksh} matches a backslash if the set
17410 contains any
17411 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17413 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17414 a closing parenthesis if not specified in a character class:
17416 @example
17417 $ @kbd{case foo in *\)*) echo fail ;; esac}
17418 fail
17419 $ @kbd{case foo in *')'*) echo fail ;; esac}
17420 fail
17421 @end example
17423 Some shells, such as Ash 0.3.8, are confused by an empty
17424 @code{case}/@code{esac}:
17426 @example
17427 ash-0.3.8 $ @kbd{case foo in esac;}
17428 @error{}Syntax error: ";" unexpected (expecting ")")
17429 @end example
17431 Posix requires @command{case} to give an exit status of 0 if no cases
17432 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17433 rule.  Meanwhile, it is unclear whether a case that matches, but
17434 contains no statements, must also change the exit status to 0.  The M4sh
17435 macro @code{AS_CASE} works around these inconsistencies.
17437 @example
17438 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17440 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17442 @end example
17445 @item @command{cd}
17446 @c ---------------
17447 @prindex @command{cd}
17448 Posix 1003.1-2001 requires that @command{cd} must support
17449 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17450 with @option{-L} being the default.  However, traditional shells do
17451 not support these options, and their @command{cd} command has the
17452 @option{-P} behavior.
17454 Portable scripts should assume neither option is supported, and should
17455 assume neither behavior is the default.  This can be a bit tricky,
17456 since the Posix default behavior means that, for example,
17457 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17458 the current logical directory is a symbolic link.  It is safe to use
17459 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17460 Also, Autoconf-generated scripts check for this problem when computing
17461 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17462 so it is safe to @command{cd} to these variables.
17464 Posix states that behavior is undefined if @command{cd} is given an
17465 explicit empty argument.  Some shells do nothing, some change to the
17466 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17467 the shell rather than returning an error.  Unfortunately, this means
17468 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17469 than @samp{cd $var} (at least the latter is well-behaved in all shells
17470 at changing to @env{HOME}, although this is probably not what you wanted
17471 in a script).  You should check that a directory name was supplied
17472 before trying to change locations.
17474 @xref{Special Shell Variables}, for portability problems involving
17475 @command{cd} and the @env{CDPATH} environment variable.
17476 Also please see the discussion of the @command{pwd} command.
17479 @anchor{echo}
17480 @item @command{echo}
17481 @c -----------------
17482 @prindex @command{echo}
17483 The simple @command{echo} is probably the most surprising source of
17484 portability troubles.  It is not possible to use @samp{echo} portably
17485 unless both options and escape sequences are omitted.  Don't expect any
17486 option.
17488 Do not use backslashes in the arguments, as there is no consensus on
17489 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17490 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17491 The problem is truly @command{echo}: all the shells
17492 understand @samp{'\n'} as the string composed of a backslash and an
17493 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17494 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17495 the first character @samp{s} only, followed by a newline, and then
17496 entirely drop the output of the next echo in a command substitution.
17498 Because of these problems, do not pass a string containing arbitrary
17499 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17500 only if you know that @var{foo}'s value cannot contain backslashes and
17501 cannot start with @samp{-}.
17503 If this may not be true, @command{printf} is in general safer and
17504 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
17505 where portability is not a major concern should use @command{printf
17506 '%s\n'} whenever @command{echo} could fail, and similarly use
17507 @command{printf %s} instead of @command{echo -n}. For portable shell
17508 scripts, instead, it is suggested to use a here-document like this:
17510 @example
17511 cat <<EOF
17512 $foo
17514 @end example
17516 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
17517 which choose between various portable implementations: @samp{echo}
17518 or @samp{print} where they work, @command{printf} if it is available,
17519 or else other creative tricks in order to work around the above problems.
17522 @item @command{eval}
17523 @c -----------------
17524 @prindex @command{eval}
17525 The @command{eval} command is useful in limited circumstances, e.g.,
17526 using commands like @samp{eval table_$key=\$value} and @samp{eval
17527 value=table_$key} to simulate a hash table when the key is known to be
17528 alphanumeric.
17530 You should also be wary of common bugs in @command{eval} implementations.
17531 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17532 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17533 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17534 @samp{$?} is 0, so they exhibit behavior like this:
17536 @example
17537 $ @kbd{false; eval 'echo $?'}
17539 @end example
17541 The correct behavior here is to output a nonzero value,
17542 but portable scripts should not rely on this.
17544 You should not rely on @code{LINENO} within @command{eval}.
17545 @xref{Special Shell Variables}.
17547 Note that, even though these bugs are easily avoided,
17548 @command{eval} is tricky to use on arbitrary arguments.
17549 It is obviously unwise to use @samp{eval $cmd} if the string value of
17550 @samp{cmd} was derived from an untrustworthy source.  But even if the
17551 string value is valid, @samp{eval $cmd} might not work as intended,
17552 since it causes field splitting and file name expansion to occur twice,
17553 once for the @command{eval} and once for the command itself.  It is
17554 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17555 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17556 equivalent of @samp{cat test;.c} if there happens to be a file named
17557 @file{test;.c} in the current directory; and this in turn
17558 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17559 then execute the command @command{.c}.  To avoid this problem, use
17560 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17562 However, suppose that you want to output the text of the evaluated
17563 command just before executing it.  Assuming the previous example,
17564 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17565 this output doesn't show the user that @samp{test;.c} is the actual name
17566 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17567 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17568 since it mistakenly replaces the contents of @file{bar} by the
17569 string @samp{cat foo}.  No simple, general, and portable solution to
17570 this problem is known.
17572 @item @command{exec}
17573 @c -----------------
17574 @prindex @command{exec}
17575 Posix describes several categories of shell built-ins.  Special
17576 built-ins (such as @command{exit}) must impact the environment of the
17577 current shell, and need not be available through @command{exec}.  All
17578 other built-ins are regular, and must not propagate variable assignments
17579 to the environment of the current shell.  However, the group of regular
17580 built-ins is further distinguished by commands that do not require a
17581 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17582 are offered as a more efficient version of something that must still be
17583 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17584 clear on whether @command{exec} must work with the list of 17 utilities
17585 that are invoked without a @env{PATH} search, and many platforms lack an
17586 executable for some of those built-ins:
17588 @example
17589 $ @kbd{sh -c 'exec cd /tmp'}
17590 sh: line 0: exec: cd: not found
17591 @end example
17593 All other built-ins that provide utilities specified by Posix must have
17594 a counterpart executable that exists on @env{PATH}, although Posix
17595 allows @command{exec} to use the built-in instead of the executable.
17596 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17598 @example
17599 $ @kbd{bash -c 'pwd --version' | head -n1}
17600 bash: line 0: pwd: --: invalid option
17601 pwd: usage: pwd [-LP]
17602 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17603 pwd (GNU coreutils) 6.10
17604 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17605 pdksh: pwd: --: unknown option
17606 @end example
17608 When it is desired to avoid a regular shell built-in, the workaround is
17609 to use some other forwarding command, such as @command{env} or
17610 @command{nice}, that will ensure a path search:
17612 @example
17613 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17614 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17615 true (GNU coreutils) 6.10
17616 $ @kbd{pdksh -c 'env true --version' | head -n1}
17617 true (GNU coreutils) 6.10
17618 @end example
17620 @item @command{exit}
17621 @c -----------------
17622 @prindex @command{exit}
17623 The default value of @command{exit} is supposed to be @code{$?};
17624 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17625 perform @samp{exit 0}.
17627 @example
17628 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17629 fail
17630 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17631 fail
17632 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17633 bash-2.04$
17634 @end example
17636 Using @samp{exit $?} restores the expected behavior.
17638 Some shell scripts, such as those generated by @command{autoconf}, use a
17639 trap to clean up before exiting.  If the last shell command exited with
17640 nonzero status, the trap also exits with nonzero status so that the
17641 invoker can tell that an error occurred.
17643 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17644 trap ignores the @code{exit} command's argument.  In these shells, a trap
17645 cannot determine whether it was invoked by plain @code{exit} or by
17646 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17647 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17650 @anchor{export}
17651 @item @command{export}
17652 @c -------------------
17653 @prindex @command{export}
17654 The builtin @command{export} dubs a shell variable @dfn{environment
17655 variable}.  Each update of exported variables corresponds to an update
17656 of the environment variables.  Conversely, each environment variable
17657 received by the shell when it is launched should be imported as a shell
17658 variable marked as exported.
17660 Alas, many shells, such as Solaris @command{/bin/sh},
17661 IRIX 6.3, IRIX 5.2,
17662 AIX 4.1.5, and Digital Unix 4.0, forget to
17663 @command{export} the environment variables they receive.  As a result,
17664 two variables coexist: the environment variable and the shell
17665 variable.  The following code demonstrates this failure:
17667 @example
17668 #!/bin/sh
17669 echo $FOO
17670 FOO=bar
17671 echo $FOO
17672 exec /bin/sh $0
17673 @end example
17675 @noindent
17676 when run with @samp{FOO=foo} in the environment, these shells print
17677 alternately @samp{foo} and @samp{bar}, although they should print only
17678 @samp{foo} and then a sequence of @samp{bar}s.
17680 Therefore you should @command{export} again each environment variable
17681 that you update; the export can occur before or after the assignment.
17683 Posix is not clear on whether the @command{export} of an undefined
17684 variable causes the variable to be defined with the value of an empty
17685 string, or merely marks any future definition of a variable by that name
17686 for export.  Various shells behave differently in this regard:
17688 @example
17689 $ @kbd{sh -c 'export foo; env | grep foo'}
17690 $ @kbd{ash -c 'export foo; env | grep foo'}
17691 foo=
17692 @end example
17694 Posix requires @command{export} to honor assignments made as arguments,
17695 but older shells do not support this, including @command{/bin/sh} in
17696 Solaris 10.  Portable scripts should separate assignments and exports
17697 into different statements.
17699 @example
17700 $ @kbd{bash -c 'export foo=bar; echo $foo'}
17702 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17703 /bin/sh: foo=bar: is not an identifier
17704 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17706 @end example
17708 @item @command{false}
17709 @c ------------------
17710 @prindex @command{false}
17711 Don't expect @command{false} to exit with status 1: in native
17712 Solaris @file{/bin/false} exits with status 255.
17715 @item @command{for}
17716 @c ----------------
17717 @prindex @command{for}
17718 To loop over positional arguments, use:
17720 @example
17721 for arg
17723   echo "$arg"
17724 done
17725 @end example
17727 @noindent
17728 You may @emph{not} leave the @code{do} on the same line as @code{for},
17729 since some shells improperly grok:
17731 @example
17732 for arg; do
17733   echo "$arg"
17734 done
17735 @end example
17737 If you want to explicitly refer to the positional arguments, given the
17738 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17740 @example
17741 for arg in $@{1+"$@@"@}; do
17742   echo "$arg"
17743 done
17744 @end example
17746 @noindent
17747 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17748 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17749 item @samp{$@@}, for more.
17751 In Solaris @command{/bin/sh}, when the list of arguments of a
17752 @command{for} loop starts with @emph{unquoted} tokens looking like
17753 variable assignments, the loop is not executed on those tokens:
17755 @example
17756 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17759 @end example
17761 @noindent
17762 Thankfully, quoting the assignment-like tokens, or starting the list
17763 with other tokens (including unquoted variable expansion that results in
17764 an assignment-like result), avoids the problem, so it is easy to work
17765 around:
17767 @example
17768 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17770 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17773 @end example
17775 @anchor{if}
17776 @item @command{if}
17777 @c ---------------
17778 @prindex @command{if}
17779 Using @samp{!} is not portable.  Instead of:
17781 @example
17782 if ! cmp -s file file.new; then
17783   mv file.new file
17785 @end example
17787 @noindent
17788 use:
17790 @example
17791 if cmp -s file file.new; then :; else
17792   mv file.new file
17794 @end example
17796 @noindent
17797 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17798 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17799 of conditionals:
17801 @example
17802 AS_IF([cmp -s file file.new], [], [mv file.new file])
17803 @end example
17805 This is especially useful in other M4 macros, where the @dfn{then} and
17806 @dfn{else} branches might be macro arguments.
17808 Some very old shells did not reset the exit status from an @command{if}
17809 with no @command{else}:
17811 @example
17812 $ @kbd{if (exit 42); then true; fi; echo $?}
17814 @end example
17816 @noindent
17817 whereas a proper shell should have printed @samp{0}.  But this is no
17818 longer a portability problem; any shell that supports functions gets it
17819 correct.  However, it explains why some makefiles have lengthy
17820 constructs:
17822 @example
17823 if test -f "$file"; then
17824   install "$file" "$dest"
17825 else
17826   :
17828 @end example
17831 @item @command{printf}
17832 @c ------------------
17833 @prindex @command{printf}
17834 A format string starting with a @samp{-} can cause problems.
17835 Bash interprets it as an option and
17836 gives an error.  And @samp{--} to mark the end of options is not good
17837 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17838 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17839 or @samp{%s} is probably easiest:
17841 @example
17842 printf %s -foo
17843 @end example
17845 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17847 @example
17848 $ @kbd{printf '\045'}
17849 bash: printf: `%': missing format character
17850 @end example
17852 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17853 example, @file{/usr/bin/printf} is buggy, so when using
17854 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17855 core.
17857 Since @command{printf} is not always a shell builtin, there is a
17858 potential speed penalty for using @code{printf '%s\n'} as a replacement
17859 for an @command{echo} that does not interpret @samp{\} or leading
17860 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17861 -r --} for this role instead.
17863 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
17864 portable alternatives to both @command{printf} and @command{echo}.
17867 @item @command{pwd}
17868 @c ----------------
17869 @prindex @command{pwd}
17870 With modern shells, plain @command{pwd} outputs a ``logical''
17871 directory name, some of whose components may be symbolic links.  These
17872 directory names are in contrast to ``physical'' directory names, whose
17873 components are all directories.
17875 Posix 1003.1-2001 requires that @command{pwd} must support
17876 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17877 with @option{-L} being the default.  However, traditional shells do
17878 not support these options, and their @command{pwd} command has the
17879 @option{-P} behavior.
17881 Portable scripts should assume neither option is supported, and should
17882 assume neither behavior is the default.  Also, on many hosts
17883 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17884 does not require this behavior and portable scripts should not rely on
17887 Typically it's best to use plain @command{pwd}.  On modern hosts this
17888 outputs logical directory names, which have the following advantages:
17890 @itemize @bullet
17891 @item
17892 Logical names are what the user specified.
17893 @item
17894 Physical names may not be portable from one installation
17895 host to another due to network file system gymnastics.
17896 @item
17897 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17898 some parent directory, but plain @command{pwd} cannot fail for this
17899 reason.
17900 @end itemize
17902 Also please see the discussion of the @command{cd} command.
17905 @item @command{read}
17906 @c -----------------
17907 @prindex @command{read}
17908 No options are portable, not even support @option{-r} (Solaris
17909 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
17910 @command{read} as a special built-in, so it may exit if input is
17911 redirected from a non-existent or unreadable file.
17914 @anchor{set}
17915 @item @command{set}
17916 @c ----------------
17917 @prindex @command{set}
17918 With the FreeBSD 6.0 shell, the @command{set} command (without
17919 any options) does not sort its output.
17921 The @command{set} builtin faces the usual problem with arguments
17922 starting with a
17923 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17924 the end of the options (any argument after @option{--} is a parameter,
17925 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
17926 10 @command{/bin/sh}) simply stop option
17927 processing as soon as a non-option argument is found.  Therefore, use
17928 @samp{dummy} or simply @samp{x} to end the option processing, and use
17929 @command{shift} to pop it out:
17931 @example
17932 set x $my_list; shift
17933 @end example
17935 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17936 longer requires support for this command, and in traditional shells
17937 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17938 makes scripts harder to debug.
17940 Some nonstandard shells do not recognize more than one option
17941 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17942 better to combine them:
17944 @example
17945 set -ex
17946 @end example
17948 @cindex @command{set -e}
17949 The option @option{-e} has historically been underspecified, with enough
17950 ambiguities to cause numerous differences across various shell
17951 implementations; see for example
17952 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
17953 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
17954 documenting a change to Posix 2008 to match @command{ksh88} behavior.
17955 Note that mixing @code{set -e} and shell functions is asking for surprises:
17957 @example
17958 set -e
17959 doit()
17961   rm file
17962   echo one
17964 doit || echo two
17965 @end example
17967 @noindent
17968 According to the recommendation, @samp{one} should always be output
17969 regardless of whether the @command{rm} failed, because it occurs within
17970 the body of the shell function @samp{doit} invoked on the left side of
17971 @samp{||}, where the effects of @samp{set -e} are not enforced.
17972 Likewise, @samp{two} should never be printed, since the failure of
17973 @command{rm} does not abort the function, such that the status of
17974 @samp{doit} is 0.
17976 The BSD shell has had several problems with the @option{-e}
17977 option.  Older versions of the BSD
17978 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17979 @samp{case} when @option{-e} was in effect, causing the shell to exit
17980 unexpectedly in some cases.  This was particularly a problem with
17981 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17982 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17983 wrapper works around the bug (@pxref{Failure in Make Rules}).
17985 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17986 wrongly exit with @option{-e} if the last command within a compound
17987 statement fails and is guarded by an @samp{&&} only.  For example:
17989 @example
17990 #! /bin/sh
17991 set -e
17992 foo=''
17993 test -n "$foo" && exit 1
17994 echo one
17995 if :; then
17996   test -n "$foo" && exit 1
17997   echo two
17998   test -n "$foo" && exit 1
18000 echo three
18001 @end example
18003 @noindent
18004 does not print @samp{three}.  One workaround is to change the last
18005 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18006 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18007 users not to use @samp{sh -e}.
18009 When @samp{set -e} is in effect, a failed command substitution in
18010 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
18012 @example
18013 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18014 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18017 @end example
18019 @noindent
18020 Moreover, a command substitution, successful or not, causes this shell to
18021 exit from a failing outer command even in presence of an @samp{&&} list:
18023 @example
18024 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18026 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18028 @end example
18030 Portable scripts should not use @samp{set -e} if @command{trap} is used
18031 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18032 sometimes enters the trap handler with the exit status of the command
18033 prior to the one that triggered the errexit handler:
18035 @example
18036 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18038 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18040 @end example
18042 @noindent
18043 Thus, when writing a script in M4sh, rather than trying to rely on
18044 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18045 statement where it is desirable to abort on failure.
18047 @cindex @command{set -b}
18048 @cindex @command{set -m}
18049 Job control is not provided by all shells, so the use of @samp{set -m}
18050 or @samp{set -b} must be done with care.  When using @command{zsh} in
18051 native mode, asynchronous notification (@samp{set -b}) is enabled by
18052 default, and using @samp{emulate sh} to switch to Posix mode does not
18053 clear this setting (although asynchronous notification has no impact
18054 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18055 earlier have a bug where job control can be manipulated in interactive
18056 shells, but not in subshells or scripts.  Furthermore, some shells, like
18057 @command{pdksh}, fail to treat subshells as interactive, even though the
18058 parent shell was.
18060 @example
18061 $ @kbd{echo $ZSH_VERSION}
18062 4.3.10
18063 $ @kbd{set -m; echo $?}
18065 $ @kbd{zsh -c 'set -m; echo $?'}
18066 set: can't change option: -m
18067 $ @kbd{(set -m); echo $?}
18068 set: can't change option: -m
18070 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18073 @end example
18075 @cindex @command{set -n}
18076 Use of @command{set -n} (typically via @command{sh -n script}) to
18077 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18078 helpful by informing you about better syntax, but switching the script
18079 to use the suggested syntax in order to silence the warnings would
18080 render the script no longer portable to older shells:
18082 @example
18083 $ @kbd{ksh -nc '``'}
18084 ksh: warning: line 1: `...` obsolete, use $(...)
18086 @end example
18088 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18089 into an infinite loop; even with that bug fixed, Solaris 8
18090 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18091 itself uses @command{sh -n} within its testsuite to check that correct
18092 scripts were generated, but only after first probing for other shell
18093 features (such as @code{test -n "$@{BASH_VERSION+set@}"}) that indicate
18094 a reasonably fast and working implementation.
18096 @item @command{shift}
18097 @c ------------------
18098 @prindex @command{shift}
18099 Not only is @command{shift}ing a bad idea when there is nothing left to
18100 shift, but in addition it is not portable: the shell of MIPS
18101 RISC/OS 4.52 refuses to do it.
18103 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18104 it is also absent in many pre-Posix shells.
18107 @item @command{source}
18108 @c -------------------
18109 @prindex @command{source}
18110 This command is not portable, as Posix does not require it; use
18111 @command{.} instead.
18114 @item @command{test}
18115 @c -----------------
18116 @prindex @command{test}
18117 The @code{test} program is the way to perform many file and string
18118 tests.  It is often invoked by the alternate name @samp{[}, but using
18119 that name in Autoconf code is asking for trouble since it is an M4 quote
18120 character.
18122 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18123 present in all implementations, and have been marked obsolete by Posix
18124 2008.  This is because there are inherent ambiguities in using them.
18125 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18126 check whether two strings are both non-empty, but if @samp{$1} is the
18127 literal @samp{!}, then some implementations of @command{test} treat it
18128 as a negation of the unary operator @option{-a}.
18130 Thus, portable uses of @command{test} should never have more than four
18131 arguments, and scripts should use shell constructs like @samp{&&} and
18132 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18133 statement, keep in mind that they have equal precedence, so it is often
18134 better to parenthesize even when this is redundant.  For example:
18136 @smallexample
18137 # Not portable:
18138 test "X$a" = "X$b" -a \
18139   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18141 # Portable:
18142 test "X$a" = "X$b" &&
18143   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18144 @end smallexample
18146 @command{test} does not process options like most other commands do; for
18147 example, it does not recognize the @option{--} argument as marking the
18148 end of options.
18150 It is safe to use @samp{!} as a @command{test} operator.  For example,
18151 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18152 -d foo; @dots{}} is not.
18155 @item @command{test} (files)
18156 @c -------------------------
18157 To enable @command{configure} scripts to support cross-compilation, they
18158 shouldn't do anything that tests features of the build system instead of
18159 the host system.  But occasionally you may find it necessary to check
18160 whether some arbitrary file exists.  To do so, use @samp{test -f},
18161 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18162 Solaris 10 @command{/bin/sh}
18163 lacks it.  To test for symbolic links on systems that have them, use
18164 @samp{test -h} rather than @samp{test -L}; either form conforms to
18165 Posix 1003.1-2001, but older shells like Solaris 8
18166 @code{/bin/sh} support only @option{-h}.
18168 For historical reasons, Posix reluctantly allows implementations of
18169 @samp{test -x} that will succeed for the root user, even if no execute
18170 permissions are present.  Furthermore, shells do not all agree on
18171 whether Access Control Lists should affect @samp{test -r}, @samp{test
18172 -w}, and @samp{test -x}; some shells base test results strictly on the
18173 current user id compared to file owner and mode, as if by
18174 @code{stat(2)}; while other shells base test results on whether the
18175 current user has the given right, even if that right is only granted by
18176 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18177 time of check to time of use race between any use of @command{test}
18178 followed by operating on the just-checked file.  Therefore, it is a good
18179 idea to write scripts that actually attempt an operation, and are
18180 prepared for the resulting failure if permission is denied, rather than
18181 trying to avoid an operation based solely on whether @command{test}
18182 guessed that it might not be permitted.
18184 @item @command{test} (strings)
18185 @c ---------------------------
18186 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18187 not null, but this usage is not portable to traditional platforms like
18188 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18189 @samp{-n}.
18191 Posix also says that @samp{test ! "@var{string}"},
18192 @samp{test -n "@var{string}"} and
18193 @samp{test -z "@var{string}"} work with any string, but many
18194 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18195 Digital Unix 4, etc.)@: get confused if
18196 @var{string} looks like an operator:
18198 @example
18199 $ @kbd{test -n =}
18200 test: argument expected
18201 $ @kbd{test ! -n}
18202 test: argument expected
18203 $ @kbd{test -z ")"; echo $?}
18205 @end example
18207 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18208 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18209 strings, but in practice this is not true for troublesome strings that
18210 look like operators or parentheses, or that begin with @samp{-}.
18212 It is best to protect such strings with a leading @samp{X}, e.g.,
18213 @samp{test "X@var{string}" != X} rather than @samp{test -n
18214 "@var{string}"} or @samp{test ! "@var{string}"}.
18216 It is common to find variations of the following idiom:
18218 @example
18219 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18220   @var{action}
18221 @end example
18223 @noindent
18224 to take an action when a token matches a given pattern.  Such constructs
18225 should be avoided by using:
18227 @example
18228 case $ac_feature in
18229   *[!-a-zA-Z0-9_]*) @var{action};;
18230 esac
18231 @end example
18233 If the pattern is a complicated regular expression that cannot be
18234 expressed as a shell pattern, use something like this instead:
18236 @example
18237 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18238   @var{action}
18239 @end example
18241 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18242 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18243 @samp{@var{foo}} contains backslashes.
18246 @anchor{trap}
18247 @item @command{trap}
18248 @c -----------------
18249 @prindex @command{trap}
18250 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18251 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18252 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18253 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18254 will invoke the trap at the end of this function.
18256 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18257 specified signals to their default values, but many common shells (e.g.,
18258 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18259 ``command'' named @command{-} when the specified conditions arise.
18260 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18261 reset traps, as this is supported by a larger set of shells, but there
18262 are still shells like @command{dash} that mistakenly try to execute
18263 @command{1} instead of resetting the traps.  Therefore, there is no
18264 portable workaround, except for @samp{trap - 0}, for which
18265 @samp{trap '' 0} is a portable substitute.
18267 Although Posix is not absolutely clear on this point, it is widely
18268 admitted that when entering the trap @samp{$?} should be set to the exit
18269 status of the last command run before the trap.  The ambiguity can be
18270 summarized as: ``when the trap is launched by an @command{exit}, what is
18271 the @emph{last} command run: that before @command{exit}, or
18272 @command{exit} itself?''
18274 Bash considers @command{exit} to be the last command, while Zsh and
18275 Solaris @command{/bin/sh} consider that when the trap is run it is
18276 @emph{still} in the @command{exit}, hence it is the previous exit status
18277 that the trap receives:
18279 @example
18280 $ @kbd{cat trap.sh}
18281 trap 'echo $?' 0
18282 (exit 42); exit 0
18283 $ @kbd{zsh trap.sh}
18285 $ @kbd{bash trap.sh}
18287 @end example
18289 The portable solution is then simple: when you want to @samp{exit 42},
18290 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18291 set the exit status to 42 for Zsh, and the second to trigger the trap
18292 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18293 @code{AS_EXIT}.
18295 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18296 reset to 0 by empty lines if the code is inside @command{trap}.
18298 @example
18299 $ @kbd{trap 'false}
18301 echo $?' 0
18302 $ @kbd{exit}
18304 @end example
18306 @noindent
18307 Fortunately, this bug only affects @command{trap}.
18309 Several shells fail to execute an exit trap that is defined inside a
18310 subshell, when the last command of that subshell is not a builtin.  A
18311 workaround is to use @samp{exit $?} as the shell builtin.
18313 @example
18314 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18316 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18317 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18319 @end example
18321 @noindent
18322 Likewise, older implementations of @command{bash} failed to preserve
18323 @samp{$?} across an exit trap consisting of a single cleanup command.
18325 @example
18326 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18328 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18330 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18332 @end example
18334 Be aware that a trap can be called from any number of places in your
18335 script, and therefore the trap handler should not make assumptions about
18336 shell state.  For some examples, if your script temporarily modifies
18337 @env{IFS}, then the trap should include an initialization back to its
18338 typical value of space-tab-newline (autoconf does this for generated
18339 @file{configure} files).  Likewise, if your script changes the current
18340 working directory at some point after the trap is installed, then your
18341 trap cannot assume which directory it is in, and should begin by
18342 changing directories to an absolute path if that is important to the
18343 cleanup efforts (autotest does this for generated @file{testsuite}
18344 files).
18346 @item @command{true}
18347 @c -----------------
18348 @prindex @command{true}
18349 @c Info cannot handle `:' in index entries.
18350 @c @prindex @command{:}
18351 Don't worry: as far as we know @command{true} is portable.
18352 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18353 portable shell community tends to prefer using @command{:}.  This has a
18354 funny side effect: when asked whether @command{false} is more portable
18355 than @command{true} Alexandre Oliva answered:
18357 @quotation
18358 In a sense, yes, because if it doesn't exist, the shell will produce an
18359 exit status of failure, which is correct for @command{false}, but not
18360 for @command{true}.
18361 @end quotation
18363 Remember that even though @samp{:} ignores its arguments, it still takes
18364 time to compute those arguments.  It is a good idea to use double quotes
18365 around any arguments to @samp{:} to avoid time spent in field splitting
18366 and file name expansion.
18369 @anchor{unset}
18370 @item @command{unset}
18371 @c ------------------
18372 @prindex @command{unset}
18373 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18374 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18375 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18376 with @code{set -e} operation.  You can use
18378 @smallexample
18379 FOO=; unset FOO
18380 @end smallexample
18382 @noindent
18383 if you are not sure that @code{FOO} is set.
18385 A few ancient shells lack @command{unset} entirely.  For some variables
18386 such as @code{PS1}, you can use a neutralizing value instead:
18388 @smallexample
18389 PS1='$ '
18390 @end smallexample
18392 Usually, shells that do not support @command{unset} need less effort to
18393 make the environment sane, so for example is not a problem if you cannot
18394 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18395 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18396 So, you should do something like
18398 @smallexample
18399 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18400 @end smallexample
18402 @noindent
18403 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18404 @ref{export, , Limitations of Builtins}, for
18405 the case of environment variables.
18407 @item @command{wait}
18408 @c -----------------
18409 @prindex @command{wait}
18410 The exit status of @command{wait} is not always reliable.
18411 @end table
18413 @node Limitations of Usual Tools
18414 @section Limitations of Usual Tools
18415 @cindex Limitations of usual tools
18417 The small set of tools you can expect to find on any machine can still
18418 include some limitations you should be aware of.
18420 @comment Between this list and the list of builtins above, we should
18421 @comment mention all the tools in GNU Coding Standards ``Utilities in
18422 @comment Makefiles''.
18424 @c This table includes things like `@command{expr} (|)', so we can't
18425 @c use @table @command.
18426 @table @asis
18427 @anchor{awk}
18428 @item @command{awk}
18429 @c ----------------
18430 @prindex @command{awk}
18431 Don't leave white space before the opening parenthesis in a user function call.
18432 Posix does not allow this and GNU Awk rejects it:
18434 @example
18435 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18436         BEGIN @{ die () @}'}
18437 gawk: cmd. line:2:         BEGIN @{ die () @}
18438 gawk: cmd. line:2:                      ^ parse error
18439 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18440         BEGIN @{ die() @}'}
18441 Aaaaarg!
18442 @end example
18444 Posix says that if a program contains only @samp{BEGIN} actions, and
18445 contains no instances of @code{getline}, then the program merely
18446 executes the actions without reading input.  However, traditional Awk
18447 implementations (such as Solaris 10 @command{awk}) read and discard
18448 input in this case.  Portable scripts can redirect input from
18449 @file{/dev/null} to work around the problem.  For example:
18451 @example
18452 awk 'BEGIN @{print "hello world"@}' </dev/null
18453 @end example
18455 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18456 @samp{$1}) retain their value from the last record read, if no
18457 intervening @samp{getline} occurred.  However, some implementations
18458 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18459 @samp{awk}) reset these variables.  A workaround is to use an
18460 intermediate variable prior to the @samp{END} block.  For example:
18462 @example
18463 $ @kbd{cat end.awk}
18464 @{ tmp = $1 @}
18465 END @{ print "a", $1, $NF, "b", tmp @}
18466 $ @kbd{echo 1 | awk -f end.awk}
18467 a   b 1
18468 $ @kbd{echo 1 | gawk -f end.awk}
18469 a 1 1 b 1
18470 @end example
18472 If you want your program to be deterministic, don't depend on @code{for}
18473 on arrays:
18475 @example
18476 $ @kbd{cat for.awk}
18477 END @{
18478   arr["foo"] = 1
18479   arr["bar"] = 1
18480   for (i in arr)
18481     print i
18483 $ @kbd{gawk -f for.awk </dev/null}
18486 $ @kbd{nawk -f for.awk </dev/null}
18489 @end example
18491 Some Awk implementations, such as HP-UX 11.0's native one,
18492 mishandle anchors:
18494 @example
18495 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18496 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18498 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18499 xfoo
18500 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18502 @end example
18504 @noindent
18505 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18506 or use a simple test to reject such implementations.
18508 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18509 after @code{%u}:
18511 @example
18512 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18513 0 0
18514 @end example
18516 AIX version 5.2 has an arbitrary limit of 399 on the
18517 length of regular expressions and literal strings in an Awk program.
18519 Traditional Awk implementations derived from Unix version 7, such as
18520 Solaris @command{/bin/awk}, have many limitations and do not
18521 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18522 Programs}) finds you an Awk that doesn't have these problems, but if
18523 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18524 address them.  For more detailed descriptions, see @ref{Language
18525 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18527 Traditional Awk does not support multidimensional arrays or user-defined
18528 functions.
18530 Traditional Awk does not support the @option{-v} option.  You can use
18531 assignments after the program instead, e.g., @code{$AWK '@{print v
18532 $1@}' v=x}; however, don't forget that such assignments are not
18533 evaluated until they are encountered (e.g., after any @code{BEGIN}
18534 action).
18536 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18538 Traditional Awk does not support the expressions
18539 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18540 or @code{@var{a}^=@var{b}}.
18542 Traditional Awk does not support the predefined @code{CONVFMT} or
18543 @code{ENVIRON} variables.
18545 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18546 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18547 @code{sqrt}, and @code{substr}.
18549 Traditional Awk @code{getline} is not at all compatible with Posix;
18550 avoid it.
18552 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18553 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18555 In code portable to both traditional and modern Awk, @code{FS} must be a
18556 string containing just one ordinary character, and similarly for the
18557 field-separator argument to @code{split}.
18559 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18560 implementations, like Tru64's, split the input even if you don't refer
18561 to any field in the script, to circumvent this problem, set @samp{FS}
18562 to an unusual character and use @code{split}.
18564 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18565 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18566 dumps core.
18568 The original version of Awk had a limit of at most 99 bytes per
18569 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18570 per run of non-special characters in a @code{printf} format, but these
18571 bugs have been fixed on all practical hosts that we know of.
18573 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18574 of at most 3070 bytes.
18576 @item @command{basename}
18577 @c ---------------------
18578 @prindex @command{basename}
18579 Not all hosts have a working @command{basename}.
18580 You can use @command{expr} instead.
18582 @c AS_BASENAME is to be replaced by a better API.
18583 @ignore
18584 Not all hosts have a working @command{basename}, and you should instead
18585 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18586 @command{expr} if you need to strip a suffix.  For example:
18588 @example
18589 a=`basename "$aname"`       # This is not portable.
18590 a=`AS_BASENAME(["$aname"])` # This is more portable.
18592 # This is not portable.
18593 c=`basename "$cname" .c`
18595 # This is more portable.
18596 c=`AS_BASENAME(["$cname"])`
18597 case $c in
18598 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18599 esac
18600 @end example
18601 @end ignore
18604 @item @command{cat}
18605 @c ----------------
18606 @prindex @command{cat}
18607 Don't rely on any option.
18610 @item @command{cc}
18611 @c ---------------
18612 @prindex @command{cc}
18613 The command @samp{cc -c foo.c} traditionally produces an object file
18614 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18615 with @option{-o} to specify a different object file name, but
18616 Posix does not require this combination and a few compilers
18617 lack support for it.  @xref{C Compiler}, for how GNU Make
18618 tests for this feature with @code{AC_PROG_CC_C_O}.
18620 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18621 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18623 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18624 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18625 nothing.
18627 The default executable, produced by @samp{cc foo.c}, can be
18629 @itemize
18630 @item @file{a.out} --- usual Posix convention.
18631 @item @file{b.out} --- i960 compilers (including @command{gcc}).
18632 @item @file{a.exe} --- DJGPP port of @command{gcc}.
18633 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
18634 @item @file{foo.exe} --- various MS-DOS compilers.
18635 @end itemize
18637 The C compiler's traditional name is @command{cc}, but other names like
18638 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
18639 name @command{c99}, but older Posix editions specified
18640 @command{c89} and anyway these standard names are rarely used in
18641 practice.  Typically the C compiler is invoked from makefiles that use
18642 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18643 compiler name.
18645 @item @command{chgrp}
18646 @itemx @command{chown}
18647 @c -------------------
18648 @prindex @command{chgrp}
18649 @prindex @command{chown}
18650 It is not portable to change a file's group to a group that the owner
18651 does not belong to.
18653 @item @command{chmod}
18654 @c ------------------
18655 @prindex @command{chmod}
18656 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18657 instead, for two reasons.  First, plain @option{-w} does not necessarily
18658 make the file unwritable, since it does not affect mode bits that
18659 correspond to bits in the file mode creation mask.  Second,
18660 Posix says that the @option{-w} might be interpreted as an
18661 implementation-specific option, not as a mode; Posix suggests
18662 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18663 @samp{--} does not work on some older hosts.
18666 @item @command{cmp}
18667 @c ----------------
18668 @prindex @command{cmp}
18669 @command{cmp} performs a raw data comparison of two files, while
18670 @command{diff} compares two text files.  Therefore, if you might compare
18671 DOS files, even if only checking whether two files are different, use
18672 @command{diff} to avoid spurious differences due to differences of
18673 newline encoding.
18676 @item @command{cp}
18677 @c ---------------
18678 @prindex @command{cp}
18679 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18680 obsolescent and its behavior on special files is implementation-defined.
18681 Use @option{-R} instead.  On GNU hosts the two options
18682 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18683 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18684 corrupt its own memory with some directory hierarchies and error out or
18685 dump core:
18687 @example
18688 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18689 @kbd{touch 12345678/12345678/x}
18690 @kbd{cp -R 12345678 t}
18691 cp: 0653-440 12345678/12345678/: name too long.
18692 @end example
18694 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18695 trailing slashes at the end of nonexistent destination directories.  To
18696 avoid this problem, omit the trailing slashes.  For example, use
18697 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18698 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18700 @c This is thanks to Ian.
18701 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18702 its @command{mv} does.
18704 @cindex timestamp resolution
18705 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18706 -p} copied the timestamps exactly.  However, many modern file systems
18707 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18708 @samp{cp -p} implementations truncate timestamps when copying files,
18709 which can cause the destination file to appear to be older than the
18710 source.  The exact amount of truncation depends on the resolution of
18711 the system calls that @command{cp} uses.  Traditionally this was
18712 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18713 implementations such as GNU Core Utilities 5.0.91 (2003) use
18714 @code{utimes}, which has 1-microsecond resolution.  Modern
18715 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18716 the full nanosecond resolution, using the modern system calls
18717 @code{futimens} and @code{utimensat} when they are available.  As of
18718 2011, though, many platforms do not yet fully support these new system
18719 calls.
18721 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18722 ownerships.  But whether it actually does copy ownerships or not is a
18723 system dependent policy decision implemented by the kernel.  If the
18724 kernel allows it then it happens.  If the kernel does not allow it then
18725 it does not happen.  It is not something @command{cp} itself has control
18726 over.
18728 In Unix System V any user can chown files to any other user, and System
18729 V also has a non-sticky @file{/tmp}.  That probably derives from the
18730 heritage of System V in a business environment without hostile users.
18731 BSD changed this
18732 to be a more secure model where only root can @command{chown} files and
18733 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18734 of BSD in a campus environment.
18736 GNU/Linux and Solaris by default follow BSD, but
18737 can be configured to allow a System V style @command{chown}.  On the
18738 other hand, HP-UX follows System V, but can
18739 be configured to use the modern security model and disallow
18740 @command{chown}.  Since it is an administrator-configurable parameter
18741 you can't use the name of the kernel as an indicator of the behavior.
18745 @item @command{date}
18746 @c -----------------
18747 @prindex @command{date}
18748 Some versions of @command{date} do not recognize special @samp{%} directives,
18749 and unfortunately, instead of complaining, they just pass them through,
18750 and exit with success:
18752 @example
18753 $ @kbd{uname -a}
18754 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18755 $ @kbd{date "+%s"}
18757 @end example
18760 @item @command{diff}
18761 @c -----------------
18762 @prindex @command{diff}
18763 Option @option{-u} is nonportable.
18765 Some implementations, such as Tru64's, fail when comparing to
18766 @file{/dev/null}.  Use an empty file instead.
18769 @item @command{dirname}
18770 @c --------------------
18771 @prindex @command{dirname}
18772 Not all hosts have a working @command{dirname}, and you should instead
18773 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18775 @example
18776 dir=`dirname "$file"`       # This is not portable.
18777 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18778 @end example
18781 @item @command{egrep}
18782 @c ------------------
18783 @prindex @command{egrep}
18784 Posix 1003.1-2001 no longer requires @command{egrep},
18785 but many hosts do not yet support the Posix
18786 replacement @code{grep -E}.  Also, some traditional implementations do
18787 not work on long input lines.  To work around these problems, invoke
18788 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18790 Portable extended regular expressions should use @samp{\} only to escape
18791 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18792 is not portable, even though it typically matches @samp{@}}.
18794 The empty alternative is not portable.  Use @samp{?} instead.  For
18795 instance with Digital Unix v5.0:
18797 @example
18798 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18799 |foo
18800 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18801 bar|
18802 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18804 |bar
18805 @end example
18807 @command{$EGREP} also suffers the limitations of @command{grep}
18808 (@pxref{grep, , Limitations of Usual Tools}).
18810 @item @command{expr}
18811 @c -----------------
18812 @prindex @command{expr}
18813 Not all implementations obey the Posix rule that @samp{--} separates
18814 options from arguments; likewise, not all implementations provide the
18815 extension to Posix that the first argument can be treated as part of a
18816 valid expression rather than an invalid option if it begins with
18817 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18818 @samp{$var} might be a negative number, to keep @command{expr} from
18819 interpreting it as an option.
18821 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18822 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18823 misinterpreting @var{word}.
18825 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18827 @item @command{expr} (@samp{|})
18828 @prindex @command{expr} (@samp{|})
18829 You can use @samp{|}.  Although Posix does require that @samp{expr
18830 ''} return the empty string, it does not specify the result when you
18831 @samp{|} together the empty string (or zero) with the empty string.  For
18832 example:
18834 @example
18835 expr '' \| ''
18836 @end example
18838 Posix 1003.2-1992 returns the empty string
18839 for this case, but traditional Unix returns @samp{0} (Solaris is
18840 one such example).  In Posix 1003.1-2001, the specification was
18841 changed to match traditional Unix's behavior (which is
18842 bizarre, but it's too late to fix this).  Please note that the same
18843 problem does arise when the empty string results from a computation,
18844 as in:
18846 @example
18847 expr bar : foo \| foo : bar
18848 @end example
18850 @noindent
18851 Avoid this portability problem by avoiding the empty string.
18854 @item @command{expr} (@samp{:})
18855 @c ----------------------------
18856 @prindex @command{expr}
18857 Portable @command{expr} regular expressions should use @samp{\} to
18858 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18859 For example, alternation, @samp{\|}, is common but Posix does not
18860 require its support, so it should be avoided in portable scripts.
18861 Similarly, @samp{\+} and @samp{\?} should be avoided.
18863 Portable @command{expr} regular expressions should not begin with
18864 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18865 not needed anyway.
18867 On the other hand, the behavior of the @samp{$} anchor is not portable
18868 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18869 each line, as was done in older versions of the GNU Core Utilities, or
18870 whether it applies only to the end of the overall string, as in
18871 Coreutils 6.0 and most other implementations.
18873 @example
18874 $ @kbd{baz='foo}
18875 > @kbd{bar'}
18876 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18878 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18880 @end example
18882 The Posix standard is ambiguous as to whether
18883 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18884 In practice, it outputs the empty string on most platforms, but portable
18885 scripts should not assume this.  For instance, the QNX 4.25 native
18886 @command{expr} returns @samp{0}.
18888 One might think that a way to get a uniform behavior would be to use
18889 the empty string as a default value:
18891 @example
18892 expr a : '\(b\)' \| ''
18893 @end example
18895 @noindent
18896 Unfortunately this behaves exactly as the original expression; see the
18897 @command{expr} (@samp{|}) entry for more information.
18899 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18900 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18901 @command{expr} to fail if the matched substring is longer than 120
18902 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18903 @command{expr} fails.  Nowadays this is of practical importance only for
18904 the rare installer who mistakenly puts @file{/usr/ucb} before
18905 @file{/usr/bin} in @env{PATH}.
18907 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18908 some cases.  For example, the command
18909 @example
18910 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18911 @end example
18913 @noindent
18914 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18915 This particular case can be worked around by substituting @samp{[^--]}
18916 for @samp{[^-]}.
18918 Don't leave, there is some more!
18920 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18921 the empty string, has a funny behavior in its exit status: it's always 1
18922 when parentheses are used!
18924 @example
18925 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
18926 0: 1
18927 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
18928 1: 0
18930 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
18931 1: a
18932 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
18933 1: 0
18934 @end example
18936 @noindent
18937 In practice this can be a big problem if you are ready to catch failures
18938 of @command{expr} programs with some other method (such as using
18939 @command{sed}), since you may get twice the result.  For instance
18941 @example
18942 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18943 @end example
18945 @noindent
18946 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18947 simple workaround consists of testing @command{expr} and using a variable
18948 set to @command{expr} or to @command{false} according to the result.
18950 Tru64 @command{expr} incorrectly treats the result as a number, if it
18951 can be interpreted that way:
18953 @example
18954 $ @kbd{expr 00001 : '.*\(...\)'}
18956 @end example
18958 On HP-UX 11, @command{expr} only supports a single
18959 sub-expression.
18961 @example
18962 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18963 expr: More than one '\(' was used.
18964 @end example
18967 @item @command{fgrep}
18968 @c ------------------
18969 @prindex @command{fgrep}
18970 Posix 1003.1-2001 no longer requires @command{fgrep},
18971 but many hosts do not yet support the Posix
18972 replacement @code{grep -F}.  Also, some traditional implementations do
18973 not work on long input lines.  To work around these problems, invoke
18974 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
18976 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18979 @item @command{find}
18980 @c -----------------
18981 @prindex @command{find}
18982 The option @option{-maxdepth} seems to be GNU specific.
18983 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18984 commands do not understand it.
18986 The replacement of @samp{@{@}} is guaranteed only if the argument is
18987 exactly @emph{@{@}}, not if it's only a part of an argument.  For
18988 instance on DU, and HP-UX 10.20 and HP-UX 11:
18990 @example
18991 $ @kbd{touch foo}
18992 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18993 @{@}-@{@}
18994 @end example
18996 @noindent
18997 while GNU @command{find} reports @samp{./foo-./foo}.
19000 @anchor{grep}
19001 @item @command{grep}
19002 @c -----------------
19003 @prindex @command{grep}
19004 Portable scripts can rely on the @command{grep} options @option{-c},
19005 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19006 options.  For example, don't use @option{-w}, as Posix does not require
19007 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19008 portable scripts should not combine @option{-c} with @option{-l},
19009 as Posix does not allow this.
19011 Some of the options required by Posix are not portable in practice.
19012 Don't use @samp{grep -q} to suppress output, because many @command{grep}
19013 implementations (e.g., Solaris) do not support @option{-q}.
19014 Don't use @samp{grep -s} to suppress output either, because Posix
19015 says @option{-s} does not suppress output, only some error messages;
19016 also, the @option{-s} option of traditional @command{grep} behaved
19017 like @option{-q} does in most modern implementations.  Instead,
19018 redirect the standard output and standard error (in case the file
19019 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19020 status of @code{grep} to determine whether it found a match.
19022 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19023 but works with @code{grep -c '^'}.  Other alternatives for counting
19024 lines are to use @code{sed -n '$='} or @code{wc -l}.
19026 Some traditional @command{grep} implementations do not work on long
19027 input lines.  On AIX the default @code{grep} silently truncates long
19028 lines on the input before matching.
19030 Also, many implementations do not support multiple regexps
19031 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19032 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19033 work around these problems, invoke @code{AC_PROG_GREP} and then use
19034 @code{$GREP}.
19036 Another possible workaround for the multiple @option{-e} problem is to
19037 separate the patterns by newlines, for example:
19039 @example
19040 grep 'foo
19041 bar' in.txt
19042 @end example
19044 @noindent
19045 except that this fails with traditional @command{grep}
19046 implementations and with OpenBSD 3.8 @command{grep}.
19048 Traditional @command{grep} implementations (e.g., Solaris) do not
19049 support the @option{-E} or @option{-F} options.  To work around these
19050 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19051 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19052 willing to require support for Posix @command{grep}, your script should
19053 not use both @option{-E} and @option{-F}, since Posix does not allow
19054 this combination.
19056 Portable @command{grep} regular expressions should use @samp{\} only to
19057 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19058 alternation, @samp{\|}, is common but Posix does not require its
19059 support in basic regular expressions, so it should be avoided in
19060 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19061 Similarly, the following escape sequences should also be avoided:
19062 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19063 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19065 Posix does not specify the behavior of @command{grep} on binary files.
19066 An example where this matters is using BSD @command{grep} to
19067 search text that includes embedded ANSI escape sequences for
19068 colored output to terminals (@samp{\033[m} is the sequence to restore
19069 normal output); the behavior depends on whether input is seekable:
19071 @example
19072 $ @kbd{printf 'esc\033[mape\n' > sample}
19073 $ @kbd{grep . sample}
19074 Binary file sample matches
19075 $ @kbd{cat sample | grep .}
19076 escape
19077 @end example
19080 @item @command{join}
19081 @c -----------------
19082 @prindex @command{join}
19083 Solaris 8 @command{join} has bugs when the second operand is standard
19084 input, and when standard input is a pipe.  For example, the following
19085 shell script causes Solaris 8 @command{join} to loop forever:
19087 @example
19088 cat >file <<'EOF'
19089 1 x
19090 2 y
19092 cat file | join file -
19093 @end example
19095 Use @samp{join - file} instead.
19097 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19098 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19099 the workaround is to use @command{join -a1 file1 file2} instead.
19101 @item @command{ln}
19102 @c ---------------
19103 @prindex @command{ln}
19104 @cindex Symbolic links
19105 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
19106 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
19108 For versions of the DJGPP before 2.04,
19109 @command{ln} emulates symbolic links
19110 to executables by generating a stub that in turn calls the real
19111 program.  This feature also works with nonexistent files like in the
19112 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19113 which attempts to call @file{file.exe} if run.  But this feature only
19114 works for executables, so @samp{cp -p} is used instead for these
19115 systems.  DJGPP versions 2.04 and later have full support
19116 for symbolic links.
19119 @item @command{ls}
19120 @c ---------------
19121 @prindex @command{ls}
19122 @cindex Listing directories
19123 The portable options are @option{-acdilrtu}.  Current practice is for
19124 @option{-l} to output both owner and group, even though ancient versions
19125 of @command{ls} omitted the group.
19127 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19128 to standard output if @file{foo} did not exist.  Hence a shell command
19129 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19130 was equivalent to @samp{sources='*.c not found'} in the absence of
19131 @samp{.c} files.  This is no longer a practical problem, since current
19132 @command{ls} implementations send diagnostics to standard error.
19134 The behavior of @command{ls} on a directory that is being concurrently
19135 modified is not always predictable, because of a data race where cached
19136 information returned by @code{readdir} does not match the current
19137 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19138 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19139 once if other files were added or removed from the directory immediately
19140 prior to the @command{ls} call.  Since @command{ls} already sorts its
19141 output, the duplicate entries can be avoided by piping the results
19142 through @code{uniq}.
19144 @anchor{mkdir}
19145 @item @command{mkdir}
19146 @c ------------------
19147 @prindex @command{mkdir}
19148 @cindex Making directories
19149 No @command{mkdir} option is portable to older systems.  Instead of
19150 @samp{mkdir -p @var{file-name}}, you should use
19151 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19152 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19154 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19155 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19156 @command{mkdir} incorrectly attempts to change the permissions of
19157 @var{dir} even if it already exists.  HP-UX 11.23 and
19158 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19159 any newly-created parents of @var{dir}.
19161 Posix does not clearly specify whether @samp{mkdir -p foo}
19162 should succeed when @file{foo} is a symbolic link to an already-existing
19163 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19164 succeeds, but Solaris @command{mkdir} fails.
19166 Traditional @code{mkdir -p} implementations suffer from race conditions.
19167 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19168 at the same time, both processes might detect that @file{a} is missing,
19169 one might create @file{a}, then the other might try to create @file{a}
19170 and fail with a @code{File exists} diagnostic.  The GNU Core
19171 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19172 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19173 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19174 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19175 vulnerable as of Solaris 10, and other traditional Unix systems are
19176 probably vulnerable too.  This possible race is harmful in parallel
19177 builds when several Make rules call @code{mkdir -p} to
19178 construct directories.  You may use
19179 @code{install-sh -d} as a safe replacement, provided this script is
19180 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19181 OK, but copies from older versions are vulnerable.
19184 @item @command{mkfifo}
19185 @itemx @command{mknod}
19186 @c -------------------
19187 @prindex @command{mkfifo}
19188 @prindex @command{mknod}
19189 The GNU Coding Standards state that @command{mknod} is safe to use on
19190 platforms where it has been tested to exist; but it is generally portable
19191 only for creating named FIFOs, since device numbers are
19192 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19193 testsuites.  Posix states that behavior is unspecified when opening a
19194 named FIFO for both reading and writing; on at least Cygwin, this
19195 results in failure on any attempt to read or write to that file
19196 descriptor.
19198 @item @command{mktemp}
19199 @c -------------------
19200 @prindex @command{mktemp}
19201 @cindex Creating temporary files
19202 Shell scripts can use temporary files safely with @command{mktemp}, but
19203 it does not exist on all systems.  A portable way to create a safe
19204 temporary file name is to create a temporary directory with mode 700 and
19205 use a file inside this directory.  Both methods prevent attackers from
19206 gaining control, though @command{mktemp} is far less likely to fail
19207 gratuitously under attack.
19209 Here is sample code to create a new temporary directory @samp{$dir} safely:
19211 @example
19212 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19213 # Use mktemp if possible; otherwise fall back on mkdir,
19214 # with $RANDOM to make collisions less likely.
19215 : "$@{TMPDIR:=/tmp@}"
19217   dir=`
19218     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19219   ` &&
19220   test -d "$dir"
19221 @} || @{
19222   dir=$TMPDIR/foo$$-$RANDOM
19223 @c $$ restore font-lock
19224   (umask 077 && mkdir "$dir")
19225 @} || exit $?
19226 @end example
19229 @item @command{mv}
19230 @c ---------------
19231 @prindex @command{mv}
19232 @cindex Moving open files
19233 The only portable options are @option{-f} and @option{-i}.
19235 Moving individual files between file systems is portable (it was in Unix
19236 version 6),
19237 but it is not always atomic: when doing @samp{mv new existing}, there's
19238 a critical section where neither the old nor the new version of
19239 @file{existing} actually exists.
19241 On some systems moving files from @file{/tmp} can sometimes cause
19242 undesirable (but perfectly valid) warnings, even if you created these
19243 files.  This is because @file{/tmp} belongs to a group that ordinary
19244 users are not members of, and files created in @file{/tmp} inherit
19245 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19246 a diagnostic without failing:
19248 @smallexample
19249 $ @kbd{touch /tmp/foo}
19250 $ @kbd{mv /tmp/foo .}
19251 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19252 $ @kbd{echo $?}
19254 $ @kbd{ls foo}
19256 @end smallexample
19258 @noindent
19259 This annoying behavior conforms to Posix, unfortunately.
19261 Moving directories across mount points is not portable, use @command{cp}
19262 and @command{rm}.
19264 DOS variants cannot rename or remove open files, and do not
19265 support commands like @samp{mv foo bar >foo}, even though this is
19266 perfectly portable among Posix hosts.
19269 @item @command{od}
19270 @c ---------------
19271 @prindex @command{od}
19273 In Mac OS X 10.3, @command{od} does not support the
19274 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19275 @option{-t}, or the XSI option @option{-s}.  The only
19276 supported Posix option is @option{-v}, and the only supported
19277 XSI options are those in @option{-bcdox}.  The BSD
19278 @command{hexdump} program can be used instead.
19280 This problem no longer exists in Mac OS X 10.4.3.
19283 @item @command{rm}
19284 @c ---------------
19285 @prindex @command{rm}
19286 The @option{-f} and @option{-r} options are portable.
19288 It is not portable to invoke @command{rm} without options or operands.
19289 On the other hand, Posix now requires @command{rm -f} to silently
19290 succeed when there are no operands (useful for constructs like
19291 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19292 was empty).  But this was not always portable; at least NetBSD
19293 @command{rm} built before 2008 would fail with a diagnostic.
19295 A file might not be removed even if its parent directory is writable
19296 and searchable.  Many Posix hosts cannot remove a mount point, a named
19297 stream, a working directory, or a last link to a file that is being
19298 executed.
19300 DOS variants cannot rename or remove open files, and do not
19301 support commands like @samp{rm foo >foo}, even though this is
19302 perfectly portable among Posix hosts.
19304 @item @command{rmdir}
19305 @c ------------------
19306 @prindex @command{rmdir}
19307 Just as with @command{rm}, some platforms refuse to remove a working
19308 directory.
19310 @anchor{sed}
19311 @item @command{sed}
19312 @c ----------------
19313 @prindex @command{sed}
19314 Patterns should not include the separator (unless escaped), even as part
19315 of a character class.  In conformance with Posix, the Cray
19316 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19317 Even when escaped, patterns should not include separators that are also
19318 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19319 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19320 before evaluating the basic regular expression.
19322 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19323 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19324 them.
19326 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19328 Sed scripts should not use branch labels longer than 7 characters and
19329 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19330 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19331 48 labels, which cannot be circumvented by using more than one script
19332 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19333 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19334 about 6000 bytes for the internal representation of commands.
19336 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19337 NetBSD 1.4.2's, incorrectly try to interpret the second
19338 @samp{;} as a command:
19340 @example
19341 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19342 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19343 @end example
19345 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19346 and this limits the size of input lines, output lines, and internal
19347 buffers that can be processed portably.  Likewise,
19348 not all @command{sed} implementations can handle embedded @code{NUL} or
19349 a missing trailing newline.
19351 Remember that ranges within a bracket expression of a regular expression
19352 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19353 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19354 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19355 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19356 than to rely on @samp{[A-Z]}.
19358 Additionally, Posix states that regular expressions are only
19359 well-defined on characters.  Unfortunately, there exist platforms such
19360 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19361 even though that platform has a single-byte @samp{C} locale.  And Posix
19362 allows the existence of a multi-byte @samp{C} locale, although that does
19363 not yet appear to be a common implementation.  At any rate, it means
19364 that not all bytes will be matched by the regular expression @samp{.}:
19366 @example
19367 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19369 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19371 @end example
19373 Portable @command{sed} regular expressions should use @samp{\} only to escape
19374 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19375 alternation, @samp{\|}, is common but Posix does not require its
19376 support, so it should be avoided in portable scripts.  Solaris
19377 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19378 deletes only lines that contain the literal string @samp{a|b}.
19379 Similarly, @samp{\+} and @samp{\?} should be avoided.
19381 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19383 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19384 quite portable to current hosts, but was not supported by some ancient
19385 @command{sed} implementations like SVR3.
19387 Some @command{sed} implementations, e.g., Solaris, restrict the special
19388 role of the asterisk @samp{*} to one-character regular expressions and
19389 back-references, and the special role of interval expressions
19390 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19391 to one-character regular expressions.  This may lead to unexpected behavior:
19393 @example
19394 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19395 x2x4
19396 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19398 @end example
19400 The @option{-e} option is mostly portable.
19401 However, its argument
19402 cannot start with @samp{a}, @samp{c}, or @samp{i},
19403 as this runs afoul of a Tru64 5.1 bug.
19404 Also, its argument cannot be empty, as this fails on AIX 5.3.
19405 Some people prefer to use @samp{-e}:
19407 @example
19408 sed -e '@var{command-1}' \
19409     -e '@var{command-2}'
19410 @end example
19412 @noindent
19413 as opposed to the equivalent:
19415 @example
19416 sed '
19417   @var{command-1}
19418   @var{command-2}
19420 @end example
19422 @noindent
19423 The following usage is sometimes equivalent:
19425 @example
19426 sed '@var{command-1};@var{command-2}'
19427 @end example
19429 but Posix says that this use of a semicolon has undefined effect if
19430 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19431 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19432 should use semicolon only with simple scripts that do not use these
19433 verbs.
19435 Posix up to the 2008 revision requires the argument of the @option{-e}
19436 option to be a syntactically complete script.  GNU @command{sed} allows
19437 to pass multiple script fragments, each as argument of a separate
19438 @option{-e} option, that are then combined, with newlines between the
19439 fragments, and a future Posix revision may allow this as well.  This
19440 approach is not portable with script fragments ending in backslash; for
19441 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19442 don't allow splitting in this case:
19444 @example
19445 $ @kbd{echo a | sed -n -e 'i\}
19446 @kbd{0'}
19448 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19449 Unrecognized command: 0
19450 @end example
19452 @noindent
19453 In practice, however, this technique of joining fragments
19454 through @option{-e} works for multiple @command{sed} functions within
19455 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19457 @example
19458 @c The quote around the closing brace silences interactive zsh.
19459 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19461 @end example
19463 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19464 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19465 each command must be followed immediately by a newline, without any
19466 intervening blanks or semicolons.  The closing bracket must be alone on
19467 a line, other than white space preceding or following it.  However, a
19468 future version of Posix may standardize the use of addresses within brackets.
19470 Contrary to yet another urban legend, you may portably use @samp{&} in
19471 the replacement part of the @code{s} command to mean ``what was
19472 matched''.  All descendants of Unix version 7 @command{sed}
19473 (at least; we
19474 don't have first hand experience with older @command{sed} implementations) have
19475 supported it.
19477 Posix requires that you must not have any white space between
19478 @samp{!} and the following command.  It is OK to have blanks between
19479 the address and the @samp{!}.  For instance, on Solaris:
19481 @example
19482 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19483 @error{}Unrecognized command: /bar/ ! p
19484 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19485 @error{}Unrecognized command: /bar/! p
19486 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19488 @end example
19490 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19491 you use @samp{!}, it is best to put it on a command that is delimited by
19492 newlines rather than @samp{;}.
19494 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19495 @samp{w} commands be followed by exactly one space before their argument.
19496 On the other hand, no white space is allowed between @samp{:} and the
19497 subsequent label name.
19499 If a sed script is specified on the command line and ends in an
19500 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19501 should be followed by a newline.  Otherwise some @command{sed}
19502 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19503 inserted text.
19505 Many @command{sed} implementations (e.g., MacOS X 10.4,
19506 OpenBSD 3.9, Solaris 10
19507 @command{/usr/ucb/sed}) strip leading white space from the text of
19508 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19509 work around this incompatibility with Posix:
19511 @example
19512 $ @kbd{echo flushleft | sed 'a\}
19513 > @kbd{   indented}
19514 > @kbd{'}
19515 flushleft
19516 indented
19517 $ @kbd{echo foo | sed 'a\}
19518 > @kbd{\   indented}
19519 > @kbd{'}
19520 flushleft
19521    indented
19522 @end example
19524 Posix requires that with an empty regular expression, the last non-empty
19525 regular expression from either an address specification or substitution
19526 command is applied.  However, busybox 1.6.1 complains when using a
19527 substitution command with a replacement containing a back-reference to
19528 an empty regular expression; the workaround is repeating the regular
19529 expression.
19531 @example
19532 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19533 sed: No previous regexp.
19534 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19536 @end example
19539 @item @command{sed} (@samp{t})
19540 @c ---------------------------
19541 @prindex @command{sed} (@samp{t})
19542 Some old systems have @command{sed} that ``forget'' to reset their
19543 @samp{t} flag when starting a new cycle.  For instance on MIPS
19544 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19545 script (the line numbers are not actual part of the texts):
19547 @example
19548 s/keep me/kept/g  # a
19549 t end             # b
19550 s/.*/deleted/g    # c
19551 :end              # d
19552 @end example
19554 @noindent
19557 @example
19558 delete me         # 1
19559 delete me         # 2
19560 keep me           # 3
19561 delete me         # 4
19562 @end example
19564 @noindent
19565 you get
19567 @example
19568 deleted
19569 delete me
19570 kept
19571 deleted
19572 @end example
19574 @noindent
19575 instead of
19577 @example
19578 deleted
19579 deleted
19580 kept
19581 deleted
19582 @end example
19584 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19585 flag, and the output is produced.  When processing
19586 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19587 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19588 flag when a substitution fails.  Command (b) sees that the flag is set,
19589 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19590 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19591 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19592 Finally, since the flag is clear, line 4 is processed properly.
19594 There are two things one should remember about @samp{t} in @command{sed}.
19595 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19596 succeeded, not only the immediately preceding substitution.  Therefore,
19597 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19598 line, to reset the @samp{t} flag where needed.
19600 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19601 cycle.
19603 One portable implementation of the script above is:
19605 @example
19606 t clear
19607 :clear
19608 s/keep me/kept/g
19609 t end
19610 s/.*/deleted/g
19611 :end
19612 @end example
19614 @item @command{sleep}
19615 @c ------------------
19616 @prindex @command{sleep}
19617 Using @command{sleep} is generally portable.  However, remember that
19618 adding a @command{sleep} to work around timestamp issues, with a minimum
19619 granularity of one second, doesn't scale well for parallel builds on
19620 modern machines with sub-second process completion.
19622 @item @command{sort}
19623 @c -----------------
19624 @prindex @command{sort}
19625 Remember that sort order is influenced by the current locale.  Inside
19626 @file{configure}, the C locale is in effect, but in Makefile snippets,
19627 you may need to specify @code{LC_ALL=C sort}.
19629 @item @command{tar}
19630 @c ----------------
19631 @prindex @command{tar}
19632 There are multiple file formats for @command{tar}; if you use Automake,
19633 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19634 level of portability to use.
19636 @anchor{touch}
19637 @item @command{touch}
19638 @c ------------------
19639 @prindex @command{touch}
19640 @cindex timestamp resolution
19641 If you specify the desired timestamp (e.g., with the @option{-r}
19642 option), older @command{touch} implementations use the @code{utime} or
19643 @code{utimes} system call, which can result in the same kind of
19644 timestamp truncation problems that @samp{cp -p} has.
19646 On ancient BSD systems, @command{touch} or any command that
19647 results in an empty file does not update the timestamps, so use a
19648 command like @command{echo} as a workaround.
19649 Also,
19650 GNU @command{touch} 3.16r (and presumably all before that)
19651 fails to work on SunOS 4.1.3 when the empty file is on an
19652 NFS-mounted 4.2 volume.
19653 However, these problems are no longer of practical concern.
19655 @item @command{tr}
19656 @c ---------------
19657 @prindex @command{tr}
19658 @cindex carriage return, deleting
19659 @cindex newline, deleting
19660 @cindex deleting carriage return
19661 Not all versions of @command{tr} handle all backslash character escapes.
19662 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19663 Solaris contains more modern @command{tr} in other locations.
19664 Using octal escapes is more portable for carriage returns, since
19665 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19666 literal carriage returns in scripts causes a number of other problems.
19667 But for other characters, like newline, using octal escapes ties the
19668 operation to ASCII, so it is better to use literal characters.
19670 @example
19671 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19673 light
19674 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19675 moonlight
19676 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19677 moonlight
19678 $ @kbd{nl='}
19679 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19680 moonlight
19681 @end example
19683 Not all versions of @command{tr} recognize direct ranges of characters: at
19684 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19685 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19686 transliterate to themselves).
19688 @example
19689 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19690 HAZy FAntAZy
19691 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19692 HAZY FANTAZY
19693 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19694 HAZY FANTAZY
19695 @end example
19697 When providing two arguments, be sure the second string is at least as
19698 long as the first.
19700 @example
19701 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19703 $ @kbd{echo abc | coreutils/tr bc d}
19705 @end example
19707 Posix requires @command{tr} to operate on binary files.  But at least
19708 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19709 @code{NUL} in the input prior to doing any translation.  When using
19710 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19711 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19712 @command{/usr/xpg6/bin/tr} if that is available.
19714 @example
19715 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19716  61 62
19717 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19718  61 62
19719 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19720  61 00 62
19721 @end example
19723 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19724 octal escape for @code{NUL}.
19726 @example
19727 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19728  61 62 63
19729 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19730  61 00 64
19731 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19732  61 00 64
19733 @end example
19735 @end table
19738 @node Portable Make
19739 @chapter Portable Make Programming
19740 @prindex @command{make}
19741 @cindex Limitations of @command{make}
19743 Writing portable makefiles is an art.  Since a makefile's commands are
19744 executed by the shell, you must consider the shell portability issues
19745 already mentioned.  However, other issues are specific to @command{make}
19746 itself.
19748 @menu
19749 * $< in Ordinary Make Rules::   $< in ordinary rules
19750 * Failure in Make Rules::       Failing portably in rules
19751 * Special Chars in Names::      Special Characters in Macro Names
19752 * Backslash-Newline-Empty::     Empty lines after backslash-newline
19753 * Backslash-Newline Comments::  Spanning comments across line boundaries
19754 * Long Lines in Makefiles::     Line length limitations
19755 * Macros and Submakes::         @code{make macro=value} and submakes
19756 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19757 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19758 * Parallel Make::               Parallel @command{make} quirks
19759 * Comments in Make Rules::      Other problems with Make comments
19760 * Newlines in Make Rules::      Using literal newlines in rules
19761 * Comments in Make Macros::     Other problems with Make comments in macros
19762 * Trailing whitespace in Make Macros::  Macro substitution problems
19763 * Command-line Macros and whitespace::  Whitespace trimming of values
19764 * obj/ and Make::               Don't name a subdirectory @file{obj}
19765 * make -k Status::              Exit status of @samp{make -k}
19766 * VPATH and Make::              @code{VPATH} woes
19767 * Single Suffix Rules::         Single suffix rules and separated dependencies
19768 * Timestamps and Make::         Subsecond timestamp resolution
19769 @end menu
19771 @node $< in Ordinary Make Rules
19772 @section @code{$<} in Ordinary Make Rules
19774 Posix says that the @samp{$<} construct in makefiles can be
19775 used only in inference rules and in the @samp{.DEFAULT} rule; its
19776 meaning in ordinary rules is unspecified.  Solaris @command{make}
19777 for instance replaces it with the empty string.  OpenBSD (3.0 and
19778 later) @command{make} diagnoses these uses and errors out.
19780 @node Failure in Make Rules
19781 @section Failure in Make Rules
19783 Posix 2008 requires that @command{make} must invoke each command with
19784 the equivalent of a @samp{sh -e -c} subshell, which causes the
19785 subshell to exit immediately if a subsidiary simple-command fails,
19786 although not all @command{make} implementations have historically
19787 followed this rule.  For
19788 example, the command @samp{touch T; rm -f U} may attempt to
19789 remove @file{U} even if the @command{touch} fails, although this is not
19790 permitted with Posix make.  One way to work around failures in simple
19791 commands is to reword them so that they always succeed, e.g., @samp{touch
19792 T || :; rm -f U}.
19793 However, even this approach can run into common bugs in BSD
19794 implementations of the @option{-e} option of @command{sh} and
19795 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19796 are worried
19797 about porting to buggy BSD shells it may be simpler to migrate
19798 complicated @command{make} actions into separate scripts.
19800 @node Special Chars in Names
19801 @section Special Characters in Make Macro Names
19803 Posix limits macro names to nonempty strings containing only
19804 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19805 @command{make} implementations allow a wider variety of characters, but
19806 portable makefiles should avoid them.  It is portable to start a name
19807 with a special character, e.g., @samp{$(.FOO)}.
19809 Some ancient @command{make} implementations don't support leading
19810 underscores in macro names.  An example is NEWS-OS 4.2R.
19812 @example
19813 $ @kbd{cat Makefile}
19814 _am_include = #
19815 _am_quote =
19816 all:; @@echo this is test
19817 $ @kbd{make}
19818 Make: Must be a separator on rules line 2.  Stop.
19819 $ @kbd{cat Makefile2}
19820 am_include = #
19821 am_quote =
19822 all:; @@echo this is test
19823 $ @kbd{make -f Makefile2}
19824 this is test
19825 @end example
19827 @noindent
19828 However, this problem is no longer of practical concern.
19830 @node Backslash-Newline-Empty
19831 @section Backslash-Newline Before Empty Lines
19833 A bug in Bash 2.03 can cause problems if a Make rule contains a
19834 backslash-newline followed by line that expands to nothing.
19835 For example, on Solaris 8:
19837 @example
19838 SHELL = /bin/bash
19839 EMPTY =
19840 foo:
19841         touch foo \
19842         $(EMPTY)
19843 @end example
19845 @noindent
19846 executes
19848 @example
19849 /bin/bash -c 'touch foo \
19851 @end example
19853 @noindent
19854 which fails with a syntax error, due to the Bash bug.  To avoid this
19855 problem, avoid nullable macros in the last line of a multiline command.
19857 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19858 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19859 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19860 On some versions of HP-UX, @command{make} reads multiple newlines
19861 following a backslash, continuing to the next non-empty line.  For
19862 example,
19864 @example
19865 FOO = one \
19867 BAR = two
19869 test:
19870         : FOO is "$(FOO)"
19871         : BAR is "$(BAR)"
19872 @end example
19874 @noindent
19875 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19876 sensibly let a backslash continue only to the immediately following
19877 line.
19879 @node Backslash-Newline Comments
19880 @section Backslash-Newline in Make Comments
19882 According to Posix, Make comments start with @code{#}
19883 and continue until an unescaped newline is reached.
19885 @example
19886 $ @kbd{cat Makefile}
19887 # A = foo \
19888       bar \
19889       baz
19891 all:
19892         @@echo ok
19893 $ @kbd{make}   # GNU make
19895 @end example
19897 @noindent
19898 However this is not always the case.  Some implementations
19899 discard everything from @code{#} through the end of the line, ignoring any
19900 trailing backslash.
19902 @example
19903 $ @kbd{pmake}  # BSD make
19904 "Makefile", line 3: Need an operator
19905 Fatal errors encountered -- cannot continue
19906 @end example
19908 @noindent
19909 Therefore, if you want to comment out a multi-line definition, prefix each
19910 line with @code{#}, not only the first.
19912 @example
19913 # A = foo \
19914 #     bar \
19915 #     baz
19916 @end example
19918 @node Long Lines in Makefiles
19919 @section Long Lines in Makefiles
19921 Tru64 5.1's @command{make} has been reported to crash when given a
19922 makefile with lines longer than around 20 kB.  Earlier versions are
19923 reported to exit with @code{Line too long} diagnostics.
19925 @node Macros and Submakes
19926 @section @code{make macro=value} and Submakes
19928 A command-line variable definition such as @code{foo=bar} overrides any
19929 definition of @code{foo} in a makefile.  Some @command{make}
19930 implementations (such as GNU @command{make}) propagate this
19931 override to subsidiary invocations of @command{make}.  Some other
19932 implementations do not pass the substitution along to submakes.
19934 @example
19935 $ @kbd{cat Makefile}
19936 foo = foo
19937 one:
19938         @@echo $(foo)
19939         $(MAKE) two
19940 two:
19941         @@echo $(foo)
19942 $ @kbd{make foo=bar}            # GNU make 3.79.1
19944 make two
19945 make[1]: Entering directory `/home/adl'
19947 make[1]: Leaving directory `/home/adl'
19948 $ @kbd{pmake foo=bar}           # BSD make
19950 pmake two
19952 @end example
19954 You have a few possibilities if you do want the @code{foo=bar} override
19955 to propagate to submakes.  One is to use the @option{-e}
19956 option, which causes all environment variables to have precedence over
19957 the makefile macro definitions, and declare foo as an environment
19958 variable:
19960 @example
19961 $ @kbd{env foo=bar make -e}
19962 @end example
19964 The @option{-e} option is propagated to submakes automatically,
19965 and since the environment is inherited between @command{make}
19966 invocations, the @code{foo} macro is overridden in
19967 submakes as expected.
19969 This syntax (@code{foo=bar make -e}) is portable only when used
19970 outside of a makefile, for instance from a script or from the
19971 command line.  When run inside a @command{make} rule, GNU
19972 @command{make} 3.80 and prior versions forget to propagate the
19973 @option{-e} option to submakes.
19975 Moreover, using @option{-e} could have unexpected side effects if your
19976 environment contains some other macros usually defined by the
19977 makefile.  (See also the note about @code{make -e} and @code{SHELL}
19978 below.)
19980 If you can foresee all macros that a user might want to override, then
19981 you can propagate them to submakes manually, from your makefile:
19983 @example
19984 foo = foo
19985 one:
19986         @@echo $(foo)
19987         $(MAKE) foo=$(foo) two
19988 two:
19989         @@echo $(foo)
19990 @end example
19992 Another way to propagate a variable to submakes in a portable way is to
19993 expand an extra variable in every invocation of @samp{$(MAKE)} within
19994 your makefile:
19996 @example
19997 foo = foo
19998 one:
19999         @@echo $(foo)
20000         $(MAKE) $(SUBMAKEFLAGS) two
20001 two:
20002         @@echo $(foo)
20003 @end example
20005 Users must be aware that this technique is in use to take advantage of
20006 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20007 allows any macro to be overridden.  Makefiles generated by
20008 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20009 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20010 automake, GNU Automake}).
20012 @node The Make Macro MAKEFLAGS
20013 @section The Make Macro MAKEFLAGS
20014 @cindex @code{MAKEFLAGS} and @command{make}
20015 @cindex @command{make} and @code{MAKEFLAGS}
20017 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20018 current and recursive invocations of make, but allows implementations
20019 several formats for the variable.  It is tricky to parse
20020 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20021 or @option{-k} for continued execution are in effect.  For example, you
20022 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20023 contains single-letter options, since in the Cygwin version of
20024 GNU @command{make} it is either @option{--unix} or
20025 @option{--win32} with the second word containing single-letter options.
20027 @example
20028 $ @kbd{cat Makefile}
20029 all:
20030         @@echo MAKEFLAGS = $(MAKEFLAGS)
20031 $ @kbd{make}
20032 MAKEFLAGS = --unix
20033 $ @kbd{make -k}
20034 MAKEFLAGS = --unix -k
20035 @end example
20037 @node The Make Macro SHELL
20038 @section The Make Macro @code{SHELL}
20039 @cindex @code{SHELL} and @command{make}
20040 @cindex @command{make} and @code{SHELL}
20042 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20043 macro to spawn shell processes and execute Make rules.  This
20044 is a builtin macro supplied by @command{make}, but it can be modified
20045 by a makefile or by a command-line argument.
20047 Not all @command{make} implementations define this @code{SHELL} macro.
20048 Tru64
20049 @command{make} is an example; this implementation always uses
20050 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20051 your makefiles.  If you use Autoconf, do
20053 @example
20054 SHELL = @@SHELL@@
20055 @end example
20057 @noindent
20058 If you use Automake, this is done for you.
20060 Do not force @code{SHELL = /bin/sh} because that is not correct
20061 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20062 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20063 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20064 GNU @command{make} port sees such a setting it enters a
20065 special emulation mode where features like pipes and redirections are
20066 emulated on top of DOS's @command{command.com}.  Unfortunately this
20067 emulation is incomplete; for instance it does not handle command
20068 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20069 benefit from the same improved shell, such as @command{bash} or
20070 @command{ksh}, that was discovered during @command{configure}, so that
20071 you aren't fighting two different sets of shell bugs between the two
20072 contexts.
20074 Posix-compliant @command{make} should never acquire the value of
20075 $(SHELL) from the environment, even when @code{make -e} is used
20076 (otherwise, think about what would happen to your rules if
20077 @code{SHELL=/bin/tcsh}).
20079 However not all @command{make} implementations have this exception.
20080 For instance it's not surprising that Tru64 @command{make} doesn't
20081 protect @code{SHELL}, since it doesn't use it.
20083 @example
20084 $ @kbd{cat Makefile}
20085 SHELL = /bin/sh
20086 FOO = foo
20087 all:
20088         @@echo $(SHELL)
20089         @@echo $(FOO)
20090 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20091 /bin/tcsh
20093 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20094 /bin/sh
20096 @end example
20098 Conversely, @command{make} is not supposed to export any changes to the
20099 macro @code{SHELL} to child processes.  Again, many implementations
20100 break this rule:
20102 @example
20103 $ @kbd{cat Makefile}
20104 all:
20105         @@echo $(SHELL)
20106         @@printenv SHELL
20107 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20108 /bin/ksh
20109 /bin/ksh
20110 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20111 /bin/ksh
20113 @end example
20115 @node Parallel Make
20116 @section Parallel Make
20117 @cindex Parallel @command{make}
20119 Support for parallel execution in @command{make} implementation varies.
20120 Generally, using GNU make is your best bet.
20122 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20123 reuse the same shell for multiple commands within one recipe.  This can
20124 have various unexpected consequences.  For example, changes of directories
20125 or variables persist between recipes, so that:
20127 @example
20128 all:
20129         @@var=value; cd /; pwd; echo $$var; echo $$$$
20130         @@pwd; echo $$var; echo $$$$
20131 @end example
20133 @noindent
20134 may output the following with @code{make -j1}, at least on NetBSD up to
20135 5.1 and FreeBSD up to 8.2:
20137 @example
20139 value
20140 32235
20142 value
20143 32235
20144 @end example
20146 @noindent
20147 while without @option{-j1}, or with @option{-B}, the output looks less
20148 surprising:
20150 @example
20152 value
20153 32238
20154 /tmp
20156 32239
20157 @end example
20159 @noindent
20160 Another consequence is that, if one command in a recipe uses @code{exit 0}
20161 to indicate a successful exit, the shell will be gone and the remaining
20162 commands of this recipe will not be executed.
20164 The BSD @command{make} implementations, when run in parallel mode,
20165 will also pass the @command{Makefile} recipes to the shell through
20166 its standard input, thus making it unusable from the recipes:
20168 @example
20169 $ @kbd{cat Makefile}
20170 read:
20171         @@read line; echo LINE: $$line
20172 @c $$ @c restore font-lock
20173 $ @kbd{echo foo | make read}
20174 LINE: foo
20175 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20176 LINE:
20177 @end example
20179 @noindent
20180 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20181 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20182 modifiers'' by dynamically modifying the active shell flags.  This
20183 behavior has the effects of potentially clobbering the exit status
20184 of recipes silenced with the @code{@@} modifier if they also unset
20185 the @option{errexit} shell flag, and of mangling the output in
20186 unexpected ways:
20188 @example
20189 $ @kbd{cat Makefile}
20191         @@echo $$-; set +e; false
20193         -echo $$-; false; echo set -
20194 $ @kbd{make a; echo status: $?}
20195 ehBc
20196 *** Error code 1
20197 status: 1
20198 $ @kbd{make -j1 a; echo status: $?}
20200 status: 0
20201 $ @kbd{make b}
20202 echo $-; echo set -
20204 set -
20205 $ @kbd{make -j1 b}
20206 echo $-; echo hvB
20207 @end example
20209 @noindent
20210 You can avoid all these issues by using the @option{-B} option to enable
20211 compatibility semantics.  However, that will effectively also disable
20212 all parallelism as that will cause prerequisites to be updated in the
20213 order they are listed in a rule.
20215 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20216 @command{make}, and Solaris @command{dmake}), when invoked with a
20217 @option{-j@var{N}} option, connect the standard output and standard
20218 error of all their child processes to pipes or temporary regular
20219 files.  This can lead to subtly different semantics in the behavior
20220 of the spawned processes.  For example, even if the @command{make}
20221 standard output is connected to a tty, the recipe command will not be:
20223 @example
20224 $ @kbd{cat Makefile}
20225 all:
20226         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20227 $ @kbd{make -j 2} # FreeBSD 8.2 make
20228 Is not a tty
20229 $ @kbd{make -j 2} # NetBSD 5.1 make
20230 --- all ---
20231 Is not a tty
20232 $ @kbd{dmake -j 2} # Solaris 10 dmake
20233 @var{hostname} --> 1 job
20234 @var{hostname} --> Job output
20235 Is not a tty
20236 @end example
20238 @noindent
20239 On the other hand:
20241 @example
20242 $ @kbd{make -j 2} # GNU make, Heirloom make
20243 Is a tty
20244 @end example
20246 @noindent
20247 The above examples also show additional status output produced in parallel
20248 mode for targets being updated by Solaris @command{dmake} and NetBSD
20249 @command{make} (but @emph{not} by FreeBSD @command{make}).
20251 Furthermore, parallel runs of those @command{make} implementations will
20252 route standard error from commands that they spawn into their own
20253 standard output, and may remove leading whitespace from output lines.
20256 @node Comments in Make Rules
20257 @section Comments in Make Rules
20258 @cindex Comments in @file{Makefile} rules
20259 @cindex @file{Makefile} rules and comments
20261 Never put comments in a rule.
20263 Some @command{make} treat anything starting with a tab as a command for
20264 the current rule, even if the tab is immediately followed by a @code{#}.
20265 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20266 makefile runs @code{# foo} through the shell.
20268 @example
20269 all:
20270         # foo
20271 @end example
20273 As a workaround, you can use the @command{:} no-op command with a string
20274 argument that gets ignored:
20276 @example
20277 all:
20278         : "foo"
20279 @end example
20281 Conversely, if you want to use the @samp{#} character in some command,
20282 you can only do so by expanding it inside a rule (@pxref{Comments in
20283 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20284 @command{config.status} as @samp{#}, then the following substitutes
20285 @samp{@@COMMENT_CHAR@@} in a generated header:
20287 @example
20288 foo.h: foo.h.in
20289         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20290             $(srcdir)/foo.h.in > $@@
20291 @end example
20293 The funny shell quoting avoids a substitution at @command{config.status}
20294 run time of the left-hand side of the @command{sed} @samp{s} command.
20296 @node Newlines in Make Rules
20297 @section Newlines in Make Rules
20298 @cindex Newlines in @file{Makefile} rules
20299 @cindex @file{Makefile} rules and newlines
20301 In shell scripts, newlines can be used inside string literals.  But in
20302 the shell statements of @file{Makefile} rules, this is not possible:
20303 A newline not preceded by a backslash is a separator between shell
20304 statements.  Whereas a newline that is preceded by a backslash becomes
20305 part of the shell statement according to POSIX, but gets replaced,
20306 together with the backslash that precedes it, by a space in GNU
20307 @command{make} 3.80 and older.  So, how can a newline be used in a string
20308 literal?
20310 The trick is to set up a shell variable that contains a newline:
20312 @example
20313 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20314 @end example
20316 For example, in order to create a multiline @samp{sed} expression that
20317 inserts a blank line after every line of a file, this code can be used:
20319 @example
20320 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20321 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20322 @end example
20324 @node Comments in Make Macros
20325 @section Comments in Make Macros
20326 @cindex Comments in @file{Makefile} macros
20327 @cindex @file{Makefile} macros and comments
20329 Avoid putting comments in macro values as far as possible.  Posix
20330 specifies that the text starting from the @samp{#} sign until the end of
20331 the line is to be ignored, which has the unfortunate effect of
20332 disallowing them even within quotes.  Thus, the following might lead to
20333 a syntax error at compile time:
20335 @example
20336 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20337 @end example
20339 @noindent
20340 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20342 Most @command{make} implementations disregard this and treat single and
20343 double quotes specially here.  Also, GNU @command{make} lets you put
20344 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20345 @samp{\#}.  However, neither of these usages are portable.
20346 @xref{Comments in Make Rules}, for a portable alternative.
20348 Even without quoting involved, comments can have surprising effects,
20349 because the whitespace before them is part of the variable value:
20351 @example
20352 foo = bar # trailing comment
20353 print: ; @@echo "$(foo)."
20354 @end example
20356 @noindent
20357 prints @samp{bar .}, which is usually not intended, and can expose
20358 @command{make} bugs as described below.
20360 @node Trailing whitespace in Make Macros
20361 @section Trailing whitespace in Make Macros
20362 @cindex whitespace in @file{Makefile} macros
20363 @cindex @file{Makefile} macros and whitespace
20365 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20366 substitutions and appends another spurious suffix:
20368 @example
20369 empty =
20370 foo = bar $(empty)
20371 print: ; @@echo $(foo:=.test)
20372 @end example
20374 @noindent
20375 prints @samp{bar.test .test}.
20377 BSD and Solaris @command{make} implementations do not honor trailing
20378 whitespace in macro definitions as Posix requires:
20380 @example
20381 foo = bar # Note the space after "bar".
20382 print: ; @@echo $(foo)t
20383 @end example
20385 @noindent
20386 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20387 can use a helper macro as in the previous example.
20390 @node Command-line Macros and whitespace
20391 @section Command-line Macros and whitespace
20392 @cindex whitespace in command-line macros
20393 @cindex command-line, macros set on
20394 @cindex environment, macros set from
20396 Some @command{make} implementations may strip trailing whitespace off
20397 of macros set on the command line in addition to leading whitespace.
20398 Further, some may strip leading whitespace off of macros set from
20399 environment variables:
20401 @example
20402 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20403   foo=' f f ' make -f - bar=' b b '}
20404 x f f xb b x  # AIX, BSD, GNU make
20405 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20406 x f f xb bx   # Solaris make
20407 @end example
20410 @node obj/ and Make
20411 @section The @file{obj/} Subdirectory and Make
20412 @cindex @file{obj/}, subdirectory
20413 @cindex BSD @command{make} and @file{obj/}
20415 Never name one of your subdirectories @file{obj/} if you don't like
20416 surprises.
20418 If an @file{obj/} directory exists, BSD @command{make} enters it
20419 before reading the makefile.  Hence the makefile in the
20420 current directory is not read.
20422 @example
20423 $ @kbd{cat Makefile}
20424 all:
20425         echo Hello
20426 $ @kbd{cat obj/Makefile}
20427 all:
20428         echo World
20429 $ @kbd{make}      # GNU make
20430 echo Hello
20431 Hello
20432 $ @kbd{pmake}     # BSD make
20433 echo World
20434 World
20435 @end example
20437 @node make -k Status
20438 @section Exit Status of @code{make -k}
20439 @cindex @code{make -k}
20441 Do not rely on the exit status of @code{make -k}.  Some implementations
20442 reflect whether they encountered an error in their exit status; other
20443 implementations always succeed.
20445 @example
20446 $ @kbd{cat Makefile}
20447 all:
20448         false
20449 $ @kbd{make -k; echo exit status: $?}    # GNU make
20450 false
20451 make: *** [all] Error 1
20452 exit status: 2
20453 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20454 false
20455 *** Error code 1 (continuing)
20456 exit status: 0
20457 @end example
20459 @node VPATH and Make
20460 @section @code{VPATH} and Make
20461 @cindex @code{VPATH}
20463 Posix does not specify the semantics of @code{VPATH}.  Typically,
20464 @command{make} supports @code{VPATH}, but its implementation is not
20465 consistent.
20467 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20468 portable to recent-enough popular implementations of @command{make}, but
20469 to keep the resulting makefiles portable, a package's makefile
20470 prototypes must take the following issues into account.  These issues
20471 are complicated and are often poorly understood, and installers who use
20472 @code{VPATH} should expect to find many bugs in this area.  If you use
20473 @code{VPATH}, the simplest way to avoid these portability bugs is to
20474 stick with GNU @command{make}, since it is the most
20475 commonly-used @command{make} among Autoconf users.
20477 Here are some known issues with some @code{VPATH}
20478 implementations.
20480 @menu
20481 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20482 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20483 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20484 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20485 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20486 * Make Target Lookup::          More details about @code{VPATH} lookup
20487 @end menu
20489 @node Variables listed in VPATH
20490 @subsection Variables listed in @code{VPATH}
20491 @cindex @code{VPATH} and variables
20492 @cindex variables and @code{VPATH}
20494 Do not set @code{VPATH} to the value of another variable, for example
20495 @samp{VPATH = $(srcdir)}, because some ancient versions of
20496 @command{make} do not do variable substitutions on the value of
20497 @code{VPATH}.  For example, use this
20499 @example
20500 srcdir = @@srcdir@@
20501 VPATH = @@srcdir@@
20502 @end example
20504 @noindent
20505 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20506 Automake, there is no need to set this yourself.
20508 @node VPATH and Double-colon
20509 @subsection @code{VPATH} and Double-colon Rules
20510 @cindex @code{VPATH} and double-colon rules
20511 @cindex double-colon rules and @code{VPATH}
20513 With ancient versions of Sun @command{make},
20514 any assignment to @code{VPATH} causes @command{make} to execute only
20515 the first set of double-colon rules.
20516 However, this problem is no longer of practical concern.
20518 @node $< in Explicit Rules
20519 @subsection @code{$<} Not Supported in Explicit Rules
20520 @cindex explicit rules, @code{$<}, and @code{VPATH}
20521 @cindex @code{$<}, explicit rules, and @code{VPATH}
20522 @cindex @code{VPATH}, explicit rules, and @code{$<}
20524 Using @code{$<} in explicit rules is not portable.
20525 The prerequisite file must be named explicitly in the rule.  If you want
20526 to find the prerequisite via a @code{VPATH} search, you have to code the
20527 whole thing manually.  @xref{Build Directories}.
20529 @node Automatic Rule Rewriting
20530 @subsection Automatic Rule Rewriting
20531 @cindex @code{VPATH} and automatic rule rewriting
20532 @cindex automatic rule rewriting and @code{VPATH}
20534 Some @command{make} implementations, such as Solaris and Tru64,
20535 search for prerequisites in @code{VPATH} and
20536 then rewrite each occurrence as a plain word in the rule.
20537 For instance:
20539 @example
20540 # This isn't portable to GNU make.
20541 VPATH = ../pkg/src
20542 f.c: if.c
20543         cp if.c f.c
20544 @end example
20546 @noindent
20547 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20548 found in @file{../pkg/src}.
20550 However, this rule leads to real problems in practice.  For example, if
20551 the source directory contains an ordinary file named @file{test} that is
20552 used in a dependency, Solaris @command{make} rewrites commands like
20553 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20554 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20555 completely unaware of shell syntax used in the rules, so the VPATH
20556 rewrite can potentially apply to @emph{any} whitespace-separated word
20557 in a rule, including shell variables, functions, and keywords.
20559 @example
20560 $ @kbd{mkdir build}
20561 $ @kbd{cd build}
20562 $ @kbd{cat > Makefile <<'END'}
20563 VPATH = ..
20564 all: arg func for echo
20565         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20566         func "hello world"
20568 $ @kbd{touch ../arg ../func ../for ../echo}
20569 $ @kbd{make}
20570 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20571 ../func "hello world"
20572 sh: syntax error at line 1: `do' unexpected
20573 *** Error code 2
20574 @end example
20576 @noindent
20577 To avoid this problem, portable makefiles should never mention a source
20578 file or dependency whose name is that of a shell keyword like @file{for}
20579 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20580 @command{test}, or a shell function or variable used in the corresponding
20581 @command{Makefile} recipe.
20583 Because of these problems GNU @command{make} and many other @command{make}
20584 implementations do not rewrite commands, so portable makefiles should
20585 search @code{VPATH} manually.  It is tempting to write this:
20587 @smallexample
20588 # This isn't portable to Solaris make.
20589 VPATH = ../pkg/src
20590 f.c: if.c
20591         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20592 @end smallexample
20594 @noindent
20595 However, the ``prerequisite rewriting'' still applies here.  So if
20596 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20597 execute
20599 @smallexample
20600 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20601 @end smallexample
20603 @noindent
20604 which reduces to
20606 @example
20607 cp if.c f.c
20608 @end example
20610 @noindent
20611 and thus fails.  Oops.
20613 A simple workaround, and good practice anyway, is to use @samp{$?} and
20614 @samp{$@@} when possible:
20616 @smallexample
20617 VPATH = ../pkg/src
20618 f.c: if.c
20619         cp $? $@@
20620 @end smallexample
20622 @noindent
20623 but this does not generalize well to commands with multiple
20624 prerequisites.  A more general workaround is to rewrite the rule so that
20625 the prerequisite @file{if.c} never appears as a plain word.  For
20626 example, these three rules would be safe, assuming @file{if.c} is in
20627 @file{../pkg/src} and the other files are in the working directory:
20629 @smallexample
20630 VPATH = ../pkg/src
20631 f.c: if.c f1.c
20632         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20633 g.c: if.c g1.c
20634         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20635 h.c: if.c h1.c
20636         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20637 @end smallexample
20639 Things get worse when your prerequisites are in a macro.
20641 @example
20642 VPATH = ../pkg/src
20643 HEADERS = f.h g.h h.h
20644 install-HEADERS: $(HEADERS)
20645         for i in $(HEADERS); do \
20646           $(INSTALL) -m 644 \
20647             `test -f $$i || echo $(VPATH)/`$$i \
20648             $(DESTDIR)$(includedir)/$$i; \
20649 @c $$ restore font-lock
20650         done
20651 @end example
20653 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20654 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20655 where @code{f.h} and @code{g.h} are plain words and are hence
20656 subject to @code{VPATH} adjustments.
20658 If the three files are in @file{../pkg/src}, the rule is run as:
20660 @example
20661 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20662   install -m 644 \
20663      `test -f $i || echo ../pkg/src/`$i \
20664      /usr/local/include/$i; \
20665 done
20666 @end example
20668 where the two first @command{install} calls fail.  For instance,
20669 consider the @code{f.h} installation:
20671 @example
20672 install -m 644 \
20673   `test -f ../pkg/src/f.h || \
20674     echo ../pkg/src/ \
20675   `../pkg/src/f.h \
20676   /usr/local/include/../pkg/src/f.h;
20677 @end example
20679 @noindent
20680 It reduces to:
20682 @example
20683 install -m 644 \
20684   ../pkg/src/f.h \
20685   /usr/local/include/../pkg/src/f.h;
20686 @end example
20688 Note that the manual @code{VPATH} search did not cause any problems here;
20689 however this command installs @file{f.h} in an incorrect directory.
20691 Trying to quote @code{$(HEADERS)} in some way, as we did for
20692 @code{foo.c} a few makefiles ago, does not help:
20694 @example
20695 install-HEADERS: $(HEADERS)
20696         headers='$(HEADERS)'; \
20697         for i in $$headers; do \
20698           $(INSTALL) -m 644 \
20699             `test -f $$i || echo $(VPATH)/`$$i \
20700             $(DESTDIR)$(includedir)/$$i; \
20701         done
20702 @end example
20704 Now, @code{headers='$(HEADERS)'} macro-expands to:
20706 @example
20707 headers='f.h g.h h.h'
20708 @end example
20710 @noindent
20711 but @code{g.h} is still a plain word.  (As an aside, the idiom
20712 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20713 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20714 syntax error on @code{for i in;}.)
20716 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20718 @example
20719 VPATH = ../pkg/src
20720 HEADERS = f.h g.h h.h
20721 install-HEADERS: $(HEADERS)
20722         headers='$(HEADERS)'; \
20723         for i in $$headers; do \
20724           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20725           $(INSTALL) -m 644 \
20726             `test -f $$i || echo $(VPATH)/`$$i \
20727             $(DESTDIR)$(includedir)/$$i; \
20728 @c $$ restore font-lock
20729         done
20730 @end example
20732 Automake does something similar.  However the above hack works only if
20733 the files listed in @code{HEADERS} are in the current directory or a
20734 subdirectory; they should not be in an enclosing directory.  If we had
20735 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20736 build with Tru64 @command{make}.  The reason is that not only does
20737 Tru64 @command{make} rewrite dependencies, but it also simplifies
20738 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20739 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20740 a leading @file{../pkg/src/} component.
20742 The following example makes the behavior of Tru64 @command{make}
20743 more apparent.
20745 @example
20746 $ @kbd{cat Makefile}
20747 VPATH = sub
20748 all: ../foo
20749         echo ../foo
20750 $ @kbd{ls}
20751 Makefile foo
20752 $ @kbd{make}
20753 echo foo
20755 @end example
20757 @noindent
20758 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20759 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20760 directory does not even exist, this just means that the simplification
20761 occurred before the file was checked for.)
20763 For the record here is how SunOS 4 @command{make} behaves on this
20764 example.
20766 @smallexample
20767 $ @kbd{make}
20768 make: Fatal error: Don't know how to make target `../foo'
20769 $ @kbd{mkdir sub}
20770 $ @kbd{make}
20771 echo sub/../foo
20772 sub/../foo
20773 @end smallexample
20776 @node Tru64 Directory Magic
20777 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20778 @cindex @code{VPATH} and prerequisite directories
20779 @cindex prerequisite directories and @code{VPATH}
20781 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20782 @command{make} creates it in the current directory.
20784 @example
20785 $ @kbd{mkdir -p foo/bar build}
20786 $ @kbd{cd build}
20787 $ @kbd{cat >Makefile <<END
20788 VPATH = ..
20789 all: foo/bar
20790 END}
20791 $ @kbd{make}
20792 mkdir foo
20793 mkdir foo/bar
20794 @end example
20796 This can yield unexpected results if a rule uses a manual @code{VPATH}
20797 search as presented before.
20799 @example
20800 VPATH = ..
20801 all : foo/bar
20802         command `test -d foo/bar || echo ../`foo/bar
20803 @end example
20805 The above @command{command} is run on the empty @file{foo/bar}
20806 directory that was created in the current directory.
20808 @node Make Target Lookup
20809 @subsection Make Target Lookup
20810 @cindex @code{VPATH}, resolving target pathnames
20812 GNU @command{make} uses a complex algorithm to decide when it
20813 should use files found via a @code{VPATH} search.  @xref{Search
20814 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20815 Manual}.
20817 If a target needs to be rebuilt, GNU @command{make} discards the
20818 file name found during the @code{VPATH} search for this target, and
20819 builds the file locally using the file name given in the makefile.
20820 If a target does not need to be rebuilt, GNU @command{make} uses the
20821 file name found during the @code{VPATH} search.
20823 Other @command{make} implementations, like NetBSD @command{make}, are
20824 easier to describe: the file name found during the @code{VPATH} search
20825 is used whether the target needs to be rebuilt or not.  Therefore
20826 new files are created locally, but existing files are updated at their
20827 @code{VPATH} location.
20829 OpenBSD and FreeBSD @command{make}, however,
20830 never perform a
20831 @code{VPATH} search for a dependency that has an explicit rule.
20832 This is extremely annoying.
20834 When attempting a @code{VPATH} build for an autoconfiscated package
20835 (e.g., @code{mkdir build && cd build && ../configure}), this means
20837 @command{make} builds everything locally in the @file{build}
20838 directory, while BSD @command{make} builds new files locally and
20839 updates existing files in the source directory.
20841 @example
20842 $ @kbd{cat Makefile}
20843 VPATH = ..
20844 all: foo.x bar.x
20845 foo.x bar.x: newer.x
20846         @@echo Building $@@
20847 $ @kbd{touch ../bar.x}
20848 $ @kbd{touch ../newer.x}
20849 $ @kbd{make}        # GNU make
20850 Building foo.x
20851 Building bar.x
20852 $ @kbd{pmake}       # NetBSD make
20853 Building foo.x
20854 Building ../bar.x
20855 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20856 Building foo.x
20857 Building bar.x
20858 $ @kbd{tmake}       # Tru64 make
20859 Building foo.x
20860 Building bar.x
20861 $ @kbd{touch ../bar.x}
20862 $ @kbd{make}        # GNU make
20863 Building foo.x
20864 $ @kbd{pmake}       # NetBSD make
20865 Building foo.x
20866 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20867 Building foo.x
20868 Building bar.x
20869 $ @kbd{tmake}       # Tru64 make
20870 Building foo.x
20871 Building bar.x
20872 @end example
20874 Note how NetBSD @command{make} updates @file{../bar.x} in its
20875 VPATH location, and how FreeBSD, OpenBSD, and Tru64
20876 @command{make} always
20877 update @file{bar.x}, even when @file{../bar.x} is up to date.
20879 Another point worth mentioning is that once GNU @command{make} has
20880 decided to ignore a @code{VPATH} file name (e.g., it ignored
20881 @file{../bar.x} in the above example) it continues to ignore it when
20882 the target occurs as a prerequisite of another rule.
20884 The following example shows that GNU @command{make} does not look up
20885 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20886 because it ignored the @code{VPATH} result of @file{bar.x} while running
20887 the @code{bar.x: newer.x} rule.
20889 @example
20890 $ @kbd{cat Makefile}
20891 VPATH = ..
20892 all: bar.y
20893 bar.x: newer.x
20894         @@echo Building $@@
20895 .SUFFIXES: .x .y
20896 .x.y:
20897         cp $< $@@
20898 $ @kbd{touch ../bar.x}
20899 $ @kbd{touch ../newer.x}
20900 $ @kbd{make}        # GNU make
20901 Building bar.x
20902 cp bar.x bar.y
20903 cp: cannot stat `bar.x': No such file or directory
20904 make: *** [bar.y] Error 1
20905 $ @kbd{pmake}       # NetBSD make
20906 Building ../bar.x
20907 cp ../bar.x bar.y
20908 $ @kbd{rm bar.y}
20909 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20910 echo Building bar.x
20911 cp bar.x bar.y
20912 cp: cannot stat `bar.x': No such file or directory
20913 *** Error code 1
20914 $ @kbd{tmake}       # Tru64 make
20915 Building bar.x
20916 cp: bar.x: No such file or directory
20917 *** Exit 1
20918 @end example
20920 Note that if you drop away the command from the @code{bar.x: newer.x}
20921 rule, GNU @command{make} magically starts to work: it
20922 knows that @code{bar.x} hasn't been updated, therefore it doesn't
20923 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
20924 uses.  Tru64 also works, but FreeBSD and OpenBSD
20925 still don't.
20927 @example
20928 $ @kbd{cat Makefile}
20929 VPATH = ..
20930 all: bar.y
20931 bar.x: newer.x
20932 .SUFFIXES: .x .y
20933 .x.y:
20934         cp $< $@@
20935 $ @kbd{touch ../bar.x}
20936 $ @kbd{touch ../newer.x}
20937 $ @kbd{make}        # GNU make
20938 cp ../bar.x bar.y
20939 $ @kbd{rm bar.y}
20940 $ @kbd{pmake}       # NetBSD make
20941 cp ../bar.x bar.y
20942 $ @kbd{rm bar.y}
20943 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20944 cp bar.x bar.y
20945 cp: cannot stat `bar.x': No such file or directory
20946 *** Error code 1
20947 $ @kbd{tmake}       # Tru64 make
20948 cp ../bar.x bar.y
20949 @end example
20951 It seems the sole solution that would please every @command{make}
20952 implementation is to never rely on @code{VPATH} searches for targets.
20953 In other words, @code{VPATH} should be reserved to unbuilt sources.
20956 @node Single Suffix Rules
20957 @section Single Suffix Rules and Separated Dependencies
20958 @cindex Single Suffix Inference Rule
20959 @cindex Rule, Single Suffix Inference
20960 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
20961 (@samp{.from.to:}), but which @emph{destination} suffix is empty
20962 (@samp{.from:}).
20964 @cindex Separated Dependencies
20965 @dfn{Separated dependencies} simply refers to listing the prerequisite
20966 of a target, without defining a rule.  Usually one can list on the one
20967 hand side, the rules, and on the other hand side, the dependencies.
20969 Solaris @command{make} does not support separated dependencies for
20970 targets defined by single suffix rules:
20972 @example
20973 $ @kbd{cat Makefile}
20974 .SUFFIXES: .in
20975 foo: foo.in
20976 .in:
20977         cp $< $@@
20978 $ @kbd{touch foo.in}
20979 $ @kbd{make}
20980 $ @kbd{ls}
20981 Makefile  foo.in
20982 @end example
20984 @noindent
20985 while GNU Make does:
20987 @example
20988 $ @kbd{gmake}
20989 cp foo.in foo
20990 $ @kbd{ls}
20991 Makefile  foo       foo.in
20992 @end example
20994 Note it works without the @samp{foo: foo.in} dependency.
20996 @example
20997 $ @kbd{cat Makefile}
20998 .SUFFIXES: .in
20999 .in:
21000         cp $< $@@
21001 $ @kbd{make foo}
21002 cp foo.in foo
21003 @end example
21005 @noindent
21006 and it works with double suffix inference rules:
21008 @example
21009 $ @kbd{cat Makefile}
21010 foo.out: foo.in
21011 .SUFFIXES: .in .out
21012 .in.out:
21013         cp $< $@@
21014 $ @kbd{make}
21015 cp foo.in foo.out
21016 @end example
21018 As a result, in such a case, you have to write target rules.
21020 @node Timestamps and Make
21021 @section Timestamp Resolution and Make
21022 @cindex timestamp resolution
21023 Traditionally, file timestamps had 1-second resolution, and
21024 @command{make} used those timestamps to determine whether one file was
21025 newer than the other.  However, many modern file systems have
21026 timestamps with 1-nanosecond resolution.  Some @command{make}
21027 implementations look at the entire timestamp; others ignore the
21028 fractional part, which can lead to incorrect results.  Normally this
21029 is not a problem, but in some extreme cases you may need to use tricks
21030 like @samp{sleep 1} to work around timestamp truncation bugs.
21032 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21033 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21034 Tools}).  Hence you should be wary of rules like this:
21036 @example
21037 dest: src
21038         cp -p src dest
21039 @end example
21041 as @file{dest} often appears to be older than @file{src} after the
21042 timestamp is truncated, and this can cause @command{make} to do
21043 needless rework the next time it is invoked.  To work around this
21044 problem, you can use a timestamp file, e.g.:
21046 @example
21047 dest-stamp: src
21048         cp -p src dest
21049         date >dest-stamp
21050 @end example
21052 Apart from timestamp resolution, there are also differences in handling
21053 equal timestamps.  HP-UX @command{make} updates targets if it has the
21054 same time stamp as one of its prerequisites, in violation of Posix rules.
21056 This can cause spurious rebuilds for repeated runs of @command{make}.
21057 This in turn can cause @command{make} to fail if it tries to rebuild
21058 generated files in a possibly read-only source tree with tools not
21059 present on the end-user machine.  Use GNU @command{make} instead.
21063 @c ======================================== Portable C and C++ Programming
21065 @node Portable C and C++
21066 @chapter Portable C and C++ Programming
21067 @cindex Portable C and C++ programming
21069 C and C++ programs often use low-level features of the underlying
21070 system, and therefore are often more difficult to make portable to other
21071 platforms.
21073 Several standards have been developed to help make your programs more
21074 portable.  If you write programs with these standards in mind, you can
21075 have greater confidence that your programs work on a wide variety
21076 of systems.
21077 @ifhtml
21078 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21079 Standards Supported by GCC}
21080 @end ifhtml
21081 @ifnothtml
21082 @xref{Standards, , Language Standards Supported by
21083 GCC, gcc, Using the GNU Compiler Collection
21084 (GCC)},
21085 @end ifnothtml
21086 for a list of C-related standards.  Many programs also assume the
21087 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
21089 Some old code is written to be portable to K&R C, which predates any C
21090 standard.  K&R C compilers are no longer of practical interest, though,
21091 and the rest of section assumes at least C89, the first C standard.
21093 Program portability is a huge topic, and this section can only briefly
21094 introduce common pitfalls.  @xref{System Portability, , Portability
21095 between System Types, standards, The GNU Coding Standards}, for
21096 more information.
21098 @menu
21099 * Varieties of Unportability::  How to make your programs unportable
21100 * Integer Overflow::            When integers get too large
21101 * Preprocessor Arithmetic::     @code{#if} expression problems
21102 * Null Pointers::               Properties of null pointers
21103 * Buffer Overruns::             Subscript errors and the like
21104 * Volatile Objects::            @code{volatile} and signals
21105 * Floating Point Portability::  Portable floating-point arithmetic
21106 * Exiting Portably::            Exiting and the exit status
21107 @end menu
21109 @node Varieties of Unportability
21110 @section Varieties of Unportability
21111 @cindex portability
21113 Autoconf tests and ordinary programs often need to test what is allowed
21114 on a system, and therefore they may need to deliberately exceed the
21115 boundaries of what the standards allow, if only to see whether an
21116 optional feature is present.  When you write such a program, you should
21117 keep in mind the difference between constraints, unspecified behavior,
21118 and undefined behavior.
21120 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21121 example constraint is that C programs must not declare a bit-field with
21122 negative width.  Tests can therefore reliably assume that programs with
21123 negative-width bit-fields are rejected by a compiler that conforms
21124 to the standard.
21126 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21127 multiple possibilities.  For example, the order of evaluation of
21128 function arguments is unspecified.  Some unspecified behavior is
21129 @dfn{implementation-defined}, i.e., documented by the implementation,
21130 but since Autoconf tests cannot read the documentation they cannot
21131 distinguish between implementation-defined and other unspecified
21132 behavior.  It is common for Autoconf tests to probe implementations to
21133 determine otherwise-unspecified behavior.
21135 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21136 the implementation to do anything it pleases.  For example,
21137 dereferencing a null pointer leads to undefined behavior.  If possible,
21138 test programs should avoid undefined behavior, since a program with
21139 undefined behavior might succeed on a test that should fail.
21141 The above rules apply to programs that are intended to conform to the
21142 standard.  However, strictly-conforming programs are quite rare, since
21143 the standards are so limiting.  A major goal of Autoconf is to support
21144 programs that use implementation features not described by the standard,
21145 and it is fairly common for test programs to violate the above rules, if
21146 the programs work well enough in practice.
21148 @node Integer Overflow
21149 @section Integer Overflow
21150 @cindex integer overflow
21151 @cindex overflow, signed integer
21152 @cindex signed integer overflow
21153 @cindex wraparound arithmetic
21155 In practice many portable C programs assume that signed integer overflow wraps
21156 around reliably using two's complement arithmetic.  Yet the C standard
21157 says that program behavior is undefined on overflow, and in a few cases
21158 C programs do not work on some modern implementations because their
21159 overflows do not wrap around as their authors expected.  Conversely, in
21160 signed integer remainder, the C standard requires overflow
21161 behavior that is commonly not implemented.
21163 @menu
21164 * Integer Overflow Basics::     Why integer overflow is a problem
21165 * Signed Overflow Examples::    Examples of code assuming wraparound
21166 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21167 * Signed Overflow Advice::      Practical advice for signed overflow issues
21168 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21169 @end menu
21171 @node Integer Overflow Basics
21172 @subsection Basics of Integer Overflow
21173 @cindex integer overflow
21174 @cindex overflow, signed integer
21175 @cindex signed integer overflow
21176 @cindex wraparound arithmetic
21178 In languages like C, unsigned integer overflow reliably wraps around;
21179 e.g., @code{UINT_MAX + 1} yields zero.
21180 This is guaranteed by the C standard and is
21181 portable in practice, unless you specify aggressive,
21182 nonstandard optimization options
21183 suitable only for special applications.
21185 In contrast, the C standard says that signed integer overflow leads to
21186 undefined behavior where a program can do anything, including dumping
21187 core or overrunning a buffer.  The misbehavior can even precede the
21188 overflow.  Such an overflow can occur during addition, subtraction,
21189 multiplication, division, and left shift.
21191 Despite this requirement of the standard, many C programs and Autoconf
21192 tests assume that signed integer overflow silently wraps around modulo a
21193 power of two, using two's complement arithmetic, so long as you cast the
21194 resulting value to a signed integer type or store it into a signed
21195 integer variable.  If you use conservative optimization flags, such
21196 programs are generally portable to the vast majority of modern
21197 platforms, with a few exceptions discussed later.
21199 For historical reasons the C standard also allows implementations with
21200 ones' complement or signed magnitude arithmetic, but it is safe to
21201 assume two's complement nowadays.
21203 Also, overflow can occur when converting an out-of-range value to a
21204 signed integer type.  Here a standard implementation must define what
21205 happens, but this might include raising an exception.  In practice all
21206 known implementations support silent wraparound in this case, so you need
21207 not worry about other possibilities.
21209 @node Signed Overflow Examples
21210 @subsection Examples of Code Assuming Wraparound Overflow
21211 @cindex integer overflow
21212 @cindex overflow, signed integer
21213 @cindex signed integer overflow
21214 @cindex wraparound arithmetic
21216 There has long been a tension between what the C standard requires for
21217 signed integer overflow, and what C programs commonly assume.  The
21218 standard allows aggressive optimizations based on assumptions that
21219 overflow never occurs, but many practical C programs rely on overflow
21220 wrapping around.  These programs do not conform to the standard, but
21221 they commonly work in practice because compiler writers are
21222 understandably reluctant to implement optimizations that would break
21223 many programs, unless perhaps a user specifies aggressive optimization.
21225 The C Standard says that if a program has signed integer overflow its
21226 behavior is undefined, and the undefined behavior can even precede the
21227 overflow.  To take an extreme example:
21229 @c Inspired by Robert Dewar's example in
21230 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21231 @example
21232 if (password == expected_password)
21233   allow_superuser_privileges ();
21234 else if (counter++ == INT_MAX)
21235   abort ();
21236 else
21237   printf ("%d password mismatches\n", counter);
21238 @end example
21240 @noindent
21241 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21242 @code{counter++} must overflow and the behavior is undefined, so the C
21243 standard allows the compiler to optimize away the test against
21244 @code{INT_MAX} and the @code{abort} call.
21245 Worse, if an earlier bug in the program lets the compiler deduce that
21246 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21247 the C standard allows the compiler to optimize away the password test
21248 and generate code that allows superuser privileges unconditionally.
21250 Despite this requirement by the standard, it has long been common for C
21251 code to assume wraparound arithmetic after signed overflow, and all
21252 known practical C implementations support some C idioms that assume
21253 wraparound signed arithmetic, even if the idioms do not conform
21254 strictly to the standard.  If your code looks like the following
21255 examples it will almost surely work with real-world compilers.
21257 Here is an example derived from the 7th Edition Unix implementation of
21258 @code{atoi} (1979-01-10):
21260 @example
21261 char *p;
21262 int f, n;
21263 @dots{}
21264 while (*p >= '0' && *p <= '9')
21265   n = n * 10 + *p++ - '0';
21266 return (f ? -n : n);
21267 @end example
21269 @noindent
21270 Even if the input string is in range, on most modern machines this has
21271 signed overflow when computing the most negative integer (the @code{-n}
21272 overflows) or a value near an extreme integer (the first @code{+}
21273 overflows).
21275 Here is another example, derived from the 7th Edition implementation of
21276 @code{rand} (1979-01-10).  Here the programmer expects both
21277 multiplication and addition to wrap on overflow:
21279 @example
21280 static long int randx = 1;
21281 @dots{}
21282 randx = randx * 1103515245 + 12345;
21283 return (randx >> 16) & 077777;
21284 @end example
21286 In the following example, derived from the GNU C Library 2.5
21287 implementation of @code{mktime} (2006-09-09), the code assumes
21288 wraparound arithmetic in @code{+} to detect signed overflow:
21290 @example
21291 time_t t, t1, t2;
21292 int sec_requested, sec_adjustment;
21293 @dots{}
21294 t1 = t + sec_requested;
21295 t2 = t1 + sec_adjustment;
21296 if (((t1 < t) != (sec_requested < 0))
21297     | ((t2 < t1) != (sec_adjustment < 0)))
21298   return -1;
21299 @end example
21301 If your code looks like these examples, it is probably safe even though
21302 it does not strictly conform to the C standard.  This might lead one to
21303 believe that one can generally assume wraparound on overflow, but that
21304 is not always true, as can be seen in the next section.
21306 @node Optimization and Wraparound
21307 @subsection Optimizations That Break Wraparound Arithmetic
21308 @cindex loop induction
21310 Compilers sometimes generate code that is incompatible with wraparound
21311 integer arithmetic.  A simple example is an algebraic simplification: a
21312 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21313 because it assumes that @code{i * 2000} does not overflow.  The
21314 translation is not equivalent to the original when overflow occurs:
21315 e.g., in the typical case of 32-bit signed two's complement wraparound
21316 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21317 the original expression returns @minus{}2147483 but the optimized
21318 version returns the mathematically correct value 2147484.
21320 More subtly, loop induction optimizations often exploit the undefined
21321 behavior of signed overflow.  Consider the following contrived function
21322 @code{sumc}:
21324 @example
21326 sumc (int lo, int hi)
21328   int sum = 0;
21329   int i;
21330   for (i = lo; i <= hi; i++)
21331     sum ^= i * 53;
21332   return sum;
21334 @end example
21336 @noindent
21337 To avoid multiplying by 53 each time through the loop, an optimizing
21338 compiler might internally transform @code{sumc} to the equivalent of the
21339 following:
21341 @example
21343 transformed_sumc (int lo, int hi)
21345   int sum = 0;
21346   int hic = hi * 53;
21347   int ic;
21348   for (ic = lo * 53; ic <= hic; ic += 53)
21349     sum ^= ic;
21350   return sum;
21352 @end example
21354 @noindent
21355 This transformation is allowed by the C standard, but it is invalid for
21356 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21357 overflow in computing expressions like @code{hi * 53} can cause the
21358 expression @code{i <= hi} to yield a different value from the
21359 transformed expression @code{ic <= hic}.
21361 For this reason, compilers that use loop induction and similar
21362 techniques often do not support reliable wraparound arithmetic when a
21363 loop induction variable like @code{ic} is involved.  Since loop
21364 induction variables are generated by the compiler, and are not visible
21365 in the source code, it is not always trivial to say whether the problem
21366 affects your code.
21368 Hardly any code actually depends on wraparound arithmetic in cases like
21369 these, so in practice these loop induction optimizations are almost
21370 always useful.  However, edge cases in this area can cause problems.
21371 For example:
21373 @example
21374 int j;
21375 for (j = 1; 0 < j; j *= 2)
21376   test (j);
21377 @end example
21379 @noindent
21380 Here, the loop attempts to iterate through all powers of 2 that
21381 @code{int} can represent, but the C standard allows a compiler to
21382 optimize away the comparison and generate an infinite loop,
21383 under the argument that behavior is undefined on overflow.  As of this
21384 writing this optimization is not done by any production version of
21385 GCC with @option{-O2}, but it might be performed by other
21386 compilers, or by more aggressive GCC optimization options,
21387 and the GCC developers have not decided whether it will
21388 continue to work with GCC and @option{-O2}.
21390 @node Signed Overflow Advice
21391 @subsection Practical Advice for Signed Overflow Issues
21392 @cindex integer overflow
21393 @cindex overflow, signed integer
21394 @cindex signed integer overflow
21395 @cindex wraparound arithmetic
21397 Ideally the safest approach is to avoid signed integer overflow
21398 entirely.  For example, instead of multiplying two signed integers, you
21399 can convert them to unsigned integers, multiply the unsigned values,
21400 then test whether the result is in signed range.
21402 Rewriting code in this way will be inconvenient, though, particularly if
21403 the signed values might be negative.  Also, it may hurt
21404 performance.  Using unsigned arithmetic to check for overflow is
21405 particularly painful to do portably and efficiently when dealing with an
21406 integer type like @code{uid_t} whose width and signedness vary from
21407 platform to platform.
21409 Furthermore, many C applications pervasively assume wraparound behavior
21410 and typically it is not easy to find and remove all these assumptions.
21411 Hence it is often useful to maintain nonstandard code that assumes
21412 wraparound on overflow, instead of rewriting the code.  The rest of this
21413 section attempts to give practical advice for this situation.
21415 If your code wants to detect signed integer overflow in @code{sum = a +
21416 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21417 < 0)}.
21419 If your code uses a signed loop index, make sure that the index cannot
21420 overflow, along with all signed expressions derived from the index.
21421 Here is a contrived example of problematic code with two instances of
21422 overflow.
21424 @example
21425 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21426   if (i + 1 < 0)
21427     @{
21428       report_overflow ();
21429       break;
21430     @}
21431 @end example
21433 @noindent
21434 Because of the two overflows, a compiler might optimize away or
21435 transform the two comparisons in a way that is incompatible with the
21436 wraparound assumption.
21438 If your code uses an expression like @code{(i * 2000) / 1000} and you
21439 actually want the multiplication to wrap around on overflow, use
21440 unsigned arithmetic
21441 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21443 If your code assumes wraparound behavior and you want to insulate it
21444 against any GCC optimizations that would fail to support that
21445 behavior, you should use GCC's @option{-fwrapv} option, which
21446 causes signed overflow to wrap around reliably (except for division and
21447 remainder, as discussed in the next section).
21449 If you need to port to platforms where signed integer overflow does not
21450 reliably wrap around (e.g., due to hardware overflow checking, or to
21451 highly aggressive optimizations), you should consider debugging with
21452 GCC's @option{-ftrapv} option, which causes signed overflow to
21453 raise an exception.
21455 @node Signed Integer Division
21456 @subsection Signed Integer Division and Integer Overflow
21457 @cindex division, integer
21459 Overflow in signed
21460 integer division is not always harmless: for example, on CPUs of the
21461 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21462 which by default terminates the program.  Worse, taking the remainder
21463 of these two values typically yields the same signal on these CPUs,
21464 even though the C standard requires @code{INT_MIN % -1} to yield zero
21465 because the expression does not overflow.
21467 @node Preprocessor Arithmetic
21468 @section Preprocessor Arithmetic
21469 @cindex preprocessor arithmetic
21471 In C99 and later, preprocessor arithmetic, used for @code{#if}
21472 expressions, must
21473 be evaluated as if all signed values are of type @code{intmax_t} and all
21474 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21475 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21476 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21477 @code{long long int}.  Also, some older preprocessors mishandle
21478 constants ending in @code{LL}.  To work around these problems, you can
21479 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21480 @code{configure}-time rather than at @code{#if}-time.
21482 @node Null Pointers
21483 @section Properties of Null Pointers
21484 @cindex null pointers
21486 Most modern hosts reliably fail when you attempt to dereference a null
21487 pointer.
21489 On almost all modern hosts, null pointers use an all-bits-zero internal
21490 representation, so you can reliably use @code{memset} with 0 to set all
21491 the pointers in an array to null values.
21493 If @code{p} is a null pointer to an object type, the C expression
21494 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21495 the standard says that it has undefined behavior.
21497 @node Buffer Overruns
21498 @section Buffer Overruns and Subscript Errors
21499 @cindex buffer overruns
21501 Buffer overruns and subscript errors are the most common dangerous
21502 errors in C programs.  They result in undefined behavior because storing
21503 outside an array typically modifies storage that is used by some other
21504 object, and most modern systems lack runtime checks to catch these
21505 errors.  Programs should not rely on buffer overruns being caught.
21507 There is one exception to the usual rule that a portable program cannot
21508 address outside an array.  In C, it is valid to compute the address just
21509 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21510 so long as you do not dereference the resulting pointer.  But it is not
21511 valid to compute the address just before an object, e.g., @code{&a[-1]};
21512 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21513 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21514 reliable in general, and it is usually easy enough to avoid the
21515 potential portability problem, e.g., by allocating an extra unused array
21516 element at the start or end.
21518 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21520 users might also consider using the @option{-fmudflap} option to catch
21521 overruns.
21523 Buffer overruns are usually caused by off-by-one errors, but there are
21524 more subtle ways to get them.
21526 Using @code{int} values to index into an array or compute array sizes
21527 causes problems on typical 64-bit hosts where an array index might
21528 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21529 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21530 are signed, and are wide enough in practice.
21532 If you add or multiply two numbers to calculate an array size, e.g.,
21533 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21534 multiplication overflows.
21536 Many implementations of the @code{alloca} function silently misbehave
21537 and can generate buffer overflows if given sizes that are too large.
21538 The size limits are implementation dependent, but are at least 4000
21539 bytes on all platforms that we know about.
21541 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21542 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21543 portable code should not use them unless the inputs are known to be
21544 within certain limits.  The time-related functions can overflow their
21545 buffers if given timestamps out of range (e.g., a year less than -999
21546 or greater than 9999).  Time-related buffer overflows cannot happen with
21547 recent-enough versions of the GNU C library, but are possible
21548 with other
21549 implementations.  The @code{gets} function is the worst, since it almost
21550 invariably overflows its buffer when presented with an input line larger
21551 than the buffer.
21553 @node Volatile Objects
21554 @section Volatile Objects
21555 @cindex volatile objects
21557 The keyword @code{volatile} is often misunderstood in portable code.
21558 Its use inhibits some memory-access optimizations, but programmers often
21559 wish that it had a different meaning than it actually does.
21561 @code{volatile} was designed for code that accesses special objects like
21562 memory-mapped device registers whose contents spontaneously change.
21563 Such code is inherently low-level, and it is difficult to specify
21564 portably what @code{volatile} means in these cases.  The C standard
21565 says, ``What constitutes an access to an object that has
21566 volatile-qualified type is implementation-defined,'' so in theory each
21567 implementation is supposed to fill in the gap by documenting what
21568 @code{volatile} means for that implementation.  In practice, though,
21569 this documentation is usually absent or incomplete.
21571 One area of confusion is the distinction between objects defined with
21572 volatile types, and volatile lvalues.  From the C standard's point of
21573 view, an object defined with a volatile type has externally visible
21574 behavior.  You can think of such objects as having little oscilloscope
21575 probes attached to them, so that the user can observe some properties of
21576 accesses to them, just as the user can observe data written to output
21577 files.  However, the standard does not make it clear whether users can
21578 observe accesses by volatile lvalues to ordinary objects.  For example:
21580 @example
21581 /* Declare and access a volatile object.
21582    Accesses to X are "visible" to users.  */
21583 static int volatile x;
21584 x = 1;
21586 /* Access two ordinary objects via a volatile lvalue.
21587    It's not clear whether accesses to *P are "visible".  */
21588 int y;
21589 int *z = malloc (sizeof (int));
21590 int volatile *p;
21591 p = &y;
21592 *p = 1;
21593 p = z;
21594 *p = 1;
21595 @end example
21597 Programmers often wish that @code{volatile} meant ``Perform the memory
21598 access here and now, without merging several memory accesses, without
21599 changing the memory word size, and without reordering.''  But the C
21600 standard does not require this.  For objects defined with a volatile
21601 type, accesses must be done before the next sequence point; but
21602 otherwise merging, reordering, and word-size change is allowed.  Worse,
21603 it is not clear from the standard whether volatile lvalues provide more
21604 guarantees in general than nonvolatile lvalues, if the underlying
21605 objects are ordinary.
21607 Even when accessing objects defined with a volatile type,
21608 the C standard allows only
21609 extremely limited signal handlers: the behavior is undefined if a signal
21610 handler reads any nonlocal object, or writes to any nonlocal object
21611 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21612 library function other than @code{abort}, @code{signal}, and (if C99 or later)
21613 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21614 disturbing ordinary computation, unless the computation accesses a
21615 @code{sig_atomic_t volatile} lvalue that is not a local variable.
21616 (There is an obscure exception for accesses via a pointer to a volatile
21617 character, since it may point into part of a @code{sig_atomic_t
21618 volatile} object.)  Posix
21619 adds to the list of library functions callable from a portable signal
21620 handler, but otherwise is like the C standard in this area.
21622 Some C implementations allow memory-access optimizations within each
21623 translation unit, such that actual behavior agrees with the behavior
21624 required by the standard only when calling a function in some other
21625 translation unit, and a signal handler acts like it was called from a
21626 different translation unit.  The C standard hints that in these
21627 implementations, objects referred to by signal handlers ``would require
21628 explicit specification of @code{volatile} storage, as well as other
21629 implementation-defined restrictions.''  But unfortunately even for this
21630 special case these other restrictions are often not documented well.
21631 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21632 GNU Compiler Collection (GCC)}, for some
21633 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21634 Defining Signal Handlers, libc, The GNU C Library}, for some
21635 restrictions imposed by the GNU C library.  Restrictions
21636 differ on other platforms.
21638 If possible, it is best to use a signal handler that fits within the
21639 limits imposed by the C and Posix standards.
21641 If this is not practical, you can try the following rules of thumb.  A
21642 signal handler should access only volatile lvalues, preferably lvalues
21643 that refer to objects defined with a volatile type, and should not
21644 assume that the accessed objects have an internally consistent state
21645 if they are larger than a machine word.  Furthermore, installers
21646 should employ compilers and compiler options that are commonly used
21647 for building operating system kernels, because kernels often need more
21648 from @code{volatile} than the C Standard requires, and installers who
21649 compile an application in a similar environment can sometimes benefit
21650 from the extra constraints imposed by kernels on compilers.
21651 Admittedly we are handwaving somewhat here, as there are few
21652 guarantees in this area; the rules of thumb may help to fix some bugs
21653 but there is a good chance that they will not fix them all.
21655 For @code{volatile}, C++ has the same problems that C does.
21656 Multithreaded applications have even more problems with @code{volatile},
21657 but they are beyond the scope of this section.
21659 The bottom line is that using @code{volatile} typically hurts
21660 performance but should not hurt correctness.  In some cases its use
21661 does help correctness, but these cases are often so poorly understood
21662 that all too often adding @code{volatile} to a data structure merely
21663 alleviates some symptoms of a bug while not fixing the bug in general.
21665 @node Floating Point Portability
21666 @section Floating Point Portability
21667 @cindex floating point
21669 Almost all modern systems use IEEE-754 floating point, and it is safe to
21670 assume IEEE-754 in most portable code these days.  For more information,
21671 please see David Goldberg's classic paper
21672 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21673 Scientist Should Know About Floating-Point Arithmetic}.
21675 @node Exiting Portably
21676 @section Exiting Portably
21677 @cindex exiting portably
21679 A C or C++ program can exit with status @var{N} by returning
21680 @var{N} from the @code{main} function.  Portable programs are supposed
21681 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21682 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21683 fail by exiting with status 1, and test programs that assume Posix can
21684 fail by exiting with status values from 1 through 255.  Programs on
21685 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21686 status when @code{main} returned nonzero, but ancient systems like these
21687 are no longer of practical concern.
21689 A program can also exit with status @var{N} by passing @var{N} to the
21690 @code{exit} function, and a program can fail by calling the @code{abort}
21691 function.  If a program is specialized to just some platforms, it can fail
21692 by calling functions specific to those platforms, e.g., @code{_exit}
21693 (Posix).  However, like other functions, an exit
21694 function should be declared, typically by including a header.  For
21695 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21696 either directly or via the default includes (@pxref{Default Includes}).
21698 A program can fail due to undefined behavior such as dereferencing a null
21699 pointer, but this is not recommended as undefined behavior allows an
21700 implementation to do whatever it pleases and this includes exiting
21701 successfully.
21704 @c ================================================== Manual Configuration
21706 @node Manual Configuration
21707 @chapter Manual Configuration
21709 A few kinds of features can't be guessed automatically by running test
21710 programs.  For example, the details of the object-file format, or
21711 special options that need to be passed to the compiler or linker.  You
21712 can check for such features using ad-hoc means, such as having
21713 @command{configure} check the output of the @code{uname} program, or
21714 looking for libraries that are unique to particular systems.  However,
21715 Autoconf provides a uniform method for handling unguessable features.
21717 @menu
21718 * Specifying Target Triplets::  Specifying target triplets
21719 * Canonicalizing::              Getting the canonical system type
21720 * Using System Type::           What to do with the system type
21721 @end menu
21723 @node Specifying Target Triplets
21724 @section Specifying target triplets
21725 @cindex System type
21726 @cindex Target triplet
21727 @c This node used to be named Specifying Names.  The @anchor allows old
21728 @c links to still work.
21729 @anchor{Specifying Names}
21731 Autoconf-generated
21732 @command{configure} scripts can make decisions based on a canonical name
21733 for the system type, or @dfn{target triplet}, which has the form:
21734 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21735 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21737 @command{configure} can usually guess the canonical name for the type of
21738 system it's running on.  To do so it runs a script called
21739 @command{config.guess}, which infers the name using the @code{uname}
21740 command or symbols predefined by the C preprocessor.
21742 Alternately, the user can specify the system type with command line
21743 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21744 necessary when
21745 cross-compiling.  In the most complex case of cross-compiling, three
21746 system types are involved.  The options to specify them are:
21748 @table @option
21749 @item --build=@var{build-type}
21750 the type of system on which the package is being configured and
21751 compiled.  It defaults to the result of running @command{config.guess}.
21752 Specifying a @var{build-type} that differs from @var{host-type} enables
21753 cross-compilation mode.
21755 @item --host=@var{host-type}
21756 the type of system on which the package runs.  By default it is the
21757 same as the build machine.  Specifying a @var{host-type} that differs
21758 from @var{build-type}, when @var{build-type} was also explicitly
21759 specified, enables cross-compilation mode.
21761 @item --target=@var{target-type}
21762 the type of system for which any compiler tools in the package
21763 produce code (rarely needed).  By default, it is the same as host.
21764 @end table
21766 If you mean to override the result of @command{config.guess}, use
21767 @option{--build}, not @option{--host}, since the latter enables
21768 cross-compilation.  For historical reasons,
21769 whenever you specify @option{--host},
21770 be sure to specify @option{--build} too; this will be fixed in the
21771 future.  So, to enter cross-compilation mode, use a command like this
21773 @example
21774 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21775 @end example
21777 @noindent
21778 Note that if you do not specify @option{--host}, @command{configure}
21779 fails if it can't run the code generated by the specified compiler.  For
21780 example, configuring as follows fails:
21782 @example
21783 ./configure CC=m68k-coff-gcc
21784 @end example
21786 When cross-compiling, @command{configure} will warn about any tools
21787 (compilers, linkers, assemblers) whose name is not prefixed with the
21788 host type.  This is an aid to users performing cross-compilation.
21789 Continuing the example above, if a cross-compiler named @command{cc} is
21790 used with a native @command{pkg-config}, then libraries found by
21791 @command{pkg-config} will likely cause subtle build failures; but using
21792 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21793 avoids any confusion.  Avoiding the warning is as simple as creating the
21794 correct symlinks naming the cross tools.
21796 @cindex @command{config.sub}
21797 @command{configure} recognizes short aliases for many system types; for
21798 example, @samp{decstation} can be used instead of
21799 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21800 @command{config.sub} to canonicalize system type aliases.
21802 This section deliberately omits the description of the obsolete
21803 interface; see @ref{Hosts and Cross-Compilation}.
21806 @node Canonicalizing
21807 @section Getting the Canonical System Type
21808 @cindex System type
21809 @cindex Canonical system type
21811 The following macros make the system type available to @command{configure}
21812 scripts.
21814 @ovindex build_alias
21815 @ovindex host_alias
21816 @ovindex target_alias
21818 The variables @samp{build_alias}, @samp{host_alias}, and
21819 @samp{target_alias} are always exactly the arguments of @option{--build},
21820 @option{--host}, and @option{--target}; in particular, they are left empty
21821 if the user did not use them, even if the corresponding
21822 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21823 variables anywhere.  These are the variables that should be used when in
21824 interaction with the user.
21826 If you need to recognize some special environments based on their system
21827 type, run the following macros to get canonical system names.  These
21828 variables are not set before the macro call.
21830 If you use these macros, you must distribute @command{config.guess} and
21831 @command{config.sub} along with your source code.  @xref{Output}, for
21832 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21833 to control in which directory @command{configure} looks for those scripts.
21836 @defmac AC_CANONICAL_BUILD
21837 @acindex{CANONICAL_BUILD}
21838 @ovindex build
21839 @ovindex build_cpu
21840 @ovindex build_vendor
21841 @ovindex build_os
21842 Compute the canonical build-system type variable, @code{build}, and its
21843 three individual parts @code{build_cpu}, @code{build_vendor}, and
21844 @code{build_os}.
21846 If @option{--build} was specified, then @code{build} is the
21847 canonicalization of @code{build_alias} by @command{config.sub},
21848 otherwise it is determined by the shell script @command{config.guess}.
21849 @end defmac
21851 @defmac AC_CANONICAL_HOST
21852 @acindex{CANONICAL_HOST}
21853 @ovindex host
21854 @ovindex host_cpu
21855 @ovindex host_vendor
21856 @ovindex host_os
21857 Compute the canonical host-system type variable, @code{host}, and its
21858 three individual parts @code{host_cpu}, @code{host_vendor}, and
21859 @code{host_os}.
21861 If @option{--host} was specified, then @code{host} is the
21862 canonicalization of @code{host_alias} by @command{config.sub},
21863 otherwise it defaults to @code{build}.
21864 @end defmac
21866 @defmac AC_CANONICAL_TARGET
21867 @acindex{CANONICAL_TARGET}
21868 @ovindex target
21869 @ovindex target_cpu
21870 @ovindex target_vendor
21871 @ovindex target_os
21872 Compute the canonical target-system type variable, @code{target}, and its
21873 three individual parts @code{target_cpu}, @code{target_vendor}, and
21874 @code{target_os}.
21876 If @option{--target} was specified, then @code{target} is the
21877 canonicalization of @code{target_alias} by @command{config.sub},
21878 otherwise it defaults to @code{host}.
21879 @end defmac
21881 Note that there can be artifacts due to the backward compatibility
21882 code.  @xref{Hosts and Cross-Compilation}, for more.
21884 @node Using System Type
21885 @section Using the System Type
21887 In @file{configure.ac} the system type is generally used by one or more
21888 @code{case} statements to select system-specifics.  Shell wildcards can
21889 be used to match a group of system types.
21891 For example, an extra assembler code object file could be chosen, giving
21892 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
21893 following would be used in a makefile to add the object to a
21894 program or library.
21896 @example
21897 AS_CASE([$host],
21898   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
21899   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
21900   [CYCLE_OBJ=""]
21902 AC_SUBST([CYCLE_OBJ])
21903 @end example
21905 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
21906 to select variant source files, for example optimized code for some
21907 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
21908 so some runtime capability checks may be necessary too.
21910 @example
21911 case $host in
21912   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
21913   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
21914   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
21915 esac
21916 @end example
21918 The host system type can also be used to find cross-compilation tools
21919 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
21921 The above examples all show @samp{$host}, since this is where the code
21922 is going to run.  Only rarely is it necessary to test @samp{$build}
21923 (which is where the build is being done).
21925 Whenever you're tempted to use @samp{$host} it's worth considering
21926 whether some sort of probe would be better.  New system types come along
21927 periodically or previously missing features are added.  Well-written
21928 probes can adapt themselves to such things, but hard-coded lists of
21929 names can't.  Here are some guidelines,
21931 @itemize @bullet
21932 @item
21933 Availability of libraries and library functions should always be checked
21934 by probing.
21935 @item
21936 Variant behavior of system calls is best identified with runtime tests
21937 if possible, but bug workarounds or obscure difficulties might have to
21938 be driven from @samp{$host}.
21939 @item
21940 Assembler code is inevitably highly CPU-specific and is best selected
21941 according to @samp{$host_cpu}.
21942 @item
21943 Assembler variations like underscore prefix on globals or ELF versus
21944 COFF type directives are however best determined by probing, perhaps
21945 even examining the compiler output.
21946 @end itemize
21948 @samp{$target} is for use by a package creating a compiler or similar.
21949 For ordinary packages it's meaningless and should not be used.  It
21950 indicates what the created compiler should generate code for, if it can
21951 cross-compile.  @samp{$target} generally selects various hard-coded CPU
21952 and system conventions, since usually the compiler or tools under
21953 construction themselves determine how the target works.
21956 @c ===================================================== Site Configuration.
21958 @node Site Configuration
21959 @chapter Site Configuration
21961 @command{configure} scripts support several kinds of local configuration
21962 decisions.  There are ways for users to specify where external software
21963 packages are, include or exclude optional features, install programs
21964 under modified names, and set default values for @command{configure}
21965 options.
21967 @menu
21968 * Help Formatting::             Customizing @samp{configure --help}
21969 * External Software::           Working with other optional software
21970 * Package Options::             Selecting optional features
21971 * Pretty Help Strings::         Formatting help string
21972 * Option Checking::             Controlling checking of @command{configure} options
21973 * Site Details::                Configuring site details
21974 * Transforming Names::          Changing program names when installing
21975 * Site Defaults::               Giving @command{configure} local defaults
21976 @end menu
21978 @node Help Formatting
21979 @section Controlling Help Output
21981 Users consult @samp{configure --help} to learn of configuration
21982 decisions specific to your package.  By default, @command{configure}
21983 breaks this output into sections for each type of option; within each
21984 section, help strings appear in the order @file{configure.ac} defines
21985 them:
21987 @example
21988 Optional Features:
21989   @dots{}
21990   --enable-bar            include bar
21992 Optional Packages:
21993   @dots{}
21994   --with-foo              use foo
21995 @end example
21997 @defmac AC_PRESERVE_HELP_ORDER
21998 @acindex{PRESERVE_HELP_ORDER}
22000 Request an alternate @option{--help} format, in which options of all
22001 types appear together, in the order defined.  Call this macro before any
22002 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22004 @example
22005 Optional Features and Packages:
22006   @dots{}
22007   --enable-bar            include bar
22008   --with-foo              use foo
22009 @end example
22011 @end defmac
22013 @node External Software
22014 @section Working With External Software
22015 @cindex External software
22017 Some packages require, or can optionally use, other software packages
22018 that are already installed.  The user can give @command{configure}
22019 command line options to specify which such external software to use.
22020 The options have one of these forms:
22022 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22023 @c awful.
22024 @example
22025 --with-@var{package}@r{[}=@var{arg}@r{]}
22026 --without-@var{package}
22027 @end example
22029 For example, @option{--with-gnu-ld} means work with the GNU linker
22030 instead of some other linker.  @option{--with-x} means work with The X
22031 Window System.
22033 The user can give an argument by following the package name with
22034 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22035 packages that are used by default; it says to @emph{not} use the
22036 package.  An argument that is neither @samp{yes} nor @samp{no} could
22037 include a name or number of a version of the other package, to specify
22038 more precisely which other package this program is supposed to work
22039 with.  If no argument is given, it defaults to @samp{yes}.
22040 @option{--without-@var{package}} is equivalent to
22041 @option{--with-@var{package}=no}.
22043 Normally @command{configure} scripts complain about
22044 @option{--with-@var{package}} options that they do not support.
22045 @xref{Option Checking}, for details, and for how to override the
22046 defaults.
22048 For each external software package that may be used, @file{configure.ac}
22049 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22050 user asked to use it.  Whether each package is used or not by default,
22051 and which arguments are valid, is up to you.
22053 @anchor{AC_ARG_WITH}
22054 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22055   @ovar{action-if-given}, @ovar{action-if-not-given})
22056 @acindex{ARG_WITH}
22057 If the user gave @command{configure} the option @option{--with-@var{package}}
22058 or @option{--without-@var{package}}, run shell commands
22059 @var{action-if-given}.  If neither option was given, run shell commands
22060 @var{action-if-not-given}.  The name @var{package} indicates another
22061 software package that this program should work with.  It should consist
22062 only of alphanumeric characters, dashes, plus signs, and dots.
22064 The option's argument is available to the shell commands
22065 @var{action-if-given} in the shell variable @code{withval}, which is
22066 actually just the value of the shell variable named
22067 @code{with_@var{package}}, with any non-alphanumeric characters in
22068 @var{package} changed into @samp{_}.  You may use that variable instead,
22069 if you wish.
22071 The argument @var{help-string} is a description of the option that
22072 looks like this:
22073 @example
22074   --with-readline         support fancy command line editing
22075 @end example
22077 @noindent
22078 @var{help-string} may be more than one line long, if more detail is
22079 needed.  Just make sure the columns line up in @samp{configure
22080 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22081 proper leading whitespace is to format your @var{help-string} with the macro
22082 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22084 The following example shows how to use the @code{AC_ARG_WITH} macro in
22085 a common situation.  You want to let the user decide whether to enable
22086 support for an external library (e.g., the readline library); if the user
22087 specified neither @option{--with-readline} nor @option{--without-readline},
22088 you want to enable support for readline only if the library is available
22089 on the system.
22091 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22092 @example
22093 AC_ARG_WITH([readline],
22094   [AS_HELP_STRING([--with-readline],
22095     [support fancy command line editing @@<:@@default=check@@:>@@])],
22096   [],
22097   [with_readline=check])
22099 LIBREADLINE=
22100 AS_IF([test "x$with_readline" != xno],
22101   [AC_CHECK_LIB([readline], [main],
22102     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22103      AC_DEFINE([HAVE_LIBREADLINE], [1],
22104                [Define if you have libreadline])
22105     ],
22106     [if test "x$with_readline" != xcheck; then
22107        AC_MSG_FAILURE(
22108          [--with-readline was given, but test for readline failed])
22109      fi
22110     ], -lncurses)])
22111 @end example
22113 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22114 possibility to enable support for the readline library, in case it is still
22115 experimental and not well tested, and is therefore disabled by default.
22117 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22118 @example
22119 AC_ARG_WITH([readline],
22120   [AS_HELP_STRING([--with-readline],
22121     [enable experimental support for readline])],
22122   [],
22123   [with_readline=no])
22125 LIBREADLINE=
22126 AS_IF([test "x$with_readline" != xno],
22127   [AC_CHECK_LIB([readline], [main],
22128     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22129      AC_DEFINE([HAVE_LIBREADLINE], [1],
22130                [Define if you have libreadline])
22131     ],
22132     [AC_MSG_FAILURE(
22133        [--with-readline was given, but test for readline failed])],
22134     [-lncurses])])
22135 @end example
22137 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22138 possibility to disable support for the readline library, given that it is
22139 an important feature and that it should be enabled by default.
22141 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22142 @example
22143 AC_ARG_WITH([readline],
22144   [AS_HELP_STRING([--without-readline],
22145     [disable support for readline])],
22146   [],
22147   [with_readline=yes])
22149 LIBREADLINE=
22150 AS_IF([test "x$with_readline" != xno],
22151   [AC_CHECK_LIB([readline], [main],
22152     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22153      AC_DEFINE([HAVE_LIBREADLINE], [1],
22154                [Define if you have libreadline])
22155     ],
22156     [AC_MSG_FAILURE(
22157        [readline test failed (--without-readline to disable)])],
22158     [-lncurses])])
22159 @end example
22161 These three examples can be easily adapted to the case where
22162 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22163 @ref{Package Options}).
22164 @end defmac
22166 @node Package Options
22167 @section Choosing Package Options
22168 @cindex Package options
22169 @cindex Options, package
22171 If a software package has optional compile-time features, the user can
22172 give @command{configure} command line options to specify whether to
22173 compile them.  The options have one of these forms:
22175 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22176 @c awful.
22177 @example
22178 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22179 --disable-@var{feature}
22180 @end example
22182 These options allow users to choose which optional features to build and
22183 install.  @option{--enable-@var{feature}} options should never make a
22184 feature behave differently or cause one feature to replace another.
22185 They should only cause parts of the program to be built rather than left
22186 out.
22188 The user can give an argument by following the feature name with
22189 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22190 that the feature @emph{not} be made available.  A feature with an
22191 argument looks like @option{--enable-debug=stabs}.  If no argument is
22192 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22193 equivalent to @option{--enable-@var{feature}=no}.
22195 Normally @command{configure} scripts complain about
22196 @option{--enable-@var{package}} options that they do not support.
22197 @xref{Option Checking}, for details, and for how to override the
22198 defaults.
22200 For each optional feature, @file{configure.ac} should call
22201 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22202 to include it.  Whether each feature is included or not by default, and
22203 which arguments are valid, is up to you.
22205 @anchor{AC_ARG_ENABLE}
22206 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22207   @ovar{action-if-given}, @ovar{action-if-not-given})
22208 @acindex{ARG_ENABLE}
22209 If the user gave @command{configure} the option
22210 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22211 shell commands @var{action-if-given}.  If neither option was given, run
22212 shell commands @var{action-if-not-given}.  The name @var{feature}
22213 indicates an optional user-level facility.  It should consist only of
22214 alphanumeric characters, dashes, plus signs, and dots.
22216 The option's argument is available to the shell commands
22217 @var{action-if-given} in the shell variable @code{enableval}, which is
22218 actually just the value of the shell variable named
22219 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22220 @var{feature} changed into @samp{_}.  You may use that variable instead,
22221 if you wish.  The @var{help-string} argument is like that of
22222 @code{AC_ARG_WITH} (@pxref{External Software}).
22224 You should format your @var{help-string} with the macro
22225 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22227 See the examples suggested with the definition of @code{AC_ARG_WITH}
22228 (@pxref{External Software}) to get an idea of possible applications of
22229 @code{AC_ARG_ENABLE}.
22230 @end defmac
22232 @node Pretty Help Strings
22233 @section Making Your Help Strings Look Pretty
22234 @cindex Help strings
22236 Properly formatting the @samp{help strings} which are used in
22237 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22238 (@pxref{Package Options}) can be challenging.  Specifically, you want
22239 your own @samp{help strings} to line up in the appropriate columns of
22240 @samp{configure --help} just like the standard Autoconf @samp{help
22241 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22243 @anchor{AS_HELP_STRING}
22244 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22245   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22246 @asindex{HELP_STRING}
22248 Expands into a help string that looks pretty when the user executes
22249 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22250 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22251 Options}).  The following example makes this clearer.
22253 @example
22254 AC_ARG_WITH([foo],
22255   [AS_HELP_STRING([--with-foo],
22256      [use foo (default is no)])],
22257   [use_foo=$withval],
22258   [use_foo=no])
22259 @end example
22261 Then the last few lines of @samp{configure --help} appear like
22262 this:
22264 @example
22265 --enable and --with options recognized:
22266   --with-foo              use foo (default is no)
22267 @end example
22269 Macro expansion is performed on the first argument.  However, the second
22270 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22271 list of text to be reformatted, and is not subject to macro expansion.
22272 Since it is not expanded, it should not be double quoted.
22273 @xref{Autoconf Language}, for a more detailed explanation.
22275 The @code{AS_HELP_STRING} macro is particularly helpful when the
22276 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22277 arguments, as shown in the following example.  Be aware that
22278 @var{left-hand-side} may not expand to unbalanced quotes,
22279 although quadrigraphs can be used.
22281 @example
22282 AC_DEFUN([MY_ARG_WITH],
22283   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22284      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22285                      [use $1 (default is $2)])],
22286      [use_[]$1=$withval],
22287      [use_[]$1=$2])])
22288 MY_ARG_WITH([a_b], [no])
22289 @end example
22290 @noindent
22291 Here, the last few lines of @samp{configure --help} will include:
22293 @example
22294 --enable and --with options recognized:
22295   --with-a-b              use a_b (default is no)
22296 @end example
22298 The parameters @var{indent-column} and @var{wrap-column} were introduced
22299 in Autoconf 2.62.  Generally, they should not be specified; they exist
22300 for fine-tuning of the wrapping.
22301 @example
22302 AS_HELP_STRING([--option], [description of option])
22303 @result{}  --option                description of option
22304 AS_HELP_STRING([--option], [description of option], [15], [30])
22305 @result{}  --option     description of
22306 @result{}               option
22307 @end example
22308 @end defmac
22311 @node Option Checking
22312 @section Controlling Checking of @command{configure} Options
22313 @cindex Options, Package
22315 The @command{configure} script checks its command-line options against a
22316 list of known options, like @option{--help} or @option{--config-cache}.
22317 An unknown option ordinarily indicates a mistake by the user and
22318 @command{configure} halts with an error.  However, by default unknown
22319 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22320 options elicit only a warning, to support configuring entire source
22321 trees.
22323 Source trees often contain multiple packages with a top-level
22324 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22325 (@pxref{Subdirectories}).  Because the packages generally support
22326 different @option{--with-@var{package}} and
22327 @option{--enable-@var{feature}} options, the GNU Coding
22328 Standards say they must accept unrecognized options without halting.
22329 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22330 automatically disables the warnings.
22332 This default behavior may be modified in two ways.  First, the installer
22333 can invoke @code{configure --disable-option-checking} to disable
22334 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22335 options to turn them into fatal errors, respectively.  Second, the
22336 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22338 @defmac AC_DISABLE_OPTION_CHECKING
22339 @acindex{DISABLE_OPTION_CHECKING}
22341 By default, disable warnings related to any unrecognized
22342 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22343 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22345 The installer can override this behavior by passing
22346 @option{--enable-option-checking} (enable warnings) or
22347 @option{--enable-option-checking=fatal} (enable errors) to
22348 @command{configure}.
22349 @end defmac
22352 @node Site Details
22353 @section Configuring Site Details
22354 @cindex Site details
22356 Some software packages require complex site-specific information.  Some
22357 examples are host names to use for certain services, company names, and
22358 email addresses to contact.  Since some configuration scripts generated
22359 by Metaconfig ask for such information interactively, people sometimes
22360 wonder how to get that information in Autoconf-generated configuration
22361 scripts, which aren't interactive.
22363 Such site configuration information should be put in a file that is
22364 edited @emph{only by users}, not by programs.  The location of the file
22365 can either be based on the @code{prefix} variable, or be a standard
22366 location such as the user's home directory.  It could even be specified
22367 by an environment variable.  The programs should examine that file at
22368 runtime, rather than at compile time.  Runtime configuration is more
22369 convenient for users and makes the configuration process simpler than
22370 getting the information while configuring.  @xref{Directory Variables, ,
22371 Variables for Installation Directories, standards, The GNU Coding
22372 Standards}, for more information on where to put data files.
22374 @node Transforming Names
22375 @section Transforming Program Names When Installing
22376 @cindex Transforming program names
22377 @cindex Program names, transforming
22379 Autoconf supports changing the names of programs when installing them.
22380 In order to use these transformations, @file{configure.ac} must call the
22381 macro @code{AC_ARG_PROGRAM}.
22383 @defmac AC_ARG_PROGRAM
22384 @acindex{ARG_PROGRAM}
22385 @ovindex program_transform_name
22386 Place in output variable @code{program_transform_name} a sequence of
22387 @code{sed} commands for changing the names of installed programs.
22389 If any of the options described below are given to @command{configure},
22390 program names are transformed accordingly.  Otherwise, if
22391 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22392 is given, the target type followed by a dash is used as a prefix.
22393 Otherwise, no program name transformation is done.
22394 @end defmac
22396 @menu
22397 * Transformation Options::      @command{configure} options to transform names
22398 * Transformation Examples::     Sample uses of transforming names
22399 * Transformation Rules::        Makefile uses of transforming names
22400 @end menu
22402 @node Transformation Options
22403 @subsection Transformation Options
22405 You can specify name transformations by giving @command{configure} these
22406 command line options:
22408 @table @option
22409 @item --program-prefix=@var{prefix}
22410 prepend @var{prefix} to the names;
22412 @item --program-suffix=@var{suffix}
22413 append @var{suffix} to the names;
22415 @item --program-transform-name=@var{expression}
22416 perform @code{sed} substitution @var{expression} on the names.
22417 @end table
22419 @node Transformation Examples
22420 @subsection Transformation Examples
22422 These transformations are useful with programs that can be part of a
22423 cross-compilation development environment.  For example, a
22424 cross-assembler running on a Sun 4 configured with
22425 @option{--target=i960-vxworks} is normally installed as
22426 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22427 with a native Sun 4 assembler.
22429 You can force a program name to begin with @file{g}, if you don't want
22430 GNU programs installed on your system to shadow other programs with
22431 the same name.  For example, if you configure GNU @code{diff} with
22432 @option{--program-prefix=g}, then when you run @samp{make install} it is
22433 installed as @file{/usr/local/bin/gdiff}.
22435 As a more sophisticated example, you could use
22437 @example
22438 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22439 @end example
22440 @noindent
22442 to prepend @samp{g} to most of the program names in a source tree,
22443 excepting those like @code{gdb} that already have one and those like
22444 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22445 assuming that you have a source tree containing those programs that is
22446 set up to use this feature.)
22448 One way to install multiple versions of some programs simultaneously is
22449 to append a version number to the name of one or both.  For example, if
22450 you want to keep Autoconf version 1 around for awhile, you can configure
22451 Autoconf version 2 using @option{--program-suffix=2} to install the
22452 programs as @file{/usr/local/bin/autoconf2},
22453 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22454 that only the binaries are renamed, therefore you'd have problems with
22455 the library files which might overlap.
22457 @node Transformation Rules
22458 @subsection Transformation Rules
22460 Here is how to use the variable @code{program_transform_name} in a
22461 @file{Makefile.in}:
22463 @example
22464 PROGRAMS = cp ls rm
22465 transform = @@program_transform_name@@
22466 install:
22467         for p in $(PROGRAMS); do \
22468           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22469                                               sed '$(transform)'`; \
22470         done
22472 uninstall:
22473         for p in $(PROGRAMS); do \
22474           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22475 @c $$ restore font-lock
22476         done
22477 @end example
22479 It is guaranteed that @code{program_transform_name} is never empty, and
22480 that there are no useless separators.  Therefore you may safely embed
22481 @code{program_transform_name} within a sed program using @samp{;}:
22483 @example
22484 transform = @@program_transform_name@@
22485 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22486 @end example
22488 Whether to do the transformations on documentation files (Texinfo or
22489 @code{man}) is a tricky question; there seems to be no perfect answer,
22490 due to the several reasons for name transforming.  Documentation is not
22491 usually particular to a specific architecture, and Texinfo files do not
22492 conflict with system documentation.  But they might conflict with
22493 earlier versions of the same files, and @code{man} pages sometimes do
22494 conflict with system documentation.  As a compromise, it is probably
22495 best to do name transformations on @code{man} pages but not on Texinfo
22496 manuals.
22498 @node Site Defaults
22499 @section Setting Site Defaults
22500 @cindex Site defaults
22501 @cindex config.site
22503 Autoconf-generated @command{configure} scripts allow your site to provide
22504 default values for some configuration values.  You do this by creating
22505 site- and system-wide initialization files.
22507 @evindex CONFIG_SITE
22508 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22509 uses its value as the name of a shell script to read; it is recommended
22510 that this be an absolute file name.  Otherwise, it
22511 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22512 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22513 settings in machine-specific files override those in machine-independent
22514 ones in case of conflict.
22516 Site files can be arbitrary shell scripts, but only certain kinds of
22517 code are really appropriate to be in them.  Because @command{configure}
22518 reads any cache file after it has read any site files, a site file can
22519 define a default cache file to be shared between all Autoconf-generated
22520 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22521 you set a default cache file in a site file, it is a good idea to also
22522 set the output variable @code{CC} in that site file, because the cache
22523 file is only valid for a particular compiler, but many systems have
22524 several available.
22526 You can examine or override the value set by a command line option to
22527 @command{configure} in a site file; options set shell variables that have
22528 the same names as the options, with any dashes turned into underscores.
22529 The exceptions are that @option{--without-} and @option{--disable-} options
22530 are like giving the corresponding @option{--with-} or @option{--enable-}
22531 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22532 sets the variable @code{cache_file} to the value @samp{localcache};
22533 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22534 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22535 variable @code{prefix} to the value @samp{/usr}; etc.
22537 Site files are also good places to set default values for other output
22538 variables, such as @code{CFLAGS}, if you need to give them non-default
22539 values: anything you would normally do, repetitively, on the command
22540 line.  If you use non-default values for @var{prefix} or
22541 @var{exec_prefix} (wherever you locate the site file), you can set them
22542 in the site file if you specify it with the @code{CONFIG_SITE}
22543 environment variable.
22545 You can set some cache values in the site file itself.  Doing this is
22546 useful if you are cross-compiling, where it is impossible to check features
22547 that require running a test program.  You could ``prime the cache'' by
22548 setting those values correctly for that system in
22549 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22550 variables you need to set, see the documentation of the respective
22551 Autoconf macro.  If the variables or their semantics are undocumented,
22552 you may need to look for shell variables with @samp{_cv_} in their names
22553 in the affected @command{configure} scripts, or in the Autoconf M4
22554 source code for those macros; but in that case, their name or semantics
22555 may change in a future Autoconf version.
22557 The cache file is careful to not override any variables set in the site
22558 files.  Similarly, you should not override command-line options in the
22559 site files.  Your code should check that variables such as @code{prefix}
22560 and @code{cache_file} have their default values (as set near the top of
22561 @command{configure}) before changing them.
22563 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22564 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22565 file (if @code{CONFIG_SITE} is not set to a different file).
22567 @example
22568 # /usr/share/local/gnu/share/config.site for configure
22570 # Change some defaults.
22571 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22572 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22573 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22574 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22576 # Give Autoconf 2.x generated configure scripts a shared default
22577 # cache file for feature test results, architecture-specific.
22578 if test "$cache_file" = /dev/null; then
22579   cache_file="$prefix/var/config.cache"
22580   # A cache file is only valid for one C compiler.
22581   CC=gcc
22583 @end example
22585 @c Leave this use of ``File system'' rendered as one word, but
22586 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22587 @cindex File@/system Hierarchy Standard
22588 @cindex FHS
22590 Another use of @file{config.site} is for priming the directory variables
22591 @c ``File system'', but slightly obfuscated, as above.
22592 in a manner consistent with the File@/system Hierarchy Standard
22593 (FHS).  Once the following file is installed at
22594 @file{/usr/share/config.site}, a user can execute simply
22595 @code{./configure --prefix=/usr} to get all the directories chosen in
22596 the locations recommended by FHS.
22598 @example
22599 # /usr/share/config.site for FHS defaults when installing below /usr,
22600 # and the respective settings were not changed on the command line.
22601 if test "$prefix" = /usr; then
22602   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22603   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22604   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22606 @end example
22608 @cindex @file{lib64}
22609 @cindex 64-bit libraries
22610 Likewise, on platforms where 64-bit libraries are built by default, then
22611 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22612 it is appropriate to install @file{/usr/local/@/share/config.site}:
22614 @example
22615 # /usr/local/share/config.site for platforms that prefer
22616 # the directory /usr/local/lib64 over /usr/local/lib.
22617 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22618 @end example
22621 @c ============================================== Running configure Scripts.
22623 @node Running configure Scripts
22624 @chapter Running @command{configure} Scripts
22625 @cindex @command{configure}
22627 Below are instructions on how to configure a package that uses a
22628 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22629 file in the package.  A plain-text version of @file{INSTALL} which you
22630 may use comes with Autoconf.
22632 @menu
22633 * Basic Installation::          Instructions for typical cases
22634 * Compilers and Options::       Selecting compilers and optimization
22635 * Multiple Architectures::      Compiling for multiple architectures at once
22636 * Installation Names::          Installing in different directories
22637 * Optional Features::           Selecting optional features
22638 * Particular Systems::          Particular systems
22639 * System Type::                 Specifying the system type
22640 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22641 * Defining Variables::          Specifying the compiler etc.
22642 * configure Invocation::        Changing how @command{configure} runs
22643 @end menu
22645 @set autoconf
22646 @include install.texi
22649 @c ============================================== config.status Invocation
22651 @node config.status Invocation
22652 @chapter config.status Invocation
22653 @cindex @command{config.status}
22655 The @command{configure} script creates a file named @file{config.status},
22656 which actually configures, @dfn{instantiates}, the template files.  It
22657 also records the configuration options that were specified when the
22658 package was last configured in case reconfiguring is needed.
22660 Synopsis:
22661 @example
22662 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22663 @end example
22665 It configures each @var{tag}; if none are specified, all the templates
22666 are instantiated.  A @var{tag} refers to a file or other tag associated
22667 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22668 macro (@pxref{Configuration Actions}).  The files must be specified
22669 without their dependencies, as in
22671 @example
22672 ./config.status foobar
22673 @end example
22675 @noindent
22678 @example
22679 ./config.status foobar:foo.in:bar.in
22680 @end example
22682 The supported options are:
22684 @table @option
22685 @item --help
22686 @itemx -h
22687 Print a summary of the command line options, the list of the template
22688 files, and exit.
22690 @item --version
22691 @itemx -V
22692 Print the version number of Autoconf and the configuration settings,
22693 and exit.
22695 @item --config
22696 Print the configuration settings in reusable way, quoted for the shell,
22697 and exit.  For example, for a debugging build that otherwise reuses the
22698 configuration from a different build directory @var{build-dir} of a
22699 package in @var{src-dir}, you could use the following:
22701 @example
22702 args=`@var{build-dir}/config.status --config`
22703 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22704 @end example
22706 @noindent
22707 Note that it may be necessary to override a @option{--srcdir} setting
22708 that was saved in the configuration, if the arguments are used in a
22709 different build directory.
22711 @item --silent
22712 @itemx --quiet
22713 @itemx -q
22714 Do not print progress messages.
22716 @item --debug
22717 @itemx -d
22718 Don't remove the temporary files.
22720 @item --file=@var{file}[:@var{template}]
22721 Require that @var{file} be instantiated as if
22722 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22723 @var{file} and @var{template} may be @samp{-} in which case the standard
22724 output and/or standard input, respectively, is used.  If a
22725 @var{template} file name is relative, it is first looked for in the build
22726 tree, and then in the source tree.  @xref{Configuration Actions}, for
22727 more details.
22729 This option and the following ones provide one way for separately
22730 distributed packages to share the values computed by @command{configure}.
22731 Doing so can be useful if some of the packages need a superset of the
22732 features that one of them, perhaps a common library, does.  These
22733 options allow a @file{config.status} file to create files other than the
22734 ones that its @file{configure.ac} specifies, so it can be used for a
22735 different package, or for extracting a subset of values.  For example,
22737 @example
22738 echo '@@CC@@' | ./config.status --file=-
22739 @end example
22741 @noindent
22742 provides the value of @code{@@CC@@} on standard output.
22744 @item --header=@var{file}[:@var{template}]
22745 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22747 @item --recheck
22748 Ask @file{config.status} to update itself and exit (no instantiation).
22749 This option is useful if you change @command{configure}, so that the
22750 results of some tests might be different from the previous run.  The
22751 @option{--recheck} option reruns @command{configure} with the same arguments
22752 you used before, plus the @option{--no-create} option, which prevents
22753 @command{configure} from running @file{config.status} and creating
22754 @file{Makefile} and other files, and the @option{--no-recursion} option,
22755 which prevents @command{configure} from running other @command{configure}
22756 scripts in subdirectories.  (This is so other Make rules can
22757 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22758 for an example).
22759 @end table
22761 @file{config.status} checks several optional environment variables that
22762 can alter its behavior:
22764 @anchor{CONFIG_SHELL}
22765 @defvar CONFIG_SHELL
22766 @evindex CONFIG_SHELL
22767 The shell with which to run @command{configure}.  It must be
22768 Bourne-compatible, and the absolute name of the shell should be passed.
22769 The default is a shell that supports @code{LINENO} if available, and
22770 @file{/bin/sh} otherwise.
22771 @end defvar
22773 @defvar CONFIG_STATUS
22774 @evindex CONFIG_STATUS
22775 The file name to use for the shell script that records the
22776 configuration.  The default is @file{./config.status}.  This variable is
22777 useful when one package uses parts of another and the @command{configure}
22778 scripts shouldn't be merged because they are maintained separately.
22779 @end defvar
22781 You can use @file{./config.status} in your makefiles.  For example, in
22782 the dependencies given above (@pxref{Automatic Remaking}),
22783 @file{config.status} is run twice when @file{configure.ac} has changed.
22784 If that bothers you, you can make each run only regenerate the files for
22785 that rule:
22786 @example
22787 @group
22788 config.h: stamp-h
22789 stamp-h: config.h.in config.status
22790         ./config.status config.h
22791         echo > stamp-h
22793 Makefile: Makefile.in config.status
22794         ./config.status Makefile
22795 @end group
22796 @end example
22798 The calling convention of @file{config.status} has changed; see
22799 @ref{Obsolete config.status Use}, for details.
22802 @c =================================================== Obsolete Constructs
22804 @node Obsolete Constructs
22805 @chapter Obsolete Constructs
22806 @cindex Obsolete constructs
22808 Autoconf changes, and throughout the years some constructs have been
22809 obsoleted.  Most of the changes involve the macros, but in some cases
22810 the tools themselves, or even some concepts, are now considered
22811 obsolete.
22813 You may completely skip this chapter if you are new to Autoconf.  Its
22814 intention is mainly to help maintainers updating their packages by
22815 understanding how to move to more modern constructs.
22817 @menu
22818 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
22819 * acconfig Header::             Additional entries in @file{config.h.in}
22820 * autoupdate Invocation::       Automatic update of @file{configure.ac}
22821 * Obsolete Macros::             Backward compatibility macros
22822 * Autoconf 1::                  Tips for upgrading your files
22823 * Autoconf 2.13::               Some fresher tips
22824 @end menu
22826 @node Obsolete config.status Use
22827 @section Obsolete @file{config.status} Invocation
22829 @file{config.status} now supports arguments to specify the files to
22830 instantiate; see @ref{config.status Invocation}, for more details.
22831 Before, environment variables had to be used.
22833 @defvar CONFIG_COMMANDS
22834 @evindex CONFIG_COMMANDS
22835 The tags of the commands to execute.  The default is the arguments given
22836 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
22837 @file{configure.ac}.
22838 @end defvar
22840 @defvar CONFIG_FILES
22841 @evindex CONFIG_FILES
22842 The files in which to perform @samp{@@@var{variable}@@} substitutions.
22843 The default is the arguments given to @code{AC_OUTPUT} and
22844 @code{AC_CONFIG_FILES} in @file{configure.ac}.
22845 @end defvar
22847 @defvar CONFIG_HEADERS
22848 @evindex CONFIG_HEADERS
22849 The files in which to substitute C @code{#define} statements.  The
22850 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
22851 macro was not called, @file{config.status} ignores this variable.
22852 @end defvar
22854 @defvar CONFIG_LINKS
22855 @evindex CONFIG_LINKS
22856 The symbolic links to establish.  The default is the arguments given to
22857 @code{AC_CONFIG_LINKS}; if that macro was not called,
22858 @file{config.status} ignores this variable.
22859 @end defvar
22861 In @ref{config.status Invocation}, using this old interface, the example
22862 would be:
22864 @example
22865 @group
22866 config.h: stamp-h
22867 stamp-h: config.h.in config.status
22868         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
22869           CONFIG_HEADERS=config.h ./config.status
22870         echo > stamp-h
22872 Makefile: Makefile.in config.status
22873         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
22874           CONFIG_FILES=Makefile ./config.status
22875 @end group
22876 @end example
22878 @noindent
22879 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
22880 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
22881 for @code{CONFIG_COMMANDS}, etc.)
22884 @node acconfig Header
22885 @section @file{acconfig.h}
22887 @cindex @file{acconfig.h}
22888 @cindex @file{config.h.top}
22889 @cindex @file{config.h.bot}
22891 In order to produce @file{config.h.in}, @command{autoheader} needs to
22892 build or to find templates for each symbol.  Modern releases of Autoconf
22893 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
22894 Macros}), but in older releases a file, @file{acconfig.h}, contained the
22895 list of needed templates.  @command{autoheader} copied comments and
22896 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
22897 the current directory, if present.  This file used to be mandatory if
22898 you @code{AC_DEFINE} any additional symbols.
22900 Modern releases of Autoconf also provide @code{AH_TOP} and
22901 @code{AH_BOTTOM} if you need to prepend/append some information to
22902 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
22903 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
22904 @command{autoheader} copies the lines before the line containing
22905 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
22906 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
22907 @command{autoheader} copies the lines after that line to the end of the
22908 file it generates.  Either or both of those strings may be omitted.  An
22909 even older alternate way to produce the same effect in ancient versions
22910 of Autoconf is to create the files @file{@var{file}.top} (typically
22911 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
22912 directory.  If they exist, @command{autoheader} copies them to the
22913 beginning and end, respectively, of its output.
22915 In former versions of Autoconf, the files used in preparing a software
22916 package for distribution were:
22917 @example
22918 @group
22919 configure.ac --.   .------> autoconf* -----> configure
22920                +---+
22921 [aclocal.m4] --+   `---.
22922 [acsite.m4] ---'       |
22923                        +--> [autoheader*] -> [config.h.in]
22924 [acconfig.h] ----.     |
22925                  +-----'
22926 [config.h.top] --+
22927 [config.h.bot] --'
22928 @end group
22929 @end example
22931 Using only the @code{AH_} macros, @file{configure.ac} should be
22932 self-contained, and should not depend upon @file{acconfig.h} etc.
22935 @node autoupdate Invocation
22936 @section Using @command{autoupdate} to Modernize @file{configure.ac}
22937 @cindex @command{autoupdate}
22939 The @command{autoupdate} program updates a @file{configure.ac} file that
22940 calls Autoconf macros by their old names to use the current macro names.
22941 In version 2 of Autoconf, most of the macros were renamed to use a more
22942 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
22943 description of the new scheme.  Although the old names still work
22944 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
22945 new names), you can make your @file{configure.ac} files more readable
22946 and make it easier to use the current Autoconf documentation if you
22947 update them to use the new macro names.
22949 @evindex SIMPLE_BACKUP_SUFFIX
22950 If given no arguments, @command{autoupdate} updates @file{configure.ac},
22951 backing up the original version with the suffix @file{~} (or the value
22952 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
22953 set).  If you give @command{autoupdate} an argument, it reads that file
22954 instead of @file{configure.ac} and writes the updated file to the
22955 standard output.
22957 @noindent
22958 @command{autoupdate} accepts the following options:
22960 @table @option
22961 @item --help
22962 @itemx -h
22963 Print a summary of the command line options and exit.
22965 @item --version
22966 @itemx -V
22967 Print the version number of Autoconf and exit.
22969 @item --verbose
22970 @itemx -v
22971 Report processing steps.
22973 @item --debug
22974 @itemx -d
22975 Don't remove the temporary files.
22977 @item --force
22978 @itemx -f
22979 Force the update even if the file has not changed.  Disregard the cache.
22981 @item --include=@var{dir}
22982 @itemx -I @var{dir}
22983 Also look for input files in @var{dir}.  Multiple invocations accumulate.
22984 Directories are browsed from last to first.
22986 @item --prepend-include=@var{dir}
22987 @itemx -B @var{dir}
22988 Prepend directory @var{dir} to the search path.  This is used to include
22989 the language-specific files before any third-party macros.
22990 @end table
22992 @node Obsolete Macros
22993 @section Obsolete Macros
22995 Several macros are obsoleted in Autoconf, for various reasons (typically
22996 they failed to quote properly, couldn't be extended for more recent
22997 issues, etc.).  They are still supported, but deprecated: their use
22998 should be avoided.
23000 During the jump from Autoconf version 1 to version 2, most of the
23001 macros were renamed to use a more uniform and descriptive naming scheme,
23002 but their signature did not change.  @xref{Macro Names}, for a
23003 description of the new naming scheme.  Below, if there is just the mapping
23004 from old names to new names for these macros, the reader is invited to
23005 refer to the definition of the new macro for the signature and the
23006 description.
23008 @defmac AC_AIX
23009 @acindex{AIX}
23010 @cvindex _ALL_SOURCE
23011 This macro is a platform-specific subset of
23012 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23013 @end defmac
23015 @defmac AC_ALLOCA
23016 @acindex{ALLOCA}
23017 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23018 @end defmac
23020 @defmac AC_ARG_ARRAY
23021 @acindex{ARG_ARRAY}
23022 Removed because of limited usefulness.
23023 @end defmac
23025 @defmac AC_C_CROSS
23026 @acindex{C_CROSS}
23027 This macro is obsolete; it does nothing.
23028 @end defmac
23030 @defmac AC_C_LONG_DOUBLE
23031 @acindex{C_LONG_DOUBLE}
23032 @cvindex HAVE_LONG_DOUBLE
23033 If the C compiler supports a working @code{long double} type with more
23034 range or precision than the @code{double} type, define
23035 @code{HAVE_LONG_DOUBLE}.
23037 You should use @code{AC_TYPE_LONG_DOUBLE} or
23038 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23039 @end defmac
23041 @defmac AC_CANONICAL_SYSTEM
23042 @acindex{CANONICAL_SYSTEM}
23043 Determine the system type and set output variables to the names of the
23044 canonical system types.  @xref{Canonicalizing}, for details about the
23045 variables this macro sets.
23047 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23048 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23049 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23050 other macros (@pxref{Canonicalizing}).
23051 @end defmac
23053 @defmac AC_CHAR_UNSIGNED
23054 @acindex{CHAR_UNSIGNED}
23055 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23056 @end defmac
23058 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23059 @acindex{CHECK_TYPE}
23060 Autoconf, up to 2.13, used to provide this version of
23061 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23062 it is a member of the @code{CHECK} clan, it does
23063 more than just checking.  Secondly, missing types are defined
23064 using @code{#define}, not @code{typedef}, and this can lead to
23065 problems in the case of pointer types.
23067 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23068 @ref{Generic Types}, for the description of the current macro.
23070 If the type @var{type} is not defined, define it to be the C (or C++)
23071 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23073 This macro is equivalent to:
23075 @example
23076 AC_CHECK_TYPE([@var{type}], [],
23077   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23078      [Define to `@var{default}'
23079       if <sys/types.h> does not define.])])
23080 @end example
23082 In order to keep backward compatibility, the two versions of
23083 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23085 @enumerate
23086 @item
23087 If there are three or four arguments, the modern version is used.
23089 @item
23090 If the second argument appears to be a C or C++ type, then the
23091 obsolete version is used.  This happens if the argument is a C or C++
23092 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23093 followed by one of @samp{[(* } and then by a string of zero or more
23094 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23096 @item
23097 If the second argument is spelled with the alphabet of valid C and C++
23098 types, the user is warned and the modern version is used.
23100 @item
23101 Otherwise, the modern version is used.
23102 @end enumerate
23104 @noindent
23105 You are encouraged either to use a valid builtin type, or to use the
23106 equivalent modern code (see above), or better yet, to use
23107 @code{AC_CHECK_TYPES} together with
23109 @example
23110 #ifndef HAVE_LOFF_T
23111 typedef loff_t off_t;
23112 #endif
23113 @end example
23114 @end defmac
23115 @c end of AC_CHECK_TYPE
23117 @defmac AC_CHECKING (@var{feature-description})
23118 @acindex{CHECKING}
23119 Same as
23121 @example
23122 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23123 @end example
23125 @noindent
23126 @xref{AC_MSG_NOTICE}.
23127 @end defmac
23129 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23130   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23131 @acindex{COMPILE_CHECK}
23132 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23133 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23134 addition that it prints @samp{checking for @var{echo-text}} to the
23135 standard output first, if @var{echo-text} is non-empty.  Use
23136 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23137 messages (@pxref{Printing Messages}).
23138 @end defmac
23140 @defmac AC_CONST
23141 @acindex{CONST}
23142 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23143 @end defmac
23145 @defmac AC_CROSS_CHECK
23146 @acindex{CROSS_CHECK}
23147 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23148 @code{:-)}.
23149 @end defmac
23151 @defmac AC_CYGWIN
23152 @acindex{CYGWIN}
23153 @evindex CYGWIN
23154 Check for the Cygwin environment in which case the shell variable
23155 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23156 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23157 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23159 @example
23160 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23161 case $host_os in
23162   *cygwin* ) CYGWIN=yes;;
23163          * ) CYGWIN=no;;
23164 esac
23165 @end example
23167 Beware that the variable @env{CYGWIN} has a special meaning when
23168 running Cygwin, and should not be changed.  That's yet another reason
23169 not to use this macro.
23170 @end defmac
23172 @defmac AC_DECL_SYS_SIGLIST
23173 @acindex{DECL_SYS_SIGLIST}
23174 @cvindex SYS_SIGLIST_DECLARED
23175 Same as:
23177 @example
23178 AC_CHECK_DECLS([sys_siglist], [], [],
23179 [#include <signal.h>
23180 /* NetBSD declares sys_siglist in unistd.h.  */
23181 #ifdef HAVE_UNISTD_H
23182 # include <unistd.h>
23183 #endif
23185 @end example
23187 @noindent
23188 @xref{AC_CHECK_DECLS}.
23189 @end defmac
23191 @defmac AC_DECL_YYTEXT
23192 @acindex{DECL_YYTEXT}
23193 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23194 @end defmac
23196 @defmac AC_DIR_HEADER
23197 @acindex{DIR_HEADER}
23198 @cvindex DIRENT
23199 @cvindex SYSNDIR
23200 @cvindex SYSDIR
23201 @cvindex NDIR
23202 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23203 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23204 (@pxref{AC_HEADER_DIRENT}),
23205 but defines a different set of C preprocessor macros to indicate which
23206 header file is found:
23208 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23209 @item Header            @tab Old Symbol     @tab New Symbol
23210 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23211 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23212 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23213 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23214 @end multitable
23215 @end defmac
23217 @defmac AC_DYNIX_SEQ
23218 @acindex{DYNIX_SEQ}
23219 If on DYNIX/ptx, add @option{-lseq} to output variable
23220 @code{LIBS}.  This macro used to be defined as
23222 @example
23223 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23224 @end example
23226 @noindent
23227 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23228 @end defmac
23230 @defmac AC_EXEEXT
23231 @acindex{EXEEXT}
23232 @ovindex EXEEXT
23233 Defined the output variable @code{EXEEXT} based on the output of the
23234 compiler, which is now done automatically.  Typically set to empty
23235 string if Posix and @samp{.exe} if a DOS variant.
23236 @end defmac
23238 @defmac AC_EMXOS2
23239 @acindex{EMXOS2}
23240 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23241 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23242 check the nature of the host is using @code{AC_CANONICAL_HOST}
23243 (@pxref{Canonicalizing}).
23244 @end defmac
23246 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23247   @ovar{action-if-not-given})
23248 @acindex{ENABLE}
23249 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23250 support providing a help string (@pxref{AC_ARG_ENABLE}).
23251 @end defmac
23253 @defmac AC_ERROR
23254 @acindex{ERROR}
23255 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23256 @end defmac
23258 @defmac AC_FIND_X
23259 @acindex{FIND_X}
23260 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23261 @end defmac
23263 @defmac AC_FIND_XTRA
23264 @acindex{FIND_XTRA}
23265 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23266 @end defmac
23268 @defmac AC_FOREACH
23269 @acindex{FOREACH}
23270 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23271 @end defmac
23273 @defmac AC_FUNC_CHECK
23274 @acindex{FUNC_CHECK}
23275 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23276 @end defmac
23278 @anchor{AC_FUNC_SETVBUF_REVERSED}
23279 @defmac AC_FUNC_SETVBUF_REVERSED
23280 @acindex{FUNC_SETVBUF_REVERSED}
23281 @cvindex SETVBUF_REVERSED
23282 @c @fuindex setvbuf
23283 @prindex @code{setvbuf}
23284 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23285 the buffering type as its second argument and the buffer pointer as the
23286 third, instead of the other way around, and defined
23287 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23288 were those based on SVR2, which became obsolete in 1987, and the macro
23289 is no longer needed.
23290 @end defmac
23292 @defmac AC_FUNC_WAIT3
23293 @acindex{FUNC_WAIT3}
23294 @cvindex HAVE_WAIT3
23295 @c @fuindex wait3
23296 @prindex @code{wait3}
23297 If @code{wait3} is found and fills in the contents of its third argument
23298 (a @samp{struct rusage *}), which HP-UX does not do, define
23299 @code{HAVE_WAIT3}.
23301 These days portable programs should use @code{waitpid}, not
23302 @code{wait3}, as @code{wait3} has been removed from Posix.
23303 @end defmac
23305 @defmac AC_GCC_TRADITIONAL
23306 @acindex{GCC_TRADITIONAL}
23307 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23308 @end defmac
23310 @defmac AC_GETGROUPS_T
23311 @acindex{GETGROUPS_T}
23312 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23313 @end defmac
23315 @defmac AC_GETLOADAVG
23316 @acindex{GETLOADAVG}
23317 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23318 @end defmac
23320 @defmac AC_GNU_SOURCE
23321 @acindex{GNU_SOURCE}
23322 @cvindex _GNU_SOURCE
23323 This macro is a platform-specific subset of
23324 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23325 @end defmac
23327 @defmac AC_HAVE_FUNCS
23328 @acindex{HAVE_FUNCS}
23329 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23330 @end defmac
23332 @defmac AC_HAVE_HEADERS
23333 @acindex{HAVE_HEADERS}
23334 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23335 @end defmac
23337 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23338   @ovar{action-if-not-found}, @ovar{other-libraries})
23339 @acindex{HAVE_LIBRARY}
23340 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23341 @var{function} argument of @code{main}.  In addition, @var{library} can
23342 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23343 all of those cases, the compiler is passed @option{-lfoo}.  However,
23344 @var{library} cannot be a shell variable; it must be a literal name.
23345 @xref{AC_CHECK_LIB}.
23346 @end defmac
23348 @defmac AC_HAVE_POUNDBANG
23349 @acindex{HAVE_POUNDBANG}
23350 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23351 @end defmac
23353 @defmac AC_HEADER_CHECK
23354 @acindex{HEADER_CHECK}
23355 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23356 @end defmac
23358 @defmac AC_HEADER_EGREP
23359 @acindex{HEADER_EGREP}
23360 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23361 @end defmac
23363 @defmac AC_HELP_STRING
23364 @acindex{HELP_STRING}
23365 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23366 @end defmac
23368 @defmac AC_INIT (@var{unique-file-in-source-dir})
23369 @acindex{INIT}
23370 Formerly @code{AC_INIT} used to have a single argument, and was
23371 equivalent to:
23373 @example
23374 AC_INIT
23375 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23376 @end example
23377 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23378 @end defmac
23380 @defmac AC_INLINE
23381 @acindex{INLINE}
23382 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23383 @end defmac
23385 @defmac AC_INT_16_BITS
23386 @acindex{INT_16_BITS}
23387 @cvindex INT_16_BITS
23388 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23389 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23390 @end defmac
23392 @defmac AC_IRIX_SUN
23393 @acindex{IRIX_SUN}
23394 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23395 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23396 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23397 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23398 getpwnam)}.  Up to Autoconf 2.13, it used to be
23400 @example
23401 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23402 @end example
23404 @noindent
23405 now it is defined as
23407 @example
23408 AC_FUNC_GETMNTENT
23409 AC_CHECK_LIB([sun], [getpwnam])
23410 @end example
23412 @noindent
23413 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23414 @end defmac
23416 @defmac AC_ISC_POSIX
23417 @acindex{ISC_POSIX}
23418 @ovindex LIBS
23419 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23420 necessary for Posix facilities.  Sun dropped support for the obsolete
23421 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23422 need not use this macro.  It is implemented as
23423 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23424 @end defmac
23426 @defmac AC_LANG_C
23427 @acindex{LANG_C}
23428 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23429 @end defmac
23431 @defmac AC_LANG_CPLUSPLUS
23432 @acindex{LANG_CPLUSPLUS}
23433 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23434 @end defmac
23436 @defmac AC_LANG_FORTRAN77
23437 @acindex{LANG_FORTRAN77}
23438 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23439 @end defmac
23441 @defmac AC_LANG_RESTORE
23442 @acindex{LANG_RESTORE}
23443 Select the @var{language} that is saved on the top of the stack, as set
23444 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23445 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23446 preferred way to change languages.
23447 @end defmac
23449 @defmac AC_LANG_SAVE
23450 @acindex{LANG_SAVE}
23451 Remember the current language (as set by @code{AC_LANG}) on a stack.
23452 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23453 (@pxref{AC_LANG_PUSH}).
23454 @end defmac
23456 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23457 @acindex{LINK_FILES}
23458 This is an obsolete version of @code{AC_CONFIG_LINKS}
23459 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23461 @example
23462 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23463               host.h            object.h)
23464 @end example
23466 @noindent
23469 @example
23470 AC_CONFIG_LINKS([host.h:config/$machine.h
23471                 object.h:config/$obj_format.h])
23472 @end example
23473 @end defmac
23475 @defmac AC_LN_S
23476 @acindex{LN_S}
23477 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23478 @end defmac
23480 @defmac AC_LONG_64_BITS
23481 @acindex{LONG_64_BITS}
23482 @cvindex LONG_64_BITS
23483 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23484 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23485 (@pxref{AC_CHECK_SIZEOF}).
23486 @end defmac
23488 @defmac AC_LONG_DOUBLE
23489 @acindex{LONG_DOUBLE}
23490 If the C compiler supports a working @code{long double} type with more
23491 range or precision than the @code{double} type, define
23492 @code{HAVE_LONG_DOUBLE}.
23494 You should use @code{AC_TYPE_LONG_DOUBLE} or
23495 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23496 @end defmac
23498 @defmac AC_LONG_FILE_NAMES
23499 @acindex{LONG_FILE_NAMES}
23500 Replaced by
23501 @example
23502 AC_SYS_LONG_FILE_NAMES
23503 @end example
23504 @noindent
23505 @xref{AC_SYS_LONG_FILE_NAMES}.
23506 @end defmac
23508 @defmac AC_MAJOR_HEADER
23509 @acindex{MAJOR_HEADER}
23510 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23511 @end defmac
23513 @defmac AC_MEMORY_H
23514 @acindex{MEMORY_H}
23515 @cvindex NEED_MEMORY_H
23516 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23517 defined in @file{memory.h}.  Today it is equivalent to
23518 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23519 your code to depend upon
23520 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
23521 Symbols}.
23522 @end defmac
23524 @defmac AC_MINGW32
23525 @acindex{MINGW32}
23526 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23527 environment and sets @code{MINGW32}.  Don't use this macro, the
23528 dignified means to check the nature of the host is using
23529 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23530 @end defmac
23532 @defmac AC_MINIX
23533 @acindex{MINIX}
23534 @cvindex _MINIX
23535 @cvindex _POSIX_SOURCE
23536 @cvindex _POSIX_1_SOURCE
23537 This macro is a platform-specific subset of
23538 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23539 @end defmac
23541 @defmac AC_MINUS_C_MINUS_O
23542 @acindex{MINUS_C_MINUS_O}
23543 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23544 @end defmac
23546 @defmac AC_MMAP
23547 @acindex{MMAP}
23548 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23549 @end defmac
23551 @defmac AC_MODE_T
23552 @acindex{MODE_T}
23553 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23554 @end defmac
23556 @defmac AC_OBJEXT
23557 @acindex{OBJEXT}
23558 @ovindex OBJEXT
23559 Defined the output variable @code{OBJEXT} based on the output of the
23560 compiler, after .c files have been excluded.  Typically set to @samp{o}
23561 if Posix, @samp{obj} if a DOS variant.
23562 Now the compiler checking macros handle
23563 this automatically.
23564 @end defmac
23566 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23567 @acindex{OBSOLETE}
23568 Make M4 print a message to the standard error output warning that
23569 @var{this-macro-name} is obsolete, and giving the file and line number
23570 where it was called.  @var{this-macro-name} should be the name of the
23571 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23572 it is printed at the end of the warning message; for example, it can be
23573 a suggestion for what to use instead of @var{this-macro-name}.
23575 For instance
23577 @example
23578 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23579 @end example
23581 @noindent
23582 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23583 services to the user (@pxref{AU_DEFUN}).
23584 @end defmac
23586 @defmac AC_OFF_T
23587 @acindex{OFF_T}
23588 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23589 @end defmac
23591 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23592 @acindex{OUTPUT}
23593 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23594 interface is equivalent to:
23596 @example
23597 @group
23598 AC_CONFIG_FILES(@var{file}@dots{})
23599 AC_CONFIG_COMMANDS([default],
23600                    @var{extra-cmds}, @var{init-cmds})
23601 AC_OUTPUT
23602 @end group
23603 @end example
23605 @noindent
23606 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23607 @end defmac
23609 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23610 @acindex{OUTPUT_COMMANDS}
23611 Specify additional shell commands to run at the end of
23612 @file{config.status}, and shell commands to initialize any variables
23613 from @command{configure}.  This macro may be called multiple times.  It is
23614 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23616 Here is an unrealistic example:
23618 @example
23619 fubar=27
23620 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23621                    [fubar=$fubar])
23622 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23623                    [echo init bit])
23624 @end example
23626 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23627 additional key, an important difference is that
23628 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23629 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23630 can safely be given macro calls as arguments:
23632 @example
23633 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23634 @end example
23636 @noindent
23637 Conversely, where one level of quoting was enough for literal strings
23638 with @code{AC_OUTPUT_COMMANDS}, you need two with
23639 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23641 @example
23642 @group
23643 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23644 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23645 @end group
23646 @end example
23647 @end defmac
23649 @defmac AC_PID_T
23650 @acindex{PID_T}
23651 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23652 @end defmac
23654 @defmac AC_PREFIX
23655 @acindex{PREFIX}
23656 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23657 @end defmac
23659 @defmac AC_PROG_CC_STDC
23660 @acindex{PROG_CC_STDC}
23661 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23662 @end defmac
23664 @defmac AC_PROGRAMS_CHECK
23665 @acindex{PROGRAMS_CHECK}
23666 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23667 @end defmac
23669 @defmac AC_PROGRAMS_PATH
23670 @acindex{PROGRAMS_PATH}
23671 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23672 @end defmac
23674 @defmac AC_PROGRAM_CHECK
23675 @acindex{PROGRAM_CHECK}
23676 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23677 @end defmac
23679 @defmac AC_PROGRAM_EGREP
23680 @acindex{PROGRAM_EGREP}
23681 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23682 @end defmac
23684 @defmac AC_PROGRAM_PATH
23685 @acindex{PROGRAM_PATH}
23686 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23687 @end defmac
23689 @defmac AC_REMOTE_TAPE
23690 @acindex{REMOTE_TAPE}
23691 Removed because of limited usefulness.
23692 @end defmac
23694 @defmac AC_RESTARTABLE_SYSCALLS
23695 @acindex{RESTARTABLE_SYSCALLS}
23696 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23697 these days portable programs should use @code{sigaction} with
23698 @code{SA_RESTART} if they want restartable system calls.  They should
23699 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23700 system call is restartable is a dynamic issue, not a configuration-time
23701 issue.
23702 @end defmac
23704 @defmac AC_RETSIGTYPE
23705 @acindex{RETSIGTYPE}
23706 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23707 is obsolete when assuming C89 or better.
23708 @end defmac
23710 @defmac AC_RSH
23711 @acindex{RSH}
23712 Removed because of limited usefulness.
23713 @end defmac
23715 @defmac AC_SCO_INTL
23716 @acindex{SCO_INTL}
23717 @ovindex LIBS
23718 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23719 macro used to do this:
23721 @example
23722 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23723 @end example
23725 @noindent
23726 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23727 @end defmac
23729 @defmac AC_SETVBUF_REVERSED
23730 @acindex{SETVBUF_REVERSED}
23731 Replaced by
23732 @example
23733 AC_FUNC_SETVBUF_REVERSED
23734 @end example
23735 @noindent
23736 @xref{AC_FUNC_SETVBUF_REVERSED}.
23737 @end defmac
23739 @defmac AC_SET_MAKE
23740 @acindex{SET_MAKE}
23741 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23742 @end defmac
23744 @defmac AC_SIZEOF_TYPE
23745 @acindex{SIZEOF_TYPE}
23746 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23747 @end defmac
23749 @defmac AC_SIZE_T
23750 @acindex{SIZE_T}
23751 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23752 @end defmac
23754 @defmac AC_STAT_MACROS_BROKEN
23755 @acindex{STAT_MACROS_BROKEN}
23756 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23757 @end defmac
23759 @defmac AC_STDC_HEADERS
23760 @acindex{STDC_HEADERS}
23761 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
23762 @end defmac
23764 @defmac AC_STRCOLL
23765 @acindex{STRCOLL}
23766 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23767 @end defmac
23769 @defmac AC_STRUCT_ST_BLKSIZE
23770 @acindex{STRUCT_ST_BLKSIZE}
23771 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23772 @cvindex HAVE_ST_BLKSIZE
23773 If @code{struct stat} contains an @code{st_blksize} member, define
23774 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23775 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23776 the future.  This macro is obsoleted, and should be replaced by
23778 @example
23779 AC_CHECK_MEMBERS([struct stat.st_blksize])
23780 @end example
23781 @noindent
23782 @xref{AC_CHECK_MEMBERS}.
23783 @end defmac
23785 @defmac AC_STRUCT_ST_RDEV
23786 @acindex{STRUCT_ST_RDEV}
23787 @cvindex HAVE_ST_RDEV
23788 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23789 If @code{struct stat} contains an @code{st_rdev} member, define
23790 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23791 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23792 in the future.  Actually, even the new macro is obsolete and should be
23793 replaced by:
23794 @example
23795 AC_CHECK_MEMBERS([struct stat.st_rdev])
23796 @end example
23797 @noindent
23798 @xref{AC_CHECK_MEMBERS}.
23799 @end defmac
23801 @defmac AC_ST_BLKSIZE
23802 @acindex{ST_BLKSIZE}
23803 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23804 @end defmac
23806 @defmac AC_ST_BLOCKS
23807 @acindex{ST_BLOCKS}
23808 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
23809 @end defmac
23811 @defmac AC_ST_RDEV
23812 @acindex{ST_RDEV}
23813 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23814 @end defmac
23816 @defmac AC_SYS_RESTARTABLE_SYSCALLS
23817 @acindex{SYS_RESTARTABLE_SYSCALLS}
23818 @cvindex HAVE_RESTARTABLE_SYSCALLS
23819 If the system automatically restarts a system call that is interrupted
23820 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
23821 not check whether system calls are restarted in general---it checks whether a
23822 signal handler installed with @code{signal} (but not @code{sigaction})
23823 causes system calls to be restarted.  It does not check whether system calls
23824 can be restarted when interrupted by signals that have no handler.
23826 These days portable programs should use @code{sigaction} with
23827 @code{SA_RESTART} if they want restartable system calls.  They should
23828 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23829 system call is restartable is a dynamic issue, not a configuration-time
23830 issue.
23831 @end defmac
23833 @defmac AC_SYS_SIGLIST_DECLARED
23834 @acindex{SYS_SIGLIST_DECLARED}
23835 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
23836 name is obsolete, as the same functionality is now achieved via
23837 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
23838 @end defmac
23840 @defmac AC_TEST_CPP
23841 @acindex{TEST_CPP}
23842 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
23843 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
23844 @end defmac
23846 @defmac AC_TEST_PROGRAM
23847 @acindex{TEST_PROGRAM}
23848 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
23849 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
23850 @end defmac
23852 @defmac AC_TIMEZONE
23853 @acindex{TIMEZONE}
23854 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
23855 @end defmac
23857 @defmac AC_TIME_WITH_SYS_TIME
23858 @acindex{TIME_WITH_SYS_TIME}
23859 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
23860 @end defmac
23862 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
23863   @ovar{action-if-true}, @ovar{action-if-false})
23864 @acindex{TRY_COMPILE}
23865 Same as:
23867 @example
23868 AC_COMPILE_IFELSE(
23869   [AC_LANG_PROGRAM([[@var{includes}]],
23870      [[@var{function-body}]])],
23871   [@var{action-if-true}],
23872   [@var{action-if-false}])
23873 @end example
23875 @noindent
23876 @xref{Running the Compiler}.
23878 This macro double quotes both @var{includes} and @var{function-body}.
23880 For C and C++, @var{includes} is any @code{#include} statements needed
23881 by the code in @var{function-body} (@var{includes} is ignored if
23882 the currently selected language is Fortran or Fortran 77).  The compiler
23883 and compilation flags are determined by the current language
23884 (@pxref{Language Choice}).
23885 @end defmac
23887 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
23888 @acindex{TRY_CPP}
23889 Same as:
23891 @example
23892 AC_PREPROC_IFELSE(
23893   [AC_LANG_SOURCE([[@var{input}]])],
23894   [@var{action-if-true}],
23895   [@var{action-if-false}])
23896 @end example
23898 @noindent
23899 @xref{Running the Preprocessor}.
23901 This macro double quotes the @var{input}.
23902 @end defmac
23904 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
23905   @ovar{action-if-true}, @ovar{action-if-false})
23906 @acindex{TRY_LINK}
23907 Same as:
23909 @example
23910 AC_LINK_IFELSE(
23911   [AC_LANG_PROGRAM([[@var{includes}]],
23912      [[@var{function-body}]])],
23913   [@var{action-if-true}],
23914   [@var{action-if-false}])
23915 @end example
23917 @noindent
23918 @xref{Running the Compiler}.
23920 This macro double quotes both @var{includes} and @var{function-body}.
23922 Depending on the current language (@pxref{Language Choice}), create a
23923 test program to see whether a function whose body consists of
23924 @var{function-body} can be compiled and linked.  If the file compiles
23925 and links successfully, run shell commands @var{action-if-found},
23926 otherwise run @var{action-if-not-found}.
23928 This macro double quotes both @var{includes} and @var{function-body}.
23930 For C and C++, @var{includes} is any @code{#include} statements needed
23931 by the code in @var{function-body} (@var{includes} is ignored if
23932 the currently selected language is Fortran or Fortran 77).  The compiler
23933 and compilation flags are determined by the current language
23934 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
23935 @code{LIBS} are used for linking.
23936 @end defmac
23938 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
23939   @ovar{action-if-not-found})
23940 @acindex{TRY_LINK_FUNC}
23941 This macro is equivalent to
23942 @example
23943 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
23944   [@var{action-if-found}], [@var{action-if-not-found}])
23945 @end example
23946 @noindent
23947 @xref{AC_LINK_IFELSE}.
23948 @end defmac
23950 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
23951   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
23952 @acindex{TRY_RUN}
23953 Same as:
23955 @example
23956 AC_RUN_IFELSE(
23957   [AC_LANG_SOURCE([[@var{program}]])],
23958   [@var{action-if-true}],
23959   [@var{action-if-false}],
23960   [@var{action-if-cross-compiling}])
23961 @end example
23963 @noindent
23964 @xref{Runtime}.
23965 @end defmac
23967 @anchor{AC_TYPE_SIGNAL}
23968 @defmac AC_TYPE_SIGNAL
23969 @acindex{TYPE_SIGNAL}
23970 @cvindex RETSIGTYPE
23971 @hdrindex{signal.h}
23972 If @file{signal.h} declares @code{signal} as returning a pointer to a
23973 function returning @code{void}, define @code{RETSIGTYPE} to be
23974 @code{void}; otherwise, define it to be @code{int}.  These days, it is
23975 portable to assume C89, and that signal handlers return @code{void},
23976 without needing to use this macro or @code{RETSIGTYPE}.
23978 When targeting older K&R C, it is possible to define signal handlers as
23979 returning type @code{RETSIGTYPE}, and omit a return statement:
23981 @example
23982 @group
23983 RETSIGTYPE
23984 hup_handler ()
23986 @dots{}
23988 @end group
23989 @end example
23990 @end defmac
23992 @defmac AC_UID_T
23993 @acindex{UID_T}
23994 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23995 @end defmac
23997 @defmac AC_UNISTD_H
23998 @acindex{UNISTD_H}
23999 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
24000 @end defmac
24002 @defmac AC_USG
24003 @acindex{USG}
24004 @cvindex USG
24005 Define @code{USG} if the BSD string functions are defined in
24006 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
24007 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
24008 @end defmac
24010 @defmac AC_UTIME_NULL
24011 @acindex{UTIME_NULL}
24012 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24013 @end defmac
24015 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24016 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24017 If the cache file is inconsistent with the current host, target and
24018 build system types, it used to execute @var{cmd} or print a default
24019 error message.  This is now handled by default.
24020 @end defmac
24022 @defmac AC_VERBOSE (@var{result-description})
24023 @acindex{VERBOSE}
24024 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24025 @end defmac
24027 @defmac AC_VFORK
24028 @acindex{VFORK}
24029 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24030 @end defmac
24032 @defmac AC_VPRINTF
24033 @acindex{VPRINTF}
24034 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24035 @end defmac
24037 @defmac AC_WAIT3
24038 @acindex{WAIT3}
24039 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24040 portable programs should use @code{waitpid}, not @code{wait3}, as
24041 @code{wait3} has been removed from Posix.
24042 @end defmac
24044 @defmac AC_WARN
24045 @acindex{WARN}
24046 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24047 @end defmac
24049 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24050   @ovar{action-if-not-given})
24051 @acindex{WITH}
24052 This is an obsolete version of @code{AC_ARG_WITH} that does not
24053 support providing a help string (@pxref{AC_ARG_WITH}).
24054 @end defmac
24056 @defmac AC_WORDS_BIGENDIAN
24057 @acindex{WORDS_BIGENDIAN}
24058 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24059 @end defmac
24061 @defmac AC_XENIX_DIR
24062 @acindex{XENIX_DIR}
24063 @ovindex LIBS
24064 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24065 Xenix.  Also, if @file{dirent.h} is being checked for, added
24066 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24067 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24068 running XENIX on which you should not depend:
24070 @example
24071 AC_MSG_CHECKING([for Xenix])
24072 AC_EGREP_CPP([yes],
24073 [#if defined M_XENIX && !defined M_UNIX
24074   yes
24075 #endif],
24076              [AC_MSG_RESULT([yes]); XENIX=yes],
24077              [AC_MSG_RESULT([no]); XENIX=])
24078 @end example
24079 @noindent
24080 Don't use this macro, the dignified means to check the nature of the
24081 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24082 @end defmac
24084 @defmac AC_YYTEXT_POINTER
24085 @acindex{YYTEXT_POINTER}
24086 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24087 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24088 @end defmac
24090 @node Autoconf 1
24091 @section Upgrading From Version 1
24092 @cindex Upgrading autoconf
24093 @cindex Autoconf upgrading
24095 Autoconf version 2 is mostly backward compatible with version 1.
24096 However, it introduces better ways to do some things, and doesn't
24097 support some of the ugly things in version 1.  So, depending on how
24098 sophisticated your @file{configure.ac} files are, you might have to do
24099 some manual work in order to upgrade to version 2.  This chapter points
24100 out some problems to watch for when upgrading.  Also, perhaps your
24101 @command{configure} scripts could benefit from some of the new features in
24102 version 2; the changes are summarized in the file @file{NEWS} in the
24103 Autoconf distribution.
24105 @menu
24106 * Changed File Names::          Files you might rename
24107 * Changed Makefiles::           New things to put in @file{Makefile.in}
24108 * Changed Macros::              Macro calls you might replace
24109 * Changed Results::             Changes in how to check test results
24110 * Changed Macro Writing::       Better ways to write your own macros
24111 @end menu
24113 @node Changed File Names
24114 @subsection Changed File Names
24116 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24117 in a particular package's source directory), you must rename it to
24118 @file{acsite.m4}.  @xref{autoconf Invocation}.
24120 If you distribute @file{install.sh} with your package, rename it to
24121 @file{install-sh} so @command{make} builtin rules don't inadvertently
24122 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24123 looks for the script under both names, but it is best to use the new name.
24125 If you were using @file{config.h.top}, @file{config.h.bot}, or
24126 @file{acconfig.h}, you still can, but you have less clutter if you
24127 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24129 @node Changed Makefiles
24130 @subsection Changed Makefiles
24132 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24133 your @file{Makefile.in} files, so they can take advantage of the values
24134 of those variables in the environment when @command{configure} is run.
24135 Doing this isn't necessary, but it's a convenience for users.
24137 Also add @samp{@@configure_input@@} in a comment to each input file for
24138 @code{AC_OUTPUT}, so that the output files contain a comment saying
24139 they were produced by @command{configure}.  Automatically selecting the
24140 right comment syntax for all the kinds of files that people call
24141 @code{AC_OUTPUT} on became too much work.
24143 Add @file{config.log} and @file{config.cache} to the list of files you
24144 remove in @code{distclean} targets.
24146 If you have the following in @file{Makefile.in}:
24148 @example
24149 prefix = /usr/local
24150 exec_prefix = $(prefix)
24151 @end example
24153 @noindent
24154 you must change it to:
24156 @example
24157 prefix = @@prefix@@
24158 exec_prefix = @@exec_prefix@@
24159 @end example
24161 @noindent
24162 The old behavior of replacing those variables without @samp{@@}
24163 characters around them has been removed.
24165 @node Changed Macros
24166 @subsection Changed Macros
24168 Many of the macros were renamed in Autoconf version 2.  You can still
24169 use the old names, but the new ones are clearer, and it's easier to find
24170 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24171 new names for the old macros.  Use the @command{autoupdate} program to
24172 convert your @file{configure.ac} to using the new macro names.
24173 @xref{autoupdate Invocation}.
24175 Some macros have been superseded by similar ones that do the job better,
24176 but are not call-compatible.  If you get warnings about calling obsolete
24177 macros while running @command{autoconf}, you may safely ignore them, but
24178 your @command{configure} script generally works better if you follow
24179 the advice that is printed about what to replace the obsolete macros with.  In
24180 particular, the mechanism for reporting the results of tests has
24181 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24182 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24183 looks better if you switch to @code{AC_MSG_CHECKING} and
24184 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24185 in conjunction with cache variables.  @xref{Caching Results}.
24189 @node Changed Results
24190 @subsection Changed Results
24192 If you were checking the results of previous tests by examining the
24193 shell variable @code{DEFS}, you need to switch to checking the values of
24194 the cache variables for those tests.  @code{DEFS} no longer exists while
24195 @command{configure} is running; it is only created when generating output
24196 files.  This difference from version 1 is because properly quoting the
24197 contents of that variable turned out to be too cumbersome and
24198 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24199 Variable Names}.
24201 For example, here is a @file{configure.ac} fragment written for Autoconf
24202 version 1:
24204 @example
24205 AC_HAVE_FUNCS(syslog)
24206 case "$DEFS" in
24207 *-DHAVE_SYSLOG*) ;;
24208 *) # syslog is not in the default libraries.  See if it's in some other.
24209   saved_LIBS="$LIBS"
24210   for lib in bsd socket inet; do
24211     AC_CHECKING(for syslog in -l$lib)
24212     LIBS="-l$lib $saved_LIBS"
24213     AC_HAVE_FUNCS(syslog)
24214     case "$DEFS" in
24215     *-DHAVE_SYSLOG*) break ;;
24216     *) ;;
24217     esac
24218     LIBS="$saved_LIBS"
24219   done ;;
24220 esac
24221 @end example
24223 Here is a way to write it for version 2:
24225 @example
24226 AC_CHECK_FUNCS([syslog])
24227 if test "x$ac_cv_func_syslog" = xno; then
24228   # syslog is not in the default libraries.  See if it's in some other.
24229   for lib in bsd socket inet; do
24230     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24231       LIBS="-l$lib $LIBS"; break])
24232   done
24234 @end example
24236 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24237 backslashes before quotes, you need to remove them.  It now works
24238 predictably, and does not treat quotes (except back quotes) specially.
24239 @xref{Setting Output Variables}.
24241 All of the Boolean shell variables set by Autoconf macros now use
24242 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24243 though for backward compatibility some use the empty string instead.  If
24244 you were relying on a shell variable being set to something like 1 or
24245 @samp{t} for true, you need to change your tests.
24247 @node Changed Macro Writing
24248 @subsection Changed Macro Writing
24250 When defining your own macros, you should now use @code{AC_DEFUN}
24251 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24252 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24253 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24254 messages on the screen.  There's no actual harm in continuing to use the
24255 older way, but it's less convenient and attractive.  @xref{Macro
24256 Definitions}.
24258 You probably looked at the macros that came with Autoconf as a guide for
24259 how to do things.  It would be a good idea to take a look at the new
24260 versions of them, as the style is somewhat improved and they take
24261 advantage of some new features.
24263 If you were doing tricky things with undocumented Autoconf internals
24264 (macros, variables, diversions), check whether you need to change
24265 anything to account for changes that have been made.  Perhaps you can
24266 even use an officially supported technique in version 2 instead of
24267 kludging.  Or perhaps not.
24269 To speed up your locally written feature tests, add caching to them.
24270 See whether any of your tests are of general enough usefulness to
24271 encapsulate them into macros that you can share.
24274 @node Autoconf 2.13
24275 @section Upgrading From Version 2.13
24276 @cindex Upgrading autoconf
24277 @cindex Autoconf upgrading
24279 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24280 suits this section@enddots{}
24282 @quotation
24283 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24284 However, it introduces better ways to do some things, and doesn't
24285 support some of the ugly things in version 2.13.  So, depending on how
24286 sophisticated your @file{configure.ac} files are, you might have to do
24287 some manual work in order to upgrade to version 2.50.  This chapter
24288 points out some problems to watch for when upgrading.  Also, perhaps
24289 your @command{configure} scripts could benefit from some of the new
24290 features in version 2.50; the changes are summarized in the file
24291 @file{NEWS} in the Autoconf distribution.
24292 @end quotation
24294 @menu
24295 * Changed Quotation::           Broken code which used to work
24296 * New Macros::                  Interaction with foreign macros
24297 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24298 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24299 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24300 @end menu
24302 @node Changed Quotation
24303 @subsection Changed Quotation
24305 The most important changes are invisible to you: the implementation of
24306 most macros have completely changed.  This allowed more factorization of
24307 the code, better error messages, a higher uniformity of the user's
24308 interface etc.  Unfortunately, as a side effect, some construct which
24309 used to (miraculously) work might break starting with Autoconf 2.50.
24310 The most common culprit is bad quotation.
24312 For instance, in the following example, the message is not properly
24313 quoted:
24315 @example
24316 AC_INIT
24317 AC_CHECK_HEADERS(foo.h, ,
24318   AC_MSG_ERROR(cannot find foo.h, bailing out))
24319 AC_OUTPUT
24320 @end example
24322 @noindent
24323 Autoconf 2.13 simply ignores it:
24325 @example
24326 $ @kbd{autoconf-2.13; ./configure --silent}
24327 creating cache ./config.cache
24328 configure: error: cannot find foo.h
24330 @end example
24332 @noindent
24333 while Autoconf 2.50 produces a broken @file{configure}:
24335 @example
24336 $ @kbd{autoconf-2.50; ./configure --silent}
24337 configure: error: cannot find foo.h
24338 ./configure: exit: bad non-numeric arg `bailing'
24339 ./configure: exit: bad non-numeric arg `bailing'
24341 @end example
24343 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24344 too!
24346 @example
24347 AC_INIT([Example], [1.0], [bug-example@@example.org])
24348 AC_CHECK_HEADERS([foo.h], [],
24349   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24350 AC_OUTPUT
24351 @end example
24353 Many many (and many more) Autoconf macros were lacking proper quotation,
24354 including no less than@dots{} @code{AC_DEFUN} itself!
24356 @example
24357 $ @kbd{cat configure.in}
24358 AC_DEFUN([AC_PROG_INSTALL],
24359 [# My own much better version
24361 AC_INIT
24362 AC_PROG_INSTALL
24363 AC_OUTPUT
24364 $ @kbd{autoconf-2.13}
24365 autoconf: Undefined macros:
24366 ***BUG in Autoconf--please report*** AC_FD_MSG
24367 ***BUG in Autoconf--please report*** AC_EPI
24368 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24369 configure.in:5:AC_PROG_INSTALL
24370 $ @kbd{autoconf-2.50}
24372 @end example
24375 @node New Macros
24376 @subsection New Macros
24378 @cindex undefined macro
24379 @cindex @code{_m4_divert_diversion}
24381 While Autoconf was relatively dormant in the late 1990s, Automake
24382 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24383 in 2001, Autoconf provided
24384 versions of these macros, integrated in the @code{AC_} namespace,
24385 instead of @code{AM_}.  But in order to ease the upgrading via
24386 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24388 Unfortunately older versions of Automake (e.g., Automake 1.4)
24389 did not quote the names of these macros.
24390 Therefore, when @command{m4} finds something like
24391 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24392 @code{AM_TYPE_PTRDIFF_T} is
24393 expanded, replaced with its Autoconf definition.
24395 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24396 complains, in its own words:
24398 @example
24399 $ @kbd{cat configure.ac}
24400 AC_INIT([Example], [1.0], [bug-example@@example.org])
24401 AM_TYPE_PTRDIFF_T
24402 $ @kbd{aclocal-1.4}
24403 $ @kbd{autoconf}
24404 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24405 aclocal.m4:17: the top level
24406 autom4te: m4 failed with exit status: 1
24408 @end example
24410 Modern versions of Automake no longer define most of these
24411 macros, and properly quote the names of the remaining macros.
24412 If you must use an old Automake, do not depend upon macros from Automake
24413 as it is simply not its job
24414 to provide macros (but the one it requires itself):
24416 @example
24417 $ @kbd{cat configure.ac}
24418 AC_INIT([Example], [1.0], [bug-example@@example.org])
24419 AM_TYPE_PTRDIFF_T
24420 $ @kbd{rm aclocal.m4}
24421 $ @kbd{autoupdate}
24422 autoupdate: `configure.ac' is updated
24423 $ @kbd{cat configure.ac}
24424 AC_INIT([Example], [1.0], [bug-example@@example.org])
24425 AC_CHECK_TYPES([ptrdiff_t])
24426 $ @kbd{aclocal-1.4}
24427 $ @kbd{autoconf}
24429 @end example
24432 @node Hosts and Cross-Compilation
24433 @subsection Hosts and Cross-Compilation
24434 @cindex Cross compilation
24436 Based on the experience of compiler writers, and after long public
24437 debates, many aspects of the cross-compilation chain have changed:
24439 @itemize @minus
24440 @item
24441 the relationship between the build, host, and target architecture types,
24443 @item
24444 the command line interface for specifying them to @command{configure},
24446 @item
24447 the variables defined in @command{configure},
24449 @item
24450 the enabling of cross-compilation mode.
24451 @end itemize
24453 @sp 1
24455 The relationship between build, host, and target have been cleaned up:
24456 the chain of default is now simply: target defaults to host, host to
24457 build, and build to the result of @command{config.guess}.  Nevertheless,
24458 in order to ease the transition from 2.13 to 2.50, the following
24459 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24460 be completely disabled in a couple of releases (we cannot keep it, as it
24461 proves to cause more problems than it cures).
24463 They all default to the result of running @command{config.guess}, unless
24464 you specify either @option{--build} or @option{--host}.  In this case,
24465 the default becomes the system type you specified.  If you specify both,
24466 and they're different, @command{configure} enters cross compilation
24467 mode, so it doesn't run any tests that require execution.
24469 Hint: if you mean to override the result of @command{config.guess},
24470 prefer @option{--build} over @option{--host}.
24472 @sp 1
24474 For backward compatibility, @command{configure} accepts a system
24475 type as an option by itself.  Such an option overrides the
24476 defaults for build, host, and target system types.  The following
24477 configure statement configures a cross toolchain that runs on
24478 NetBSD/alpha but generates code for GNU Hurd/sparc,
24479 which is also the build platform.
24481 @example
24482 ./configure --host=alpha-netbsd sparc-gnu
24483 @end example
24485 @sp 1
24487 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24488 and @code{target} had a different semantics before and after the
24489 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24490 @option{--build} is strictly copied into @code{build_alias}, and is left
24491 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24492 set to the canonicalized build type.  To ease the transition, before,
24493 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24494 rely on this broken feature.
24496 For consistency with the backward compatibility scheme exposed above,
24497 when @option{--host} is specified but @option{--build} isn't, the build
24498 system is assumed to be the same as @option{--host}, and
24499 @samp{build_alias} is set to that value.  Eventually, this
24500 historically incorrect behavior will go away.
24502 @sp 1
24504 The former scheme to enable cross-compilation proved to cause more harm
24505 than good, in particular, it used to be triggered too easily, leaving
24506 regular end users puzzled in front of cryptic error messages.
24507 @command{configure} could even enter cross-compilation mode only
24508 because the compiler was not functional.  This is mainly because
24509 @command{configure} used to try to detect cross-compilation, instead of
24510 waiting for an explicit flag from the user.
24512 Now, @command{configure} enters cross-compilation mode if and only if
24513 @option{--host} is passed.
24515 That's the short documentation.  To ease the transition between 2.13 and
24516 its successors, a more complicated scheme is implemented.  @emph{Do not
24517 rely on the following}, as it will be removed in the near future.
24519 If you specify @option{--host}, but not @option{--build}, when
24520 @command{configure} performs the first compiler test it tries to run
24521 an executable produced by the compiler.  If the execution fails, it
24522 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24523 the compiler test is performed, it may be too late to modify the
24524 build-system type: other tests may have already been performed.
24525 Therefore, whenever you specify @option{--host}, be sure to specify
24526 @option{--build} too.
24528 @example
24529 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24530 @end example
24532 @noindent
24533 enters cross-compilation mode.  The former interface, which
24534 consisted in setting the compiler to a cross-compiler without informing
24535 @command{configure} is obsolete.  For instance, @command{configure}
24536 fails if it can't run the code generated by the specified compiler if you
24537 configure as follows:
24539 @example
24540 ./configure CC=m68k-coff-gcc
24541 @end example
24544 @node AC_LIBOBJ vs LIBOBJS
24545 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24547 Up to Autoconf 2.13, the replacement of functions was triggered via the
24548 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24549 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24550 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24552 This change is mandated by the unification of the GNU Build System
24553 components.  In particular, the various fragile techniques used to parse
24554 a @file{configure.ac} are all replaced with the use of traces.  As a
24555 consequence, any action must be traceable, which obsoletes critical
24556 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24557 and it can even be handled gracefully (read, ``without your having to
24558 change something'').
24560 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24561 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24563 @sp 1
24565 As for function replacement, the fix is immediate: use
24566 @code{AC_LIBOBJ}.  For instance:
24568 @example
24569 LIBOBJS="$LIBOBJS fnmatch.o"
24570 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24571 @end example
24573 @noindent
24574 should be replaced with:
24576 @example
24577 AC_LIBOBJ([fnmatch])
24578 AC_LIBOBJ([malloc])
24579 @end example
24581 @sp 1
24583 @ovindex LIBOBJDIR
24584 When used with Automake 1.10 or newer, a suitable value for
24585 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24586 can be referenced from any @file{Makefile.am}.  Even without Automake,
24587 arranging for @code{LIBOBJDIR} to be set correctly enables
24588 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24589 The @code{LIBOBJDIR} feature is experimental.
24592 @node AC_ACT_IFELSE vs AC_TRY_ACT
24593 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24594 @c the anchor keeps the old node name, to try to avoid breaking links
24595 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24597 @acindex{@var{ACT}_IFELSE}
24598 @acindex{TRY_@var{ACT}}
24599 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24600 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24601 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24602 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24603 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24604 @code{AC_TRY_RUN}.  The motivations where:
24605 @itemize @minus
24606 @item
24607 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24608 quoting their arguments;
24610 @item
24611 the combinatoric explosion is solved by decomposing on the one hand the
24612 generation of sources, and on the other hand executing the program;
24614 @item
24615 this scheme helps supporting more languages than plain C and C++.
24616 @end itemize
24618 In addition to the change of syntax, the philosophy has changed too:
24619 while emphasis was put on speed at the expense of accuracy, today's
24620 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24621 expense of speed.
24624 As a perfect example of what is @emph{not} to be done, here is how to
24625 find out whether a header file contains a particular declaration, such
24626 as a typedef, a structure, a structure member, or a function.  Use
24627 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24628 header file; on some systems the symbol might be defined in another
24629 header file that the file you are checking includes.
24631 As a (bad) example, here is how you should not check for C preprocessor
24632 symbols, either defined by header files or predefined by the C
24633 preprocessor: using @code{AC_EGREP_CPP}:
24635 @example
24636 @group
24637 AC_EGREP_CPP(yes,
24638 [#ifdef _AIX
24639   yes
24640 #endif
24641 ], is_aix=yes, is_aix=no)
24642 @end group
24643 @end example
24645 The above example, properly written would (i) use
24646 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24648 @example
24649 @group
24650 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24651 [[#ifndef _AIX
24652  error: This isn't AIX!
24653 #endif
24654 ]])],
24655                    [is_aix=yes],
24656                    [is_aix=no])
24657 @end group
24658 @end example
24661 @c ============================= Generating Test Suites with Autotest
24663 @node Using Autotest
24664 @chapter Generating Test Suites with Autotest
24666 @cindex Autotest
24668 @display
24669 @strong{N.B.: This section describes a feature which is still
24670 stabilizing.  Although we believe that Autotest is useful as-is, this
24671 documentation describes an interface which might change in the future:
24672 do not depend upon Autotest without subscribing to the Autoconf mailing
24673 lists.}
24674 @end display
24676 It is paradoxical that portable projects depend on nonportable tools
24677 to run their test suite.  Autoconf by itself is the paragon of this
24678 problem: although it aims at perfectly portability, up to 2.13 its
24679 test suite was using DejaGNU, a rich and complex testing
24680 framework, but which is far from being standard on Posix systems.
24681 Worse yet, it was likely to be missing on the most fragile platforms,
24682 the very platforms that are most likely to torture Autoconf and
24683 exhibit deficiencies.
24685 To circumvent this problem, many package maintainers have developed their
24686 own testing framework, based on simple shell scripts whose sole outputs
24687 are exit status values describing whether the test succeeded.  Most of
24688 these tests share common patterns, and this can result in lots of
24689 duplicated code and tedious maintenance.
24691 Following exactly the same reasoning that yielded to the inception of
24692 Autoconf, Autotest provides a test suite generation framework, based on
24693 M4 macros building a portable shell script.  The suite itself is
24694 equipped with automatic logging and tracing facilities which greatly
24695 diminish the interaction with bug reporters, and simple timing reports.
24697 Autoconf itself has been using Autotest for years, and we do attest that
24698 it has considerably improved the strength of the test suite and the
24699 quality of bug reports.  Other projects are known to use some generation
24700 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
24701 them with different needs, and this usage has validated Autotest as a general
24702 testing framework.
24704 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24705 interactive tool testing, which is probably its main limitation.
24707 @menu
24708 * Using an Autotest Test Suite::  Autotest and the user
24709 * Writing Testsuites::          Autotest macros
24710 * testsuite Invocation::        Running @command{testsuite} scripts
24711 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24712 @end menu
24714 @node Using an Autotest Test Suite
24715 @section Using an Autotest Test Suite
24717 @menu
24718 * testsuite Scripts::           The concepts of Autotest
24719 * Autotest Logs::               Their contents
24720 @end menu
24722 @node testsuite Scripts
24723 @subsection @command{testsuite} Scripts
24725 @cindex @command{testsuite}
24727 Generating testing or validation suites using Autotest is rather easy.
24728 The whole validation suite is held in a file to be processed through
24729 @command{autom4te}, itself using GNU M4 under the hood, to
24730 produce a stand-alone Bourne shell script which then gets distributed.
24731 Neither @command{autom4te} nor GNU M4 are needed at
24732 the installer's end.
24734 @cindex test group
24735 Each test of the validation suite should be part of some test group.  A
24736 @dfn{test group} is a sequence of interwoven tests that ought to be
24737 executed together, usually because one test in the group creates data
24738 files that a later test in the same group needs to read.  Complex test
24739 groups make later debugging more tedious.  It is much better to
24740 keep only a few tests per test group.  Ideally there is only one test
24741 per test group.
24743 For all but the simplest packages, some file such as @file{testsuite.at}
24744 does not fully hold all test sources, as these are often easier to
24745 maintain in separate files.  Each of these separate files holds a single
24746 test group, or a sequence of test groups all addressing some common
24747 functionality in the package.  In such cases, @file{testsuite.at}
24748 merely initializes the validation suite, and sometimes does elementary
24749 health checking, before listing include statements for all other test
24750 files.  The special file @file{package.m4}, containing the
24751 identification of the package, is automatically included if found.
24753 A convenient alternative consists in moving all the global issues
24754 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24755 invocation) into the file @code{local.at}, and making
24756 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24757 suites.  In such case, generating the whole test suite or pieces of it
24758 is only a matter of choosing the @command{autom4te} command line
24759 arguments.
24761 The validation scripts that Autotest produces are by convention called
24762 @command{testsuite}.  When run, @command{testsuite} executes each test
24763 group in turn, producing only one summary line per test to say if that
24764 particular test succeeded or failed.  At end of all tests, summarizing
24765 counters get printed.  One debugging directory is left for each test
24766 group which failed, if any: such directories are named
24767 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24768 the test group, and they include:
24770 @itemize @bullet
24771 @item a debugging script named @file{run} which reruns the test in
24772 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24773 of debugging scripts has the purpose of easing the chase for bugs.
24775 @item all the files created with @code{AT_DATA}
24777 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24779 @item a log of the run, named @file{testsuite.log}
24780 @end itemize
24782 In the ideal situation, none of the tests fail, and consequently no
24783 debugging directory is left behind for validation.
24785 It often happens in practice that individual tests in the validation
24786 suite need to get information coming out of the configuration process.
24787 Some of this information, common for all validation suites, is provided
24788 through the file @file{atconfig}, automatically created by
24789 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
24790 testing environment specifically needs, you might prepare an optional
24791 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24792 The configuration process produces @file{atconfig} and @file{atlocal}
24793 out of these two input files, and these two produced files are
24794 automatically read by the @file{testsuite} script.
24796 Here is a diagram showing the relationship between files.
24798 @noindent
24799 Files used in preparing a software package for distribution:
24801 @example
24802                 [package.m4] -->.
24803                                  \
24804 subfile-1.at ->.  [local.at] ---->+
24805     ...         \                  \
24806 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
24807     ...         /
24808 subfile-n.at ->'
24809 @end example
24811 @noindent
24812 Files used in configuring a software package:
24814 @example
24815                                      .--> atconfig
24816                                     /
24817 [atlocal.in] -->  config.status* --<
24818                                     \
24819                                      `--> [atlocal]
24820 @end example
24822 @noindent
24823 Files created during test suite execution:
24825 @example
24826 atconfig -->.                    .--> testsuite.log
24827              \                  /
24828               >-- testsuite* --<
24829              /                  \
24830 [atlocal] ->'                    `--> [testsuite.dir]
24831 @end example
24834 @node Autotest Logs
24835 @subsection Autotest Logs
24837 When run, the test suite creates a log file named after itself, e.g., a
24838 test suite named @command{testsuite} creates @file{testsuite.log}.  It
24839 contains a lot of information, usually more than maintainers actually
24840 need, but therefore most of the time it contains all that is needed:
24842 @table @asis
24843 @item command line arguments
24844 A bad but unfortunately widespread habit consists of
24845 setting environment variables before the command, such as in
24846 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
24847 know this change, hence (i) it cannot report it to you, and (ii)
24848 it cannot preserve the value of @code{CC} for subsequent runs.
24849 Autoconf faced exactly the same problem, and solved it by asking
24850 users to pass the variable definitions as command line arguments.
24851 Autotest requires this rule, too, but has no means to enforce it; the log
24852 then contains a trace of the variables that were changed by the user.
24854 @item @file{ChangeLog} excerpts
24855 The topmost lines of all the @file{ChangeLog} files found in the source
24856 hierarchy.  This is especially useful when bugs are reported against
24857 development versions of the package, since the version string does not
24858 provide sufficient information to know the exact state of the sources
24859 the user compiled.  Of course, this relies on the use of a
24860 @file{ChangeLog}.
24862 @item build machine
24863 Running a test suite in a cross-compile environment is not an easy task,
24864 since it would mean having the test suite run on a machine @var{build},
24865 while running programs on a machine @var{host}.  It is much simpler to
24866 run both the test suite and the programs on @var{host}, but then, from
24867 the point of view of the test suite, there remains a single environment,
24868 @var{host} = @var{build}.  The log contains relevant information on the
24869 state of the @var{build} machine, including some important environment
24870 variables.
24871 @c FIXME: How about having an M4sh macro to say `hey, log the value
24872 @c of `@dots{}'?  This would help both Autoconf and Autotest.
24874 @item tested programs
24875 The absolute file name and answers to @option{--version} of the tested
24876 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
24878 @item configuration log
24879 The contents of @file{config.log}, as created by @command{configure},
24880 are appended.  It contains the configuration flags and a detailed report
24881 on the configuration itself.
24882 @end table
24885 @node Writing Testsuites
24886 @section Writing @file{testsuite.at}
24888 The @file{testsuite.at} is a Bourne shell script making use of special
24889 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
24890 its beginning followed by one call to @code{m4_include} per source file
24891 for tests.  Each such included file, or the remainder of
24892 @file{testsuite.at} if include files are not used, contain a sequence of
24893 test groups.  Each test group begins with a call to @code{AT_SETUP},
24894 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
24895 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
24896 groups can be categorized by a call to @code{AT_BANNER}.
24898 All of the public Autotest macros have all-uppercase names in the
24899 namespace @samp{^AT_} to prevent them from accidentally conflicting with
24900 other text; Autoconf also reserves the namespace @samp{^_AT_} for
24901 internal macros.  All shell variables used in the testsuite for internal
24902 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
24903 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
24904 makes use of the file system namespace @samp{^at-}.
24906 Since Autoconf is built on top of M4sugar (@pxref{Programming in
24907 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
24908 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
24909 @emph{should not use} the namespace of a package that does not own the
24910 macro or shell code you are writing.
24912 @defmac AT_INIT (@ovar{name})
24913 @atindex{INIT}
24914 @c FIXME: Not clear, plus duplication of the information.
24915 Initialize Autotest.  Giving a @var{name} to the test suite is
24916 encouraged if your package includes several test suites.  Before this
24917 macro is called, @code{AT_PACKAGE_STRING} and
24918 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
24919 information about the testsuite to the user.  Typically, these macros
24920 are provided by a file @file{package.m4} built by @command{make}
24921 (@pxref{Making testsuite Scripts}), in order to inherit the package
24922 name, version, and bug reporting address from @file{configure.ac}.
24923 @end defmac
24925 @defmac AT_COPYRIGHT (@var{copyright-notice})
24926 @atindex{COPYRIGHT}
24927 @cindex Copyright Notice
24928 State that, in addition to the Free Software Foundation's copyright on
24929 the Autotest macros, parts of your test suite are covered by
24930 @var{copyright-notice}.
24932 The @var{copyright-notice} shows up in both the head of
24933 @command{testsuite} and in @samp{testsuite --version}.
24934 @end defmac
24936 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
24937   @ovar{action-if-given}, @ovar{action-if-not-given})
24938 @atindex{ARG_OPTION}
24939 @vrindex at_arg_@var{option}
24940 Accept options from the space-separated list @var{options}, a list that
24941 has leading dashes removed from the options.  Long options will be
24942 prefixed with @samp{--}, single-character options with @samp{-}.  The
24943 first word in this list is the primary @var{option}, any others are
24944 assumed to be short-hand aliases.  The variable associated with it
24945 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
24946 with underscores.
24948 If the user passes @option{--@var{option}} to the @command{testsuite},
24949 the variable will be set to @samp{:}.  If the user does not pass the
24950 option, or passes @option{--no-@var{option}}, then the variable will be
24951 set to @samp{false}.
24953 @vrindex at_optarg
24954 @vrindex at_optarg_@var{option}
24955 @var{action-if-given} is run each time the option is encountered; here,
24956 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
24957 appropriate.  @code{at_optarg} is actually just a copy of
24958 @code{at_arg_@var{option}}.
24960 @var{action-if-not-given} will be run once after option parsing is
24961 complete and if no option from @var{options} was used.
24963 @var{help-text} is added to the end of the list of options shown in
24964 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24966 It is recommended that you use a package-specific prefix to @var{options}
24967 names in order to avoid clashes with future Autotest built-in options.
24968 @end defmac
24970 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
24971   @ovar{action-if-given}, @ovar{action-if-not-given})
24972 @atindex{ARG_OPTION_ARG}
24973 @vrindex at_arg_@var{option}
24974 Accept options with arguments from the space-separated list
24975 @var{options}, a list that has leading dashes removed from the options.
24976 Long options will be prefixed with @samp{--}, single-character options
24977 with @samp{-}.  The first word in this list is the primary @var{option},
24978 any others are assumed to be short-hand aliases.  The variable associated
24979 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24980 replaced with underscores.
24982 If the user passes @option{--@var{option}=@var{arg}} or
24983 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
24984 variable will be set to @samp{@var{arg}}.
24986 @vrindex at_optarg
24987 @var{action-if-given} is run each time the option is encountered; here,
24988 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24989 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24991 @var{action-if-not-given} will be run once after option parsing is
24992 complete and if no option from @var{options} was used.
24994 @var{help-text} is added to the end of the list of options shown in
24995 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24997 It is recommended that you use a package-specific prefix to @var{options}
24998 names in order to avoid clashes with future Autotest built-in options.
24999 @end defmac
25001 @defmac AT_COLOR_TESTS
25002 @atindex{COLOR_TESTS}
25003 Enable colored test results by default when the output is connected to
25004 a terminal.
25005 @end defmac
25007 @defmac AT_TESTED (@var{executables})
25008 @atindex{TESTED}
25009 Log the file name and answer to @option{--version} of each program in
25010 space-separated list @var{executables}.  Several invocations register
25011 new executables, in other words, don't fear registering one program
25012 several times.
25014 Autotest test suites rely on @env{PATH} to find the tested program.
25015 This avoids the need to generate absolute names of the various tools, and
25016 makes it possible to test installed programs.  Therefore, knowing which
25017 programs are being exercised is crucial to understanding problems in
25018 the test suite itself, or its occasional misuses.  It is a good idea to
25019 also subscribe foreign programs you depend upon, to avoid incompatible
25020 diagnostics.
25021 @end defmac
25023 @sp 1
25025 @defmac AT_BANNER (@var{test-category-name})
25026 @atindex{BANNER}
25027 This macro identifies the start of a category of related test groups.
25028 When the resulting @file{testsuite} is invoked with more than one test
25029 group to run, its output will include a banner containing
25030 @var{test-category-name} prior to any tests run from that category.  The
25031 banner should be no more than about 40 or 50 characters.  A blank banner
25032 indicates uncategorized tests; an empty line will be inserted after
25033 tests from an earlier category, effectively ending that category.
25034 @end defmac
25036 @defmac AT_SETUP (@var{test-group-name})
25037 @atindex{SETUP}
25038 This macro starts a group of related tests, all to be executed in the
25039 same subshell.  It accepts a single argument, which holds a few words
25040 (no more than about 30 or 40 characters) quickly describing the purpose
25041 of the test group being started.  @var{test-group-name} must not expand
25042 to unbalanced quotes, although quadrigraphs can be used.
25043 @end defmac
25045 @defmac AT_KEYWORDS (@var{keywords})
25046 @atindex{KEYWORDS}
25047 Associate the space-separated list of @var{keywords} to the enclosing
25048 test group.  This makes it possible to run ``slices'' of the test suite.
25049 For instance, if some of your test groups exercise some @samp{foo}
25050 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25051 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25052 @var{test-group-name} of the test group is automatically recorded to
25053 @code{AT_KEYWORDS}.
25055 Several invocations within a test group accumulate new keywords.  In
25056 other words, don't fear registering the same keyword several times in a
25057 test group.
25058 @end defmac
25060 @defmac AT_CAPTURE_FILE (@var{file})
25061 @atindex{CAPTURE_FILE}
25062 If the current test group fails, log the contents of @var{file}.
25063 Several identical calls within one test group have no additional effect.
25064 @end defmac
25066 @defmac AT_FAIL_IF (@var{shell-condition})
25067 @atindex{FAIL_IF}
25068 Make the test group fail and skip the rest of its execution, if
25069 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25070 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25071 will be executed and may still cause the test group to be skipped.
25072 You can instantiate this macro many times from within the same test group.
25074 You should use this macro only for very simple failure conditions.  If the
25075 @var{shell-condition} could emit any kind of output you should instead
25076 use @command{AT_CHECK} like
25077 @example
25078 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25079 @end example
25080 @noindent
25081 so that such output is properly recorded in the @file{testsuite.log}
25082 file.
25083 @end defmac
25085 @defmac AT_SKIP_IF (@var{shell-condition})
25086 @atindex{SKIP_IF}
25087 Determine whether the test should be skipped because it requires
25088 features that are unsupported on the machine under test.
25089 @var{shell-condition} is a shell expression such as a @code{test}
25090 command.  Tests before @command{AT_SKIP_IF} will be executed
25091 and may still cause the test group to fail.  You can instantiate this
25092 macro many times from within the same test group.
25094 You should use this macro only for very simple skip conditions.  If the
25095 @var{shell-condition} could emit any kind of output you should instead
25096 use @command{AT_CHECK} like
25097 @example
25098 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25099 @end example
25100 @noindent
25101 so that such output is properly recorded in the @file{testsuite.log}
25102 file.
25103 @end defmac
25105 @defmac AT_XFAIL_IF (@var{shell-condition})
25106 @atindex{XFAIL_IF}
25107 Determine whether the test is expected to fail because it is a known
25108 bug (for unsupported features, you should skip the test).
25109 @var{shell-condition} is a shell expression such as a @code{test}
25110 command; you can instantiate this macro many times from within the
25111 same test group, and one of the conditions is enough to turn
25112 the test into an expected failure.
25113 @end defmac
25115 @defmac AT_CLEANUP
25116 @atindex{CLEANUP}
25117 End the current test group.
25118 @end defmac
25120 @sp 1
25122 @defmac AT_DATA (@var{file}, @var{contents})
25123 @atindex{DATA}
25124 Initialize an input data @var{file} with given @var{contents}.  Of
25125 course, the @var{contents} have to be properly quoted between square
25126 brackets to protect against included commas or spurious M4
25127 expansion.  @var{contents} must be empty or end with a newline.
25128 @var{file} must
25129 be a single shell word that expands into a single file name.
25130 @end defmac
25132 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25133   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25134 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25135   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25136 @atindex{CHECK}
25137 @atindex{CHECK_UNQUOTED}
25138 @vrindex at_status
25139 Execute a test by performing given shell @var{commands} in a subshell.
25140 @var{commands} is output as-is, so shell expansions are honored.  These
25141 commands should normally exit with @var{status}, while producing expected
25142 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25143 unexpected status 77, then the rest of the test group is skipped.  If
25144 @var{commands} exit with unexpected status 99, then the test group is
25145 immediately failed.  Otherwise, if this test fails, run shell commands
25146 @var{run-if-fail} or, if this test passes, run shell commands
25147 @var{run-if-pass}, both inside the current shell execution environment.
25148 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25149 @var{commands} is available in the @code{at_status} shell variable.
25151 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25153 If @var{status} is the literal @samp{ignore}, then the corresponding
25154 exit status is not checked, except for the special cases of 77 (skip)
25155 and 99 (hard failure).  The existence of hard failures allows one to
25156 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25157 feature has not yet been implemented, but to still distinguish between
25158 gracefully handling the missing feature and dumping core.  A hard
25159 failure also inhibits post-test actions in @var{run-if-fail}.
25161 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25162 literals in the following table, then the test treats the output
25163 according to the rules of that literal.  Otherwise, the value of the
25164 parameter is treated as text that must exactly match the output given by
25165 @var{commands} on standard output and standard error (including an empty
25166 parameter for no output); any differences are captured in the testsuite
25167 log and the test is failed (unless an unexpected exit status of 77
25168 skipped the test instead).  The difference between @code{AT_CHECK} and
25169 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25170 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25171 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25172 @var{stderr} arguments; if the text includes a trailing newline, this
25173 would be the same as if it were specified via an unquoted
25174 here-document.  (However, there is no difference in the interpretation
25175 of @var{commands}).
25177 @table @samp
25178 @item ignore
25179 The content of the output is ignored, but still captured in the test
25180 group log (if the testsuite is run with option @option{-v}, the test
25181 group log is displayed as the test is run; if the test group later
25182 fails, the test group log is also copied into the overall testsuite
25183 log).  This action is valid for both @var{stdout} and @var{stderr}.
25185 @item ignore-nolog
25186 The content of the output is ignored, and nothing is captured in the log
25187 files.  If @var{commands} are likely to produce binary output (including
25188 long lines) or large amounts of output, then logging the output can make
25189 it harder to locate details related to subsequent tests within the
25190 group, and could potentially corrupt terminal display of a user running
25191 @command{testsuite -v}.
25193 @item stdout
25194 For the @var{stdout} parameter, capture the content of standard output
25195 to both the file @file{stdout} and the test group log.  Subsequent
25196 commands in the test group can then post-process the file.  This action
25197 is often used when it is desired to use @command{grep} to look for a
25198 substring in the output, or when the output must be post-processed to
25199 normalize error messages into a common form.
25201 @item stderr
25202 Like @samp{stdout}, except that it only works for the @var{stderr}
25203 parameter, and the standard error capture file will be named
25204 @file{stderr}.
25206 @item stdout-nolog
25207 @itemx stderr-nolog
25208 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25209 not duplicated into the test group log.  This action is particularly
25210 useful for an intermediate check that produces large amounts of data,
25211 which will be followed by another check that filters down to the
25212 relevant data, as it makes it easier to locate details in the log.
25214 @item expout
25215 For the @var{stdout} parameter, compare standard output contents with
25216 the previously created file @file{expout}, and list any differences in
25217 the testsuite log.
25219 @item experr
25220 Like @samp{expout}, except that it only works for the @var{stderr}
25221 parameter, and the standard error contents are compared with
25222 @file{experr}.
25223 @end table
25224 @end defmac
25226 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25227   @ovar{run-if-fail}, @ovar{run-if-pass})
25228 @atindex{CHECK_EUNIT}
25229 Initialize and execute an Erlang module named @var{module} that performs
25230 tests following the @var{test-spec} EUnit test specification.
25231 @var{test-spec} must be a valid EUnit test specification, as defined in
25232 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25233 Reference Manual}.  @var{erlflags} are optional command-line options
25234 passed to the Erlang interpreter to execute the test Erlang module.
25235 Typically, @var{erlflags} defines at least the paths to directories
25236 containing the compiled Erlang modules under test, as @samp{-pa path1
25237 path2 ...}.
25239 For example, the unit tests associated with Erlang module @samp{testme},
25240 which compiled code is in subdirectory @file{src}, can be performed
25241 with:
25243 @example
25244 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25245                [-pa "$@{abs_top_builddir@}/src"])
25246 @end example
25248 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25250 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25251 must be defined as the path of the Erlang interpreter, the path of the
25252 Erlang compiler, and the command-line flags to pass to the compiler,
25253 respectively.  Those variables should be configured in
25254 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25255 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25256 variables are automatically defined in the testsuite.  If @code{ERL} or
25257 @code{ERLC} is not defined, the test group is skipped.
25259 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25260 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25261 an invalid EUnit test specification, the test group fails.  Otherwise,
25262 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25263 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25264 executed and the test group fails.
25266 Only the generated test Erlang module is automatically compiled and
25267 executed.  If @var{test-spec} involves testing other Erlang modules,
25268 e.g. module @samp{testme} in the example above, those modules must be
25269 already compiled.
25271 If the testsuite is run in verbose mode, with option @option{--verbose},
25272 EUnit is also run in verbose mode to output more details about
25273 individual unit tests.
25274 @end defmac
25277 @node testsuite Invocation
25278 @section Running @command{testsuite} Scripts
25279 @cindex @command{testsuite}
25281 Autotest test suites support the following options:
25283 @table @option
25284 @item --help
25285 @itemx -h
25286 Display the list of options and exit successfully.
25288 @item --version
25289 @itemx -V
25290 Display the version of the test suite and exit successfully.
25292 @item --directory=@var{dir}
25293 @itemx -C @var{dir}
25294 Change the current directory to @var{dir} before creating any files.
25295 Useful for running the testsuite in a subdirectory from a top-level
25296 Makefile.
25298 @item --jobs@r{[}=@var{n}@r{]}
25299 @itemx -j@ovar{n}
25300 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25301 run all given tests in parallel.  Note that there should be no space
25302 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25303 the separate arguments @option{-j} and @option{@var{number}}, see below.
25305 In parallel mode, the standard input device of the testsuite script is
25306 not available to commands inside a test group.  Furthermore, banner
25307 lines are not printed, and the summary line for each test group is
25308 output after the test group completes.  Summary lines may appear
25309 unordered.  If verbose and trace output are enabled (see below), they
25310 may appear intermixed from concurrently running tests.
25312 Parallel mode requires the @command{mkfifo} command to work, and will be
25313 silently disabled otherwise.
25315 @item --clean
25316 @itemx -c
25317 Remove all the files the test suite might have created and exit.  Meant
25318 for @code{clean} Make targets.
25320 @item --list
25321 @itemx -l
25322 List all the tests (or only the selection), including their possible
25323 keywords.
25324 @end table
25326 @sp 1
25328 By default all tests are performed (or described with @option{--list})
25329 silently in the default environment, but the environment, set of tests,
25330 and verbosity level can be tuned:
25332 @table @samp
25333 @item @var{variable}=@var{value}
25334 Set the environment @var{variable} to @var{value}.  Use this rather
25335 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25336 different environment.
25338 @cindex @code{AUTOTEST_PATH}
25339 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25340 to @env{PATH}.  Relative directory names (not starting with
25341 @samp{/}) are considered to be relative to the top level of the
25342 package being built.  All directories are made absolute, first
25343 starting from the top level @emph{build} tree, then from the
25344 @emph{source} tree.  For instance @samp{./testsuite
25345 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25346 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25347 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25348 @env{PATH}.
25350 @item @var{number}
25351 @itemx @var{number}-@var{number}
25352 @itemx @var{number}-
25353 @itemx -@var{number}
25354 Add the corresponding test groups, with obvious semantics, to the
25355 selection.
25357 @item --keywords=@var{keywords}
25358 @itemx -k @var{keywords}
25359 Add to the selection the test groups with title or keywords (arguments
25360 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25361 of the comma separated list @var{keywords}, case-insensitively.  Use
25362 @samp{!} immediately before the keyword to invert the selection for this
25363 keyword.  By default, the keywords match whole words; enclose them in
25364 @samp{.*} to also match parts of words.
25366 For example, running
25368 @example
25369 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25370 @end example
25372 @noindent
25373 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25374 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25375 etc.), while
25377 @example
25378 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25379 @end example
25381 @noindent
25382 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25383 containing @samp{FUNC}.
25385 @item --errexit
25386 @itemx -e
25387 If any test fails, immediately abort testing.  This implies
25388 @option{--debug}: post test group clean up, and top-level logging
25389 are inhibited.  This option is meant for the full test
25390 suite, it is not really useful for generated debugging scripts.
25391 If the testsuite is run in parallel mode using @option{--jobs},
25392 then concurrently running tests will finish before exiting.
25394 @item --verbose
25395 @itemx -v
25396 Force more verbosity in the detailed output of what is being done.  This
25397 is the default for debugging scripts.
25399 @item --color
25400 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25401 Enable colored test results.  Without an argument, or with @samp{always},
25402 test results will be colored.  With @samp{never}, color mode is turned
25403 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25404 the testsuite author, or the argument @samp{auto} is given, then test
25405 results are colored if standard output is connected to a terminal.
25407 @item --debug
25408 @itemx -d
25409 Do not remove the files after a test group was performed---but they are
25410 still removed @emph{before}, therefore using this option is sane when
25411 running several test groups.  Create debugging scripts.  Do not
25412 overwrite the top-level
25413 log (in order to preserve a supposedly existing full log file).  This is
25414 the default for debugging scripts, but it can also be useful to debug
25415 the testsuite itself.
25417 @item --recheck
25418 Add to the selection all test groups that failed or passed unexpectedly
25419 during the last non-debugging test run.
25421 @item --trace
25422 @itemx -x
25423 Trigger shell tracing of the test groups.
25424 @end table
25426 Besides these options accepted by every Autotest testsuite, the
25427 testsuite author might have added package-specific options
25428 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25429 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25430 the package documentation for details.
25433 @node Making testsuite Scripts
25434 @section Making @command{testsuite} Scripts
25436 For putting Autotest into movement, you need some configuration and
25437 makefile machinery.  We recommend, at least if your package uses deep or
25438 shallow hierarchies, that you use @file{tests/} as the name of the
25439 directory holding all your tests and their makefile.  Here is a
25440 check list of things to do, followed by an example, taking into
25441 consideration whether you are also using Automake.
25443 @itemize @minus
25445 @item
25446 @cindex @file{package.m4}
25447 @atindex{PACKAGE_STRING}
25448 @atindex{PACKAGE_BUGREPORT}
25449 @atindex{PACKAGE_NAME}
25450 @atindex{PACKAGE_TARNAME}
25451 @atindex{PACKAGE_VERSION}
25452 @atindex{PACKAGE_URL}
25453 Make sure to create the file @file{package.m4}, which defines the
25454 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25455 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25456 address to which bug reports should be sent.  For sake of completeness,
25457 we suggest that you also define @code{AT_PACKAGE_NAME},
25458 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25459 @code{AT_PACKAGE_URL}.
25460 @xref{Initializing configure}, for a description of these variables.
25461 Be sure to distribute @file{package.m4} and to put it into the source
25462 hierarchy: the test suite ought to be shipped!  See below for an example.
25464 @item
25465 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25467 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25468 @acindex{CONFIG_TESTDIR}
25469 An Autotest test suite is to be configured in @var{directory}.  This
25470 macro causes @file{@var{directory}/atconfig} to be created by
25471 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25472 @var{test-path} (@pxref{testsuite Invocation}).
25473 @end defmac
25475 @item
25476 Still within @file{configure.ac}, as appropriate, ensure that some
25477 @code{AC_CONFIG_FILES} command includes substitution for
25478 @file{tests/atlocal}.
25480 @item
25481 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25482 variable to be set.
25484 @item
25485 The appropriate @file{Makefile} should be modified so the validation in
25486 your package is triggered by @samp{make check}.
25487 @end itemize
25489 The following example demonstrates the above checklist, first by
25490 assuming that you are using Automake (see below for tweaks to make to
25491 get the same results without Automake).  Begin by adding the following
25492 lines to your @file{configure.ac}:
25494 @example
25495 # Initialize the test suite.
25496 AC_CONFIG_TESTDIR([tests])
25497 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25498 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25499 @end example
25501 Next, add the following lines to your @file{tests/Makefile.am}, in order
25502 to link @samp{make check} with a validation suite.
25504 @example
25505 # The `:;' works around a Bash 3.2 bug when the output is not writable.
25506 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25507         :;@{ \
25508           echo '# Signature of the current package.' && \
25509           echo 'm4_define([AT_PACKAGE_NAME],' && \
25510           echo '  [$(PACKAGE_NAME)])' && \
25511           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25512           echo '  [$(PACKAGE_TARNAME)])' && \
25513           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25514           echo '  [$(PACKAGE_VERSION)])' && \
25515           echo 'm4_define([AT_PACKAGE_STRING],' && \
25516           echo '  [$(PACKAGE_STRING)])' && \
25517           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25518           echo '  [$(PACKAGE_BUGREPORT)])'; \
25519           echo 'm4_define([AT_PACKAGE_URL],' && \
25520           echo '  [$(PACKAGE_URL)])'; \
25521         @} >'$(srcdir)/package.m4'
25523 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25524 TESTSUITE = $(srcdir)/testsuite
25526 check-local: atconfig atlocal $(TESTSUITE)
25527         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25529 installcheck-local: atconfig atlocal $(TESTSUITE)
25530         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25531           $(TESTSUITEFLAGS)
25533 clean-local:
25534         test ! -f '$(TESTSUITE)' || \
25535          $(SHELL) '$(TESTSUITE)' --clean
25537 AUTOTEST = $(AUTOM4TE) --language=autotest
25538 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25539         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25540         mv $@@.tmp $@@
25541 @end example
25543 Note that the built testsuite is distributed; this is necessary because
25544 users might not have Autoconf installed, and thus would not be able to
25545 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25546 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25547 provide the user with
25548 a nicer error message if they modify a source file to the testsuite, and
25549 accidentally trigger the rebuild rules.
25551 You might want to list explicitly the dependencies, i.e., the list of
25552 the files @file{testsuite.at} includes.
25554 If you don't use Automake, you should make the following tweaks.  In
25555 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25556 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
25557 welcome to also try using the @command{missing} script from the Automake
25558 project instead of @command{false}, to try to get a nicer error message
25559 when the user modifies prerequisites but did not have Autoconf
25560 installed, but at that point you may be better off using Automake.
25561 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25562 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
25563 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25564 distributed, as well as adding the following additional lines to prepare
25565 the set of needed Makefile variables:
25567 @example
25568 subdir = tests
25569 PACKAGE_NAME = @@PACKAGE_NAME@@
25570 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25571 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25572 PACKAGE_STRING = @@PACKAGE_STRING@@
25573 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25574 PACKAGE_URL = @@PACKAGE_URL@@
25575 AUTOM4TE = @@AUTOM4TE@@
25577 atconfig: $(top_builddir)/config.status
25578         cd $(top_builddir) && \
25579            $(SHELL) ./config.status $(subdir)/$@@
25581 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25582         cd $(top_builddir) && \
25583            $(SHELL) ./config.status $(subdir)/$@@
25584 @end example
25586 Using the above example (with or without Automake), and assuming you
25587 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25588 makefile, you can now fine-tune test suite execution at runtime by
25589 altering this variable, for example:
25591 @example
25592 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25593 @end example
25597 @c =============================== Frequent Autoconf Questions, with answers
25599 @node FAQ
25600 @chapter Frequent Autoconf Questions, with answers
25602 Several questions about Autoconf come up occasionally.  Here some of them
25603 are addressed.
25605 @menu
25606 * Distributing::                Distributing @command{configure} scripts
25607 * Why GNU M4::                  Why not use the standard M4?
25608 * Bootstrapping::               Autoconf and GNU M4 require each other?
25609 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25610 * Defining Directories::        Passing @code{datadir} to program
25611 * Autom4te Cache::              What is it?  Can I remove it?
25612 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25613 * Expanded Before Required::    Expanded Before Required
25614 * Debugging::                   Debugging @command{configure} scripts
25615 @end menu
25617 @node Distributing
25618 @section Distributing @command{configure} Scripts
25619 @cindex License
25621 @display
25622 What are the restrictions on distributing @command{configure}
25623 scripts that Autoconf generates?  How does that affect my
25624 programs that use them?
25625 @end display
25627 There are no restrictions on how the configuration scripts that Autoconf
25628 produces may be distributed or used.  In Autoconf version 1, they were
25629 covered by the GNU General Public License.  We still encourage
25630 software authors to distribute their work under terms like those of the
25631 GPL, but doing so is not required to use Autoconf.
25633 Of the other files that might be used with @command{configure},
25634 @file{config.h.in} is under whatever copyright you use for your
25635 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25636 exception to the GPL when they are used with an Autoconf-generated
25637 @command{configure} script, which permits you to distribute them under the
25638 same terms as the rest of your package.  @file{install-sh} is from the X
25639 Consortium and is not copyrighted.
25641 @node Why GNU M4
25642 @section Why Require GNU M4?
25644 @display
25645 Why does Autoconf require GNU M4?
25646 @end display
25648 Many M4 implementations have hard-coded limitations on the size and
25649 number of macros that Autoconf exceeds.  They also lack several
25650 builtin macros that it would be difficult to get along without in a
25651 sophisticated application like Autoconf, including:
25653 @example
25654 m4_builtin
25655 m4_indir
25656 m4_bpatsubst
25657 __file__
25658 __line__
25659 @end example
25661 Autoconf requires version 1.4.6 or later of GNU M4.
25663 Since only software maintainers need to use Autoconf, and since GNU
25664 M4 is simple to configure and install, it seems reasonable to require
25665 GNU M4 to be installed also.  Many maintainers of GNU and
25666 other free software already have most of the GNU utilities
25667 installed, since they prefer them.
25669 @node Bootstrapping
25670 @section How Can I Bootstrap?
25671 @cindex Bootstrap
25673 @display
25674 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25675 @command{configure} script, how do I bootstrap?  It seems like a chicken
25676 and egg problem!
25677 @end display
25679 This is a misunderstanding.  Although GNU M4 does come with a
25680 @command{configure} script produced by Autoconf, Autoconf is not required
25681 in order to run the script and install GNU M4.  Autoconf is only
25682 required if you want to change the M4 @command{configure} script, which few
25683 people have to do (mainly its maintainer).
25685 @node Why Not Imake
25686 @section Why Not Imake?
25687 @cindex Imake
25689 @display
25690 Why not use Imake instead of @command{configure} scripts?
25691 @end display
25693 Several people have written addressing this question, so
25694 adaptations of their explanations are included here.
25696 The following answer is based on one written by Richard Pixley:
25698 @quotation
25699 Autoconf generated scripts frequently work on machines that it has
25700 never been set up to handle before.  That is, it does a good job of
25701 inferring a configuration for a new system.  Imake cannot do this.
25703 Imake uses a common database of host specific data.  For X11, this makes
25704 sense because the distribution is made as a collection of tools, by one
25705 central authority who has control over the database.
25707 GNU tools are not released this way.  Each GNU tool has a
25708 maintainer; these maintainers are scattered across the world.  Using a
25709 common database would be a maintenance nightmare.  Autoconf may appear
25710 to be this kind of database, but in fact it is not.  Instead of listing
25711 host dependencies, it lists program requirements.
25713 If you view the GNU suite as a collection of native tools, then the
25714 problems are similar.  But the GNU development tools can be
25715 configured as cross tools in almost any host+target permutation.  All of
25716 these configurations can be installed concurrently.  They can even be
25717 configured to share host independent files across hosts.  Imake doesn't
25718 address these issues.
25720 Imake templates are a form of standardization.  The GNU coding
25721 standards address the same issues without necessarily imposing the same
25722 restrictions.
25723 @end quotation
25726 Here is some further explanation, written by Per Bothner:
25728 @quotation
25729 One of the advantages of Imake is that it is easy to generate large
25730 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25731 However, @code{cpp} is not programmable: it has limited conditional
25732 facilities, and no looping.  And @code{cpp} cannot inspect its
25733 environment.
25735 All of these problems are solved by using @code{sh} instead of
25736 @code{cpp}.  The shell is fully programmable, has macro substitution,
25737 can execute (or source) other shell scripts, and can inspect its
25738 environment.
25739 @end quotation
25742 Paul Eggert elaborates more:
25744 @quotation
25745 With Autoconf, installers need not assume that Imake itself is already
25746 installed and working well.  This may not seem like much of an advantage
25747 to people who are accustomed to Imake.  But on many hosts Imake is not
25748 installed or the default installation is not working well, and requiring
25749 Imake to install a package hinders the acceptance of that package on
25750 those hosts.  For example, the Imake template and configuration files
25751 might not be installed properly on a host, or the Imake build procedure
25752 might wrongly assume that all source files are in one big directory
25753 tree, or the Imake configuration might assume one compiler whereas the
25754 package or the installer needs to use another, or there might be a
25755 version mismatch between the Imake expected by the package and the Imake
25756 supported by the host.  These problems are much rarer with Autoconf,
25757 where each package comes with its own independent configuration
25758 processor.
25760 Also, Imake often suffers from unexpected interactions between
25761 @command{make} and the installer's C preprocessor.  The fundamental problem
25762 here is that the C preprocessor was designed to preprocess C programs,
25763 not makefiles.  This is much less of a problem with Autoconf,
25764 which uses the general-purpose preprocessor M4, and where the
25765 package's author (rather than the installer) does the preprocessing in a
25766 standard way.
25767 @end quotation
25770 Finally, Mark Eichin notes:
25772 @quotation
25773 Imake isn't all that extensible, either.  In order to add new features to
25774 Imake, you need to provide your own project template, and duplicate most
25775 of the features of the existing one.  This means that for a sophisticated
25776 project, using the vendor-provided Imake templates fails to provide any
25777 leverage---since they don't cover anything that your own project needs
25778 (unless it is an X11 program).
25780 On the other side, though:
25782 The one advantage that Imake has over @command{configure}:
25783 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
25784 than @file{Makefile.in} files.  There is a fix to this, however---at least
25785 for the Kerberos V5 tree, we've modified things to call in common
25786 @file{post.in} and @file{pre.in} makefile fragments for the
25787 entire tree.  This means that a lot of common things don't have to be
25788 duplicated, even though they normally are in @command{configure} setups.
25789 @end quotation
25792 @node Defining Directories
25793 @section How Do I @code{#define} Installation Directories?
25795 @display
25796 My program needs library files, installed in @code{datadir} and
25797 similar.  If I use
25799 @example
25800 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
25801   [Define to the read-only architecture-independent
25802    data directory.])
25803 @end example
25805 @noindent
25806 I get
25808 @example
25809 #define DATADIR "$@{prefix@}/share"
25810 @end example
25811 @end display
25813 As already explained, this behavior is on purpose, mandated by the
25814 GNU Coding Standards, see @ref{Installation Directory
25815 Variables}.  There are several means to achieve a similar goal:
25817 @itemize @minus
25818 @item
25819 Do not use @code{AC_DEFINE} but use your makefile to pass the
25820 actual value of @code{datadir} via compilation flags.
25821 @xref{Installation Directory Variables}, for the details.
25823 @item
25824 This solution can be simplified when compiling a program: you may either
25825 extend the @code{CPPFLAGS}:
25827 @example
25828 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
25829 @end example
25831 @noindent
25832 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
25834 @example
25835 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
25836 @end example
25838 @noindent
25839 Alternatively, create a dedicated header file:
25841 @example
25842 DISTCLEANFILES = myprog-paths.h
25843 myprog-paths.h: Makefile
25844         echo '#define DATADIR "$(datadir)"' >$@@
25845 @end example
25847 @noindent
25848 The gnulib module @samp{configmake} provides such a header with all the
25849 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
25850 Gnulib}.
25852 @item
25853 Use @code{AC_DEFINE} but have @command{configure} compute the literal
25854 value of @code{datadir} and others.  Many people have wrapped macros to
25855 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
25856 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
25857 Archive}.
25859 This solution does not conform to the GNU Coding Standards.
25861 @item
25862 Note that all the previous solutions hard wire the absolute name of
25863 these directories in the executables, which is not a good property.  You
25864 may try to compute the names relative to @code{prefix}, and try to
25865 find @code{prefix} at runtime, this way your package is relocatable.
25866 @end itemize
25869 @node Autom4te Cache
25870 @section What is @file{autom4te.cache}?
25872 @display
25873 What is this directory @file{autom4te.cache}?  Can I safely remove it?
25874 @end display
25876 In the GNU Build System, @file{configure.ac} plays a central
25877 role and is read by many tools: @command{autoconf} to create
25878 @file{configure}, @command{autoheader} to create @file{config.h.in},
25879 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
25880 check the completeness of @file{configure.ac}, @command{autoreconf} to
25881 check the GNU Build System components that are used.  To
25882 ``read @file{configure.ac}'' actually means to compile it with M4,
25883 which can be a long process for complex @file{configure.ac}.
25885 This is why all these tools, instead of running directly M4, invoke
25886 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
25887 a specific demand, stores additional information in
25888 @file{autom4te.cache} for future runs.  For instance, if you run
25889 @command{autoconf}, behind the scenes, @command{autom4te} also
25890 stores information for the other tools, so that when you invoke
25891 @command{autoheader} or @command{automake} etc., reprocessing
25892 @file{configure.ac} is not needed.  The speed up is frequently 30%,
25893 and is increasing with the size of @file{configure.ac}.
25895 But it is and remains being simply a cache: you can safely remove it.
25897 @sp 1
25899 @display
25900 Can I permanently get rid of it?
25901 @end display
25903 The creation of this cache can be disabled from
25904 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
25905 details.  You should be aware that disabling the cache slows down the
25906 Autoconf test suite by 40%.  The more GNU Build System
25907 components are used, the more the cache is useful; for instance
25908 running @samp{autoreconf -f} on the Core Utilities is twice slower without
25909 the cache @emph{although @option{--force} implies that the cache is
25910 not fully exploited}, and eight times slower than without
25911 @option{--force}.
25914 @node Present But Cannot Be Compiled
25915 @section Header Present But Cannot Be Compiled
25917 The most important guideline to bear in mind when checking for
25918 features is to mimic as much as possible the intended use.
25919 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
25920 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
25921 the preprocessor, instead of the compiler, to check for headers.  As a
25922 result, incompatibilities between headers went unnoticed during
25923 configuration, and maintainers finally had to deal with this issue
25924 elsewhere.
25926 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
25927 checks are performed, and @command{configure} complains loudly if the
25928 compiler and the preprocessor do not agree.  However, only the compiler
25929 result is considered.
25931 Consider the following example:
25933 @smallexample
25934 $ @kbd{cat number.h}
25935 typedef int number;
25936 $ @kbd{cat pi.h}
25937 const number pi = 3;
25938 $ @kbd{cat configure.ac}
25939 AC_INIT([Example], [1.0], [bug-example@@example.org])
25940 AC_CHECK_HEADERS([pi.h])
25941 $ @kbd{autoconf -Wall}
25942 $ @kbd{./configure}
25943 checking for gcc... gcc
25944 checking for C compiler default output file name... a.out
25945 checking whether the C compiler works... yes
25946 checking whether we are cross compiling... no
25947 checking for suffix of executables...
25948 checking for suffix of object files... o
25949 checking whether we are using the GNU C compiler... yes
25950 checking whether gcc accepts -g... yes
25951 checking for gcc option to accept ISO C89... none needed
25952 checking how to run the C preprocessor... gcc -E
25953 checking for grep that handles long lines and -e... grep
25954 checking for egrep... grep -E
25955 checking for ANSI C header files... yes
25956 checking for sys/types.h... yes
25957 checking for sys/stat.h... yes
25958 checking for stdlib.h... yes
25959 checking for string.h... yes
25960 checking for memory.h... yes
25961 checking for strings.h... yes
25962 checking for inttypes.h... yes
25963 checking for stdint.h... yes
25964 checking for unistd.h... yes
25965 checking pi.h usability... no
25966 checking pi.h presence... yes
25967 configure: WARNING: pi.h: present but cannot be compiled
25968 configure: WARNING: pi.h:     check for missing prerequisite headers?
25969 configure: WARNING: pi.h: see the Autoconf documentation
25970 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
25971 configure: WARNING: pi.h: proceeding with the compiler's result
25972 configure: WARNING:     ## -------------------------------------- ##
25973 configure: WARNING:     ## Report this to bug-example@@example.org ##
25974 configure: WARNING:     ## -------------------------------------- ##
25975 checking for pi.h... yes
25976 @end smallexample
25978 @noindent
25979 The proper way the handle this case is using the fourth argument
25980 (@pxref{Generic Headers}):
25982 @example
25983 $ @kbd{cat configure.ac}
25984 AC_INIT([Example], [1.0], [bug-example@@example.org])
25985 AC_CHECK_HEADERS([number.h pi.h], [], [],
25986 [[#ifdef HAVE_NUMBER_H
25987 # include <number.h>
25988 #endif
25990 $ @kbd{autoconf -Wall}
25991 $ @kbd{./configure}
25992 checking for gcc... gcc
25993 checking for C compiler default output... a.out
25994 checking whether the C compiler works... yes
25995 checking whether we are cross compiling... no
25996 checking for suffix of executables...
25997 checking for suffix of object files... o
25998 checking whether we are using the GNU C compiler... yes
25999 checking whether gcc accepts -g... yes
26000 checking for gcc option to accept ANSI C... none needed
26001 checking for number.h... yes
26002 checking for pi.h... yes
26003 @end example
26005 See @ref{Particular Headers}, for a list of headers with their
26006 prerequisites.
26008 @node Expanded Before Required
26009 @section Expanded Before Required
26011 @cindex expanded before required
26012 Older versions of Autoconf silently built files with incorrect ordering
26013 between dependent macros if an outer macro first expanded, then later
26014 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26015 situation no longer generates out-of-order code, but results in
26016 duplicate output and a syntax warning:
26018 @example
26019 $ @kbd{cat configure.ac}
26020 @result{}AC_DEFUN([TESTA], [[echo in A
26021 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26022 @result{}SEEN_A=:]])
26023 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26024 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26025 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26026 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26027 @result{}TESTA
26028 @result{}TESTC])
26029 @result{}AC_INIT
26030 @result{}OUTER
26031 @result{}AC_OUTPUT
26032 $ @kbd{autoconf}
26033 @result{}configure.ac:11: warning: AC_REQUIRE:
26034 @result{} `TESTA' was expanded before it was required
26035 @result{}configure.ac:4: TESTB is expanded from...
26036 @result{}configure.ac:6: TESTC is expanded from...
26037 @result{}configure.ac:7: OUTER is expanded from...
26038 @result{}configure.ac:11: the top level
26039 @end example
26041 @noindent
26042 To avoid this warning, decide what purpose the macro in question serves.
26043 If it only needs to be expanded once (for example, if it provides
26044 initialization text used by later macros), then the simplest fix is to
26045 change the macro to be declared with @code{AC_DEFUN_ONCE}
26046 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26047 newer.  A more portable fix is to change all
26048 instances of direct calls to instead go through @code{AC_REQUIRE}
26049 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26050 by arguments or by the current definition of other macros in the m4
26051 environment, then the macro should always be directly expanded instead
26052 of required.
26054 For another case study, consider this example trimmed down from an
26055 actual package.  Originally, the package contained shell code and
26056 multiple macro invocations at the top level of @file{configure.ac}:
26058 @example
26059 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26060 foobar=
26061 AC_PROG_CC
26063 @end example
26065 @noindent
26066 but that was getting complex, so the author wanted to offload some of
26067 the text into a new macro in another file included via
26068 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26069 macro:
26071 @example
26072 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26073 AC_DEFUN([BAR], [
26074 foobar=
26075 AC_PROG_CC
26079 @end example
26081 @noindent
26082 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26083 before the single compiler check, as the author intended.  But with
26084 Autoconf 2.64, this issues the ``expanded before it was required''
26085 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26086 check, one before @samp{foobar=}, and one after.  To understand why this
26087 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26088 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26089 the documented semantics of @code{AC_REQUIRE}, this means that
26090 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26091 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26092 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26093 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26094 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26095 autoconf.  In other words, the author was unknowingly relying on a bug
26096 exploit to get the desired results, and that exploit broke once the bug
26097 was fixed.
26099 So, what recourse does the author have, to restore their intended
26100 semantics of setting @samp{foobar=} prior to a single compiler check,
26101 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26102 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26103 there is always the possibility of using the lower-level
26104 @code{m4_define}:
26106 @example
26107 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26108 m4_define([BAR], [
26109 foobar=
26110 AC_PROG_CC
26114 @end example
26116 @noindent
26117 This works great if everything is in the same file.  However, it does
26118 not help in the case where the author wants to have @command{aclocal}
26119 find the definition of @code{BAR} from its own file, since
26120 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26121 better fix is to recognize that if @code{BAR} also uses
26122 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26123 to a subsequent require.  Then, by creating yet another helper macro,
26124 the author can once again guarantee a single invocation of
26125 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26126 author can also use @code{AC_BEFORE} to make sure no other macro
26127 appearing before @code{BAR} has triggered an unwanted expansion of
26128 @code{AC_PROG_CC}.
26130 @example
26131 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26132 AC_DEFUN([BEFORE_CC], [
26133 foobar=
26135 AC_DEFUN([BAR], [
26136 AC_BEFORE([$0], [AC_PROG_CC])dnl
26137 AC_REQUIRE([BEFORE_CC])dnl
26138 AC_REQUIRE([AC_PROG_CC])dnl
26142 @end example
26145 @node Debugging
26146 @section Debugging @command{configure} scripts
26148 While in general, @command{configure} scripts generated by Autoconf
26149 strive to be fairly portable to various systems, compilers, shells, and
26150 other tools, it may still be necessary to debug a failing test, broken
26151 script or makefile, or fix or override an incomplete, faulty, or erroneous
26152 test, especially during macro development.  Failures can occur at all levels,
26153 in M4 syntax or semantics, shell script issues, or due to bugs in the
26154 test or the tools invoked by @command{configure}.  Together with the
26155 rather arcane error message that @command{m4} and @command{make} may
26156 produce when their input contains syntax errors, this can make debugging
26157 rather painful.
26159 Nevertheless, here is a list of hints and strategies that may help:
26161 @itemize
26162 @item
26163 When @command{autoconf} fails, common causes for error include:
26165 @itemize
26166 @item
26167 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26168 Parentheses}),
26170 @item under- or overquoted macro arguments (@pxref{Autoconf
26171 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26172 Macros}),
26174 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26175 Language}).
26176 @end itemize
26178 Typically, it helps to go back to the last working version of the input
26179 and compare the differences for each of these errors.  Another
26180 possibility is to sprinkle pairs of @code{m4_traceon} and
26181 @code{m4_traceoff} judiciously in the code, either without a parameter
26182 or listing some macro names and watch @command{m4} expand its input
26183 verbosely (@pxref{Debugging via autom4te}).
26185 @item
26186 Sometimes @command{autoconf} succeeds but the generated
26187 @command{configure} script has invalid shell syntax.  You can detect this
26188 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26189 If this command fails, the same tips apply, as if @command{autoconf} had
26190 failed.
26192 @item
26193 Debugging @command{configure} script execution may be done by sprinkling
26194 pairs of @code{set -x} and @code{set +x} into the shell script before
26195 and after the region that contains a bug.  Running the whole script with
26196 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26197 @var{shell} may work, but produces lots of output.  Here, it can help to
26198 search for markers like @samp{checking for} a particular test in the
26199 @var{log-file}.
26201 @item
26202 Alternatively, you might use a shell with debugging capabilities like
26203 @uref{http://bashdb.sourceforge.net/, bashdb}.
26205 @item
26206 When @command{configure} tests produce invalid results for your system,
26207 it may be necessary to override them:
26209 @itemize
26210 @item
26211 For programs, tools or libraries variables, preprocessor, compiler, or
26212 linker flags, it is often sufficient to override them at @command{make}
26213 run time with some care (@pxref{Macros and Submakes}).  Since this
26214 normally won't cause @command{configure} to be run again with these
26215 changed settings, it may fail if the changed variable would have caused
26216 different test results from @command{configure}, so this may work only
26217 for simple differences.
26219 @item
26220 Most tests which produce their result in a substituted variable allow to
26221 override the test by setting the variable on the @command{configure}
26222 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26223 @pxref{Particular Systems}).
26225 @item
26226 Many tests store their result in a cache variable (@pxref{Caching
26227 Results}).  This lets you override them either on the
26228 @command{configure} command line as above, or through a primed cache or
26229 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26230 cache variable is documented with a test macro or may be inferred from
26231 @ref{Cache Variable Names}; the precise semantics of undocumented
26232 variables are often internal details, subject to change.
26233 @end itemize
26235 @item
26236 Alternatively, @command{configure} may produce invalid results because
26237 of uncaught programming errors, in your package or in an upstream
26238 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26239 library with a specified function, always check @file{config.log}.  This
26240 will reveal the exact error that produced the failing result: the
26241 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26242 @end itemize
26244 Conversely, as macro author, you can make it easier for users of your
26245 macro:
26247 @itemize
26248 @item
26249 by minimizing dependencies between tests and between test results as far
26250 as possible,
26252 @item
26253 by using @command{make} variables to factorize and allow
26254 override of settings at @command{make} run time,
26256 @item
26257 by honoring the GNU Coding Standards and not overriding flags
26258 reserved for the user except temporarily during @command{configure}
26259 tests,
26261 @item
26262 by not requiring users of your macro to use the cache variables.
26263 Instead, expose the result of the test via @var{run-if-true} and
26264 @var{run-if-false} parameters.  If the result is not a boolean,
26265 then provide it through documented shell variables.
26266 @end itemize
26269 @c ===================================================== History of Autoconf.
26271 @node History
26272 @chapter History of Autoconf
26273 @cindex History of autoconf
26275 @emph{This chapter was written by the original author, David MacKenzie.}
26277 You may be wondering, Why was Autoconf originally written?  How did it
26278 get into its present form?  (Why does it look like gorilla spit?)  If
26279 you're not wondering, then this chapter contains no information useful
26280 to you, and you might as well skip it.  If you @emph{are} wondering,
26281 then let there be light@enddots{}
26283 @menu
26284 * Genesis::                     Prehistory and naming of @command{configure}
26285 * Exodus::                      The plagues of M4 and Perl
26286 * Leviticus::                   The priestly code of portability arrives
26287 * Numbers::                     Growth and contributors
26288 * Deuteronomy::                 Approaching the promises of easy configuration
26289 @end menu
26291 @node Genesis
26292 @section Genesis
26294 In June 1991 I was maintaining many of the GNU utilities for the
26295 Free Software Foundation.  As they were ported to more platforms and
26296 more programs were added, the number of @option{-D} options that users
26297 had to select in the makefile (around 20) became burdensome.
26298 Especially for me---I had to test each new release on a bunch of
26299 different systems.  So I wrote a little shell script to guess some of
26300 the correct settings for the fileutils package, and released it as part
26301 of fileutils 2.0.  That @command{configure} script worked well enough that
26302 the next month I adapted it (by hand) to create similar @command{configure}
26303 scripts for several other GNU utilities packages.  Brian Berliner
26304 also adapted one of my scripts for his CVS revision control system.
26306 Later that summer, I learned that Richard Stallman and Richard Pixley
26307 were developing similar scripts to use in the GNU compiler tools;
26308 so I adapted my @command{configure} scripts to support their evolving
26309 interface: using the file name @file{Makefile.in} as the templates;
26310 adding @samp{+srcdir}, the first option (of many); and creating
26311 @file{config.status} files.
26313 @node Exodus
26314 @section Exodus
26316 As I got feedback from users, I incorporated many improvements, using
26317 Emacs to search and replace, cut and paste, similar changes in each of
26318 the scripts.  As I adapted more GNU utilities packages to use
26319 @command{configure} scripts, updating them all by hand became impractical.
26320 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26321 mail saying that the @command{configure} scripts were great, and asking if
26322 I had a tool for generating them that I could send him.  No, I thought,
26323 but I should!  So I started to work out how to generate them.  And the
26324 journey from the slavery of hand-written @command{configure} scripts to the
26325 abundance and ease of Autoconf began.
26327 Cygnus @command{configure}, which was being developed at around that time,
26328 is table driven; it is meant to deal mainly with a discrete number of
26329 system types with a small number of mainly unguessable features (such as
26330 details of the object file format).  The automatic configuration system
26331 that Brian Fox had developed for Bash takes a similar approach.  For
26332 general use, it seems to me a hopeless cause to try to maintain an
26333 up-to-date database of which features each variant of each operating
26334 system has.  It's easier and more reliable to check for most features on
26335 the fly---especially on hybrid systems that people have hacked on
26336 locally or that have patches from vendors installed.
26338 I considered using an architecture similar to that of Cygnus
26339 @command{configure}, where there is a single @command{configure} script that
26340 reads pieces of @file{configure.in} when run.  But I didn't want to have
26341 to distribute all of the feature tests with every package, so I settled
26342 on having a different @command{configure} made from each
26343 @file{configure.in} by a preprocessor.  That approach also offered more
26344 control and flexibility.
26346 I looked briefly into using the Metaconfig package, by Larry Wall,
26347 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26348 reasons.  The @command{Configure} scripts it produces are interactive,
26349 which I find quite inconvenient; I didn't like the ways it checked for
26350 some features (such as library functions); I didn't know that it was
26351 still being maintained, and the @command{Configure} scripts I had
26352 seen didn't work on many modern systems (such as System V R4 and NeXT);
26353 it wasn't flexible in what it could do in response to a feature's
26354 presence or absence; I found it confusing to learn; and it was too big
26355 and complex for my needs (I didn't realize then how much Autoconf would
26356 eventually have to grow).
26358 I considered using Perl to generate my style of @command{configure}
26359 scripts, but decided that M4 was better suited to the job of simple
26360 textual substitutions: it gets in the way less, because output is
26361 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26362 the GNU extensions to M4.)  Also, some of my friends at the
26363 University of Maryland had recently been putting M4 front ends on
26364 several programs, including @code{tvtwm}, and I was interested in trying
26365 out a new language.
26367 @node Leviticus
26368 @section Leviticus
26370 Since my @command{configure} scripts determine the system's capabilities
26371 automatically, with no interactive user intervention, I decided to call
26372 the program that generates them Autoconfig.  But with a version number
26373 tacked on, that name would be too long for old Unix file systems,
26374 so I shortened it to Autoconf.
26376 In the fall of 1991 I called together a group of fellow questers after
26377 the Holy Grail of portability (er, that is, alpha testers) to give me
26378 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26379 and continued to add features and improve the techniques used in the
26380 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26381 with the idea of making an Autoconf shell script to run M4
26382 and check for unresolved macro calls; Richard Pixley, who suggested
26383 running the compiler instead of searching the file system to find
26384 include files and symbols, for more accurate results; Karl Berry, who
26385 got Autoconf to configure @TeX{} and added the macro index to the
26386 documentation; and Ian Lance Taylor, who added support for creating a C
26387 header file as an alternative to putting @option{-D} options in a
26388 makefile, so he could use Autoconf for his UUCP package.
26389 The alpha testers cheerfully adjusted their files again and again as the
26390 names and calling conventions of the Autoconf macros changed from
26391 release to release.  They all contributed many specific checks, great
26392 ideas, and bug fixes.
26394 @node Numbers
26395 @section Numbers
26397 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26398 and converted many GNU packages to use it.  I was surprised by how
26399 positive the reaction to it was.  More people started using it than I
26400 could keep track of, including people working on software that wasn't
26401 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26402 Autoconf continued to improve rapidly, as many people using the
26403 @command{configure} scripts reported problems they encountered.
26405 Autoconf turned out to be a good torture test for M4 implementations.
26406 Unix M4 started to dump core because of the length of the
26407 macros that Autoconf defined, and several bugs showed up in GNU
26408 M4 as well.  Eventually, we realized that we needed to use some
26409 features that only GNU M4 has.  4.3BSD M4, in
26410 particular, has an impoverished set of builtin macros; the System V
26411 version is better, but still doesn't provide everything we need.
26413 More development occurred as people put Autoconf under more stresses
26414 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26415 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26416 invalid arguments.  Jim Blandy bravely coerced it into configuring
26417 GNU Emacs, laying the groundwork for several later improvements.
26418 Roland McGrath got it to configure the GNU C Library, wrote the
26419 @command{autoheader} script to automate the creation of C header file
26420 templates, and added a @option{--verbose} option to @command{configure}.
26421 Noah Friedman added the @option{--autoconf-dir} option and
26422 @code{AC_MACRODIR} environment variable.  (He also coined the term
26423 @dfn{autoconfiscate} to mean ``adapt a software package to use
26424 Autoconf''.)  Roland and Noah improved the quoting protection in
26425 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26426 dealing with portability problems from February through June, 1993.
26428 @node Deuteronomy
26429 @section Deuteronomy
26431 A long wish list for major features had accumulated, and the effect of
26432 several years of patching by various people had left some residual
26433 cruft.  In April 1994, while working for Cygnus Support, I began a major
26434 revision of Autoconf.  I added most of the features of the Cygnus
26435 @command{configure} that Autoconf had lacked, largely by adapting the
26436 relevant parts of Cygnus @command{configure} with the help of david zuhn
26437 and Ken Raeburn.  These features include support for using
26438 @file{config.sub}, @file{config.guess}, @option{--host}, and
26439 @option{--target}; making links to files; and running @command{configure}
26440 scripts in subdirectories.  Adding these features enabled Ken to convert
26441 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26442 Autoconf.
26444 I added more features in response to other peoples' requests.  Many
26445 people had asked for @command{configure} scripts to share the results of
26446 the checks between runs, because (particularly when configuring a large
26447 source tree, like Cygnus does) they were frustratingly slow.  Mike
26448 Haertel suggested adding site-specific initialization scripts.  People
26449 distributing software that had to unpack on MS-DOS asked for a way to
26450 override the @file{.in} extension on the file names, which produced file
26451 names like @file{config.h.in} containing two dots.  Jim Avera did an
26452 extensive examination of the problems with quoting in @code{AC_DEFINE}
26453 and @code{AC_SUBST}; his insights led to significant improvements.
26454 Richard Stallman asked that compiler output be sent to @file{config.log}
26455 instead of @file{/dev/null}, to help people debug the Emacs
26456 @command{configure} script.
26458 I made some other changes because of my dissatisfaction with the quality
26459 of the program.  I made the messages showing results of the checks less
26460 ambiguous, always printing a result.  I regularized the names of the
26461 macros and cleaned up coding style inconsistencies.  I added some
26462 auxiliary utilities that I had developed to help convert source code
26463 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26464 the macros not interrupt each others' messages.  (That feature revealed
26465 some performance bottlenecks in GNU M4, which he hastily
26466 corrected!)  I reorganized the documentation around problems people want
26467 to solve.  And I began a test suite, because experience had shown that
26468 Autoconf has a pronounced tendency to regress when we change it.
26470 Again, several alpha testers gave invaluable feedback, especially
26471 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26472 and Mark Eichin.
26474 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26475 have free time again.  I think.  Yeah, right.)
26478 @c ========================================================== Appendices
26481 @node GNU Free Documentation License
26482 @appendix GNU Free Documentation License
26484 @include fdl.texi
26486 @node Indices
26487 @appendix Indices
26489 @menu
26490 * Environment Variable Index::  Index of environment variables used
26491 * Output Variable Index::       Index of variables set in output files
26492 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26493 * Cache Variable Index::        Index of documented cache variables
26494 * Autoconf Macro Index::        Index of Autoconf macros
26495 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26496 * Autotest Macro Index::        Index of Autotest macros
26497 * Program & Function Index::    Index of those with portability problems
26498 * Concept Index::               General index
26499 @end menu
26501 @node Environment Variable Index
26502 @appendixsec Environment Variable Index
26504 This is an alphabetical list of the environment variables that might
26505 influence Autoconf checks.
26507 @printindex ev
26509 @node Output Variable Index
26510 @appendixsec Output Variable Index
26512 This is an alphabetical list of the variables that Autoconf can
26513 substitute into files that it creates, typically one or more
26514 makefiles.  @xref{Setting Output Variables}, for more information
26515 on how this is done.
26517 @printindex ov
26519 @node Preprocessor Symbol Index
26520 @appendixsec Preprocessor Symbol Index
26522 This is an alphabetical list of the C preprocessor symbols that the
26523 Autoconf macros define.  To work with Autoconf, C source code needs to
26524 use these names in @code{#if} or @code{#ifdef} directives.
26526 @printindex cv
26528 @node Cache Variable Index
26529 @appendixsec Cache Variable Index
26531 This is an alphabetical list of documented cache variables used
26532 by macros defined in Autoconf.  Autoconf macros may use additional cache
26533 variables internally.
26534 @ifset shortindexflag
26535 To make the list easier to use, the variables are listed without their
26536 preceding @samp{ac_cv_}.
26537 @end ifset
26539 @printindex CA
26541 @node Autoconf Macro Index
26542 @appendixsec Autoconf Macro Index
26544 This is an alphabetical list of the Autoconf macros.
26545 @ifset shortindexflag
26546 To make the list easier to use, the macros are listed without their
26547 preceding @samp{AC_}.
26548 @end ifset
26550 @printindex AC
26552 @node M4 Macro Index
26553 @appendixsec M4 Macro Index
26555 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26556 @ifset shortindexflag
26557 To make the list easier to use, the macros are listed without their
26558 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26559 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26560 names.
26561 @end ifset
26563 @printindex MS
26565 @node Autotest Macro Index
26566 @appendixsec Autotest Macro Index
26568 This is an alphabetical list of the Autotest macros.
26569 @ifset shortindexflag
26570 To make the list easier to use, the macros are listed without their
26571 preceding @samp{AT_}.
26572 @end ifset
26574 @printindex AT
26576 @node Program & Function Index
26577 @appendixsec Program and Function Index
26579 This is an alphabetical list of the programs and functions whose
26580 portability is discussed in this document.
26582 @printindex pr
26584 @node Concept Index
26585 @appendixsec Concept Index
26587 This is an alphabetical list of the files, tools, and concepts
26588 introduced in this document.
26590 @printindex cp
26592 @bye
26594 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26595 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26596 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26597 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26598 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26599 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26600 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26601 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26602 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26603 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26604 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26605 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26606 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26607 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26608 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26609 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26610 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26611 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26612 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26613 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26614 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26615 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26616 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26617 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26618 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26619 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26620 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26621 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26622 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26623 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26624 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26625 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26626 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26627 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26628 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26629 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26630 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26631 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26632 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26633 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26634 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26635 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26636 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26637 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26638 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26639 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm
26640 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26641 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26642 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26643 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26644 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26645 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26646 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26647 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26648 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26649 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26650 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26651 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26652 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26653 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26654 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26655 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26656 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26657 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26658 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26659 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26660 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26661 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26662 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26663 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26664 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26665 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26666 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26667 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26668 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26669 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26670 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26671 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26672 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26673 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26674 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26675 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26676 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26677 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26678 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26679 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26680 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26681 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26682 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26683 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26684 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck
26685 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26687 @c Local Variables:
26688 @c fill-column: 72
26689 @c ispell-local-dictionary: "american"
26690 @c indent-tabs-mode: nil
26691 @c whitespace-check-buffer-indent: nil
26692 @c End: