AC_LANG_BOOL_COMPILE_TRY(C): port to g++ with warnings
[autoconf.git] / doc / autoconf.texi
blobd7d2231cd862c1a673bd07f5c07a7402c1f8ed8a
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}@c
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
27 @end macro
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc.  That's why we first define indexes such as
34 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''.  Then you finish with a printed
37 @c index saying ``index is not existent''.  Of course: you ought to use
38 @c two letters :(  So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten.  But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself.  So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi.  But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index, for variables users may set
50 @c in their environment or on the configure command line.
51 @defcodeindex ev
52 @c Define an output variable index, for commonly AC_SUBST'ed variables.
53 @defcodeindex ov
54 @c Define a cache variable index, for variables matching *_cv_*.
55 @defcodeindex CA
56 @c Other shell variables not fitting the above categories should be
57 @c listed in the predefined vrindex, which we merge in the concept index.
58 @syncodeindex vr cp
59 @c Define a CPP preprocessor macro index, for #define'd strings.
60 @defcodeindex cv
61 @c Define an Autoconf macro index that @defmac doesn't write to.
62 @defcodeindex AC
63 @c Define an Autotest macro index that @defmac doesn't write to.
64 @defcodeindex AT
65 @c Define an M4sugar macro index that @defmac doesn't write to.
66 @defcodeindex MS
67 @c Define an index for *foreign* programs: `mv' etc.  Used for the
68 @c portability sections and so on.
69 @defindex pr
71 @c shortindexflag
72 @c --------------
73 @c Shall we factor AC_ out of the Autoconf macro index etc.?
74 @iftex
75 @set shortindexflag
76 @end iftex
78 @c @acindex{MACRO}
79 @c ---------------
80 @c Registering an AC_\MACRO\.
81 @ifset shortindexflag
82 @macro acindex{macro}
83 @ACindex \macro\
85 @end macro
86 @end ifset
87 @ifclear shortindexflag
88 @macro acindex{macro}
89 @ACindex AC_\macro\
90 @end macro
91 @end ifclear
93 @c @ahindex{MACRO}
94 @c ---------------
95 @c Registering an AH_\MACRO\.
96 @macro ahindex{macro}
97 @ACindex AH_\macro\
99 @end macro
101 @c @asindex{MACRO}
102 @c ---------------
103 @c Registering an AS_\MACRO\.
104 @ifset shortindexflag
105 @macro asindex{macro}
106 @MSindex \macro\
108 @end macro
109 @end ifset
110 @ifclear shortindexflag
111 @macro asindex{macro}
112 @MSindex AS_\macro\
113 @end macro
114 @end ifclear
116 @c @atindex{MACRO}
117 @c ---------------
118 @c Registering an AT_\MACRO\.
119 @ifset shortindexflag
120 @macro atindex{macro}
121 @ATindex \macro\
123 @end macro
124 @end ifset
125 @ifclear shortindexflag
126 @macro atindex{macro}
127 @ATindex AT_\macro\
128 @end macro
129 @end ifclear
131 @c @auindex{MACRO}
132 @c ---------------
133 @c Registering an AU_\MACRO\.
134 @macro auindex{macro}
135 @ACindex AU_\macro\
137 @end macro
139 @c @hdrindex{MACRO}
140 @c ----------------
141 @c Indexing a header.
142 @macro hdrindex{macro}
143 @prindex @file{\macro\}
145 @end macro
147 @c @msindex{MACRO}
148 @c ---------------
149 @c Registering an m4_\MACRO\.
150 @ifset shortindexflag
151 @macro msindex{macro}
152 @MSindex \macro\
154 @end macro
155 @end ifset
156 @ifclear shortindexflag
157 @macro msindex{macro}
158 @MSindex m4_\macro\
159 @end macro
160 @end ifclear
163 @c @caindex{VARIABLE}
164 @c ------------------
165 @c Registering an ac_cv_\VARIABLE\ cache variable.
166 @ifset shortindexflag
167 @macro caindex{macro}
168 @CAindex \macro\
169 @end macro
170 @end ifset
171 @ifclear shortindexflag
172 @macro caindex{macro}
173 @CAindex ac_cv_\macro\
174 @end macro
175 @end ifclear
177 @c Define an index for functions: `alloca' etc.  Used for the
178 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
179 @c since `@defmac' goes into it => we'd get all the macros too.
181 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
183 @c   ! No room for a new @write .
184 @c   l.112 @defcodeindex fu
186 @c   so don't define yet another one :(  Just put some tags before each
187 @c   @prindex which is actually a @funindex.
189 @c   @defcodeindex fu
192 @c   @c Put the programs and functions into their own index.
193 @c   @syncodeindex fu pr
195 @comment %**end of header
196 @comment ========================================================
198 @copying
200 This manual (@value{UPDATED}) is for GNU Autoconf
201 (version @value{VERSION}),
202 a package for creating scripts to configure source code packages using
203 templates and an M4 macro package.
205 Copyright @copyright{} 1992-1996, 1998-2011 Free Software Foundation,
206 Inc.
208 @quotation
209 Permission is granted to copy, distribute and/or modify this document
210 under the terms of the GNU Free Documentation License,
211 Version 1.3 or any later version published by the Free Software
212 Foundation; with no Invariant Sections, no Front-Cover texts, and
213 no Back-Cover Texts.  A copy of the license is included in the section
214 entitled ``GNU Free Documentation License.''
215 @end quotation
216 @end copying
220 @dircategory Software development
221 @direntry
222 * Autoconf: (autoconf).         Create source code configuration scripts.
223 @end direntry
225 @dircategory Individual utilities
226 @direntry
227 * autoscan: (autoconf)autoscan Invocation.
228                                 Semi-automatic @file{configure.ac} writing
229 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
230 * autoconf-invocation: (autoconf)autoconf Invocation.
231                                 How to create configuration scripts
232 * autoreconf: (autoconf)autoreconf Invocation.
233                                 Remaking multiple @command{configure} scripts
234 * autoheader: (autoconf)autoheader Invocation.
235                                 How to create configuration templates
236 * autom4te: (autoconf)autom4te Invocation.
237                                 The Autoconf executables backbone
238 * configure: (autoconf)configure Invocation.    Configuring a package.
239 * autoupdate: (autoconf)autoupdate Invocation.
240                                 Automatic update of @file{configure.ac}
241 * config.status: (autoconf)config.status Invocation. Recreating configurations.
242 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
243 @end direntry
245 @titlepage
246 @title Autoconf
247 @subtitle Creating Automatic Configuration Scripts
248 @subtitle for version @value{VERSION}, @value{UPDATED}
249 @author David MacKenzie
250 @author Ben Elliston
251 @author Akim Demaille
252 @page
253 @vskip 0pt plus 1filll
254 @insertcopying
255 @end titlepage
257 @contents
260 @ifnottex
261 @node Top
262 @top Autoconf
263 @insertcopying
264 @end ifnottex
266 @c The master menu, created with texinfo-master-menu, goes here.
268 @menu
269 * Introduction::                Autoconf's purpose, strengths, and weaknesses
270 * The GNU Build System::        A set of tools for portable software packages
271 * Making configure Scripts::    How to organize and produce Autoconf scripts
272 * Setup::                       Initialization and output
273 * Existing Tests::              Macros that check for particular features
274 * Writing Tests::               How to write new feature checks
275 * Results::                     What to do with results from feature checks
276 * Programming in M4::           Layers on top of which Autoconf is written
277 * Programming in M4sh::         Shell portability layer
278 * Writing Autoconf Macros::     Adding new macros to Autoconf
279 * Portable Shell::              Shell script portability pitfalls
280 * Portable Make::               Makefile portability pitfalls
281 * Portable C and C++::          C and C++ portability pitfalls
282 * Manual Configuration::        Selecting features that can't be guessed
283 * Site Configuration::          Local defaults for @command{configure}
284 * Running configure Scripts::   How to use the Autoconf output
285 * config.status Invocation::    Recreating a configuration
286 * Obsolete Constructs::         Kept for backward compatibility
287 * Using Autotest::              Creating portable test suites
288 * FAQ::                         Frequent Autoconf Questions, with answers
289 * History::                     History of Autoconf
290 * GNU Free Documentation License::  License for copying this manual
291 * Indices::                     Indices of symbols, concepts, etc.
293 @detailmenu
294  --- The Detailed Node Listing ---
296 The GNU Build System
298 * Automake::                    Escaping makefile hell
299 * Gnulib::                      The GNU portability library
300 * Libtool::                     Building libraries portably
301 * Pointers::                    More info on the GNU build system
303 Making @command{configure} Scripts
305 * Writing Autoconf Input::      What to put in an Autoconf input file
306 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
307 * ifnames Invocation::          Listing the conditionals in source code
308 * autoconf Invocation::         How to create configuration scripts
309 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
311 Writing @file{configure.ac}
313 * Shell Script Compiler::       Autoconf as solution of a problem
314 * Autoconf Language::           Programming in Autoconf
315 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
317 Initialization and Output Files
319 * Initializing configure::      Option processing etc.
320 * Versioning::                  Dealing with Autoconf versions
321 * Notices::                     Copyright, version numbers in @command{configure}
322 * Input::                       Where Autoconf should find files
323 * Output::                      Outputting results from the configuration
324 * Configuration Actions::       Preparing the output based on results
325 * Configuration Files::         Creating output files
326 * Makefile Substitutions::      Using output variables in makefiles
327 * Configuration Headers::       Creating a configuration header file
328 * Configuration Commands::      Running arbitrary instantiation commands
329 * Configuration Links::         Links depending on the configuration
330 * Subdirectories::              Configuring independent packages together
331 * Default Prefix::              Changing the default installation prefix
333 Substitutions in Makefiles
335 * Preset Output Variables::     Output variables that are always set
336 * Installation Directory Variables::  Other preset output variables
337 * Changed Directory Variables::  Warnings about @file{datarootdir}
338 * Build Directories::           Supporting multiple concurrent compiles
339 * Automatic Remaking::          Makefile rules for configuring
341 Configuration Header Files
343 * Header Templates::            Input for the configuration headers
344 * autoheader Invocation::       How to create configuration templates
345 * Autoheader Macros::           How to specify CPP templates
347 Existing Tests
349 * Common Behavior::             Macros' standard schemes
350 * Alternative Programs::        Selecting between alternative programs
351 * Files::                       Checking for the existence of files
352 * Libraries::                   Library archives that might be missing
353 * Library Functions::           C library functions that might be missing
354 * Header Files::                Header files that might be missing
355 * Declarations::                Declarations that may be missing
356 * Structures::                  Structures or members that might be missing
357 * Types::                       Types that might be missing
358 * Compilers and Preprocessors::  Checking for compiling programs
359 * System Services::             Operating system services
360 * Posix Variants::              Special kludges for specific Posix variants
361 * Erlang Libraries::            Checking for the existence of Erlang libraries
363 Common Behavior
365 * Standard Symbols::            Symbols defined by the macros
366 * Default Includes::            Includes used by the generic macros
368 Alternative Programs
370 * Particular Programs::         Special handling to find certain programs
371 * Generic Programs::            How to find other programs
373 Library Functions
375 * Function Portability::        Pitfalls with usual functions
376 * Particular Functions::        Special handling to find certain functions
377 * Generic Functions::           How to find other functions
379 Header Files
381 * Header Portability::          Collected knowledge on common headers
382 * Particular Headers::          Special handling to find certain headers
383 * Generic Headers::             How to find other headers
385 Declarations
387 * Particular Declarations::     Macros to check for certain declarations
388 * Generic Declarations::        How to find other declarations
390 Structures
392 * Particular Structures::       Macros to check for certain structure members
393 * Generic Structures::          How to find other structure members
395 Types
397 * Particular Types::            Special handling to find certain types
398 * Generic Types::               How to find other types
400 Compilers and Preprocessors
402 * Specific Compiler Characteristics::  Some portability issues
403 * Generic Compiler Characteristics::  Language independent tests and features
404 * C Compiler::                  Checking its characteristics
405 * C++ Compiler::                Likewise
406 * Objective C Compiler::        Likewise
407 * Objective C++ Compiler::      Likewise
408 * Erlang Compiler and Interpreter::  Likewise
409 * Fortran Compiler::            Likewise
410 * Go Compiler::                 Likewise
412 Writing Tests
414 * Language Choice::             Selecting which language to use for testing
415 * Writing Test Programs::       Forging source files for compilers
416 * Running the Preprocessor::    Detecting preprocessor symbols
417 * Running the Compiler::        Detecting language or header features
418 * Running the Linker::          Detecting library features
419 * Runtime::                     Testing for runtime features
420 * Systemology::                 A zoology of operating systems
421 * Multiple Cases::              Tests for several possible values
423 Writing Test Programs
425 * Guidelines::                  General rules for writing test programs
426 * Test Functions::              Avoiding pitfalls in test programs
427 * Generating Sources::          Source program boilerplate
429 Results of Tests
431 * Defining Symbols::            Defining C preprocessor symbols
432 * Setting Output Variables::    Replacing variables in output files
433 * Special Chars in Variables::  Characters to beware of in variables
434 * Caching Results::             Speeding up subsequent @command{configure} runs
435 * Printing Messages::           Notifying @command{configure} users
437 Caching Results
439 * Cache Variable Names::        Shell variables used in caches
440 * Cache Files::                 Files @command{configure} uses for caching
441 * Cache Checkpointing::         Loading and saving the cache file
443 Programming in M4
445 * M4 Quotation::                Protecting macros from unwanted expansion
446 * Using autom4te::              The Autoconf executables backbone
447 * Programming in M4sugar::      Convenient pure M4 macros
448 * Debugging via autom4te::      Figuring out what M4 was doing
450 M4 Quotation
452 * Active Characters::           Characters that change the behavior of M4
453 * One Macro Call::              Quotation and one macro call
454 * Quoting and Parameters::      M4 vs. shell parameters
455 * Quotation and Nested Macros::  Macros calling macros
456 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
457 * Quadrigraphs::                Another way to escape special characters
458 * Balancing Parentheses::       Dealing with unbalanced parentheses
459 * Quotation Rule Of Thumb::     One parenthesis, one quote
461 Using @command{autom4te}
463 * autom4te Invocation::         A GNU M4 wrapper
464 * Customizing autom4te::        Customizing the Autoconf package
466 Programming in M4sugar
468 * Redefined M4 Macros::         M4 builtins changed in M4sugar
469 * Diagnostic Macros::           Diagnostic messages from M4sugar
470 * Diversion support::           Diversions in M4sugar
471 * Conditional constructs::      Conditions in M4
472 * Looping constructs::          Iteration in M4
473 * Evaluation Macros::           More quotation and evaluation control
474 * Text processing Macros::      String manipulation in M4
475 * Number processing Macros::    Arithmetic computation in M4
476 * Set manipulation Macros::     Set manipulation in M4
477 * Forbidden Patterns::          Catching unexpanded macros
479 Programming in M4sh
481 * Common Shell Constructs::     Portability layer for common shell constructs
482 * Polymorphic Variables::       Support for indirect variable names
483 * Initialization Macros::       Macros to establish a sane shell environment
484 * File Descriptor Macros::      File descriptor macros for input and output
486 Writing Autoconf Macros
488 * Macro Definitions::           Basic format of an Autoconf macro
489 * Macro Names::                 What to call your new macros
490 * Reporting Messages::          Notifying @command{autoconf} users
491 * Dependencies Between Macros::  What to do when macros depend on other macros
492 * Obsoleting Macros::           Warning about old ways of doing things
493 * Coding Style::                Writing Autoconf macros @`a la Autoconf
495 Dependencies Between Macros
497 * Prerequisite Macros::         Ensuring required information
498 * Suggested Ordering::          Warning about possible ordering problems
499 * One-Shot Macros::             Ensuring a macro is called only once
501 Portable Shell Programming
503 * Shellology::                  A zoology of shells
504 * Here-Documents::              Quirks and tricks
505 * File Descriptors::            FDs and redirections
506 * Signal Handling::             Shells, signals, and headaches
507 * File System Conventions::     File names
508 * Shell Pattern Matching::      Pattern matching
509 * Shell Substitutions::         Variable and command expansions
510 * Assignments::                 Varying side effects of assignments
511 * Parentheses::                 Parentheses in shell scripts
512 * Slashes::                     Slashes in shell scripts
513 * Special Shell Variables::     Variables you should not change
514 * Shell Functions::             What to look out for if you use them
515 * Limitations of Builtins::     Portable use of not so portable /bin/sh
516 * Limitations of Usual Tools::  Portable use of portable tools
518 Portable Make Programming
520 * $< in Ordinary Make Rules::   $< in ordinary rules
521 * Failure in Make Rules::       Failing portably in rules
522 * Special Chars in Names::      Special Characters in Macro Names
523 * Backslash-Newline-Newline::   Empty last lines in macro definitions
524 * Backslash-Newline Comments::  Spanning comments across line boundaries
525 * Long Lines in Makefiles::     Line length limitations
526 * Macros and Submakes::         @code{make macro=value} and submakes
527 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
528 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
529 * Parallel Make::               Parallel @command{make} quirks
530 * Comments in Make Rules::      Other problems with Make comments
531 * Newlines in Make Rules::      Using literal newlines in rules
532 * Comments in Make Macros::     Other problems with Make comments in macros
533 * Trailing whitespace in Make Macros::  Macro substitution problems
534 * Command-line Macros and whitespace::  Whitespace trimming of values
535 * obj/ and Make::               Don't name a subdirectory @file{obj}
536 * make -k Status::              Exit status of @samp{make -k}
537 * VPATH and Make::              @code{VPATH} woes
538 * Single Suffix Rules::         Single suffix rules and separated dependencies
539 * Timestamps and Make::         Subsecond timestamp resolution
541 @code{VPATH} and Make
543 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
544 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
545 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
546 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
547 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
548 * Make Target Lookup::          More details about @code{VPATH} lookup
550 Portable C and C++ Programming
552 * Varieties of Unportability::  How to make your programs unportable
553 * Integer Overflow::            When integers get too large
554 * Preprocessor Arithmetic::     @code{#if} expression problems
555 * Null Pointers::               Properties of null pointers
556 * Buffer Overruns::             Subscript errors and the like
557 * Volatile Objects::            @code{volatile} and signals
558 * Floating Point Portability::  Portable floating-point arithmetic
559 * Exiting Portably::            Exiting and the exit status
561 Integer Overflow
563 * Integer Overflow Basics::     Why integer overflow is a problem
564 * Signed Overflow Examples::    Examples of code assuming wraparound
565 * Optimization and Wraparound::  Optimizations that break uses of wraparound
566 * Signed Overflow Advice::      Practical advice for signed overflow issues
567 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
569 Manual Configuration
571 * Specifying Target Triplets::  Specifying target triplets
572 * Canonicalizing::              Getting the canonical system type
573 * Using System Type::           What to do with the system type
575 Site Configuration
577 * Help Formatting::             Customizing @samp{configure --help}
578 * External Software::           Working with other optional software
579 * Package Options::             Selecting optional features
580 * Pretty Help Strings::         Formatting help string
581 * Option Checking::             Controlling checking of @command{configure} options
582 * Site Details::                Configuring site details
583 * Transforming Names::          Changing program names when installing
584 * Site Defaults::               Giving @command{configure} local defaults
586 Transforming Program Names When Installing
588 * Transformation Options::      @command{configure} options to transform names
589 * Transformation Examples::     Sample uses of transforming names
590 * Transformation Rules::        Makefile uses of transforming names
592 Running @command{configure} Scripts
594 * Basic Installation::          Instructions for typical cases
595 * Compilers and Options::       Selecting compilers and optimization
596 * Multiple Architectures::      Compiling for multiple architectures at once
597 * Installation Names::          Installing in different directories
598 * Optional Features::           Selecting optional features
599 * Particular Systems::          Particular systems
600 * System Type::                 Specifying the system type
601 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
602 * Defining Variables::          Specifying the compiler etc.
603 * configure Invocation::        Changing how @command{configure} runs
605 Obsolete Constructs
607 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
608 * acconfig Header::             Additional entries in @file{config.h.in}
609 * autoupdate Invocation::       Automatic update of @file{configure.ac}
610 * Obsolete Macros::             Backward compatibility macros
611 * Autoconf 1::                  Tips for upgrading your files
612 * Autoconf 2.13::               Some fresher tips
614 Upgrading From Version 1
616 * Changed File Names::          Files you might rename
617 * Changed Makefiles::           New things to put in @file{Makefile.in}
618 * Changed Macros::              Macro calls you might replace
619 * Changed Results::             Changes in how to check test results
620 * Changed Macro Writing::       Better ways to write your own macros
622 Upgrading From Version 2.13
624 * Changed Quotation::           Broken code which used to work
625 * New Macros::                  Interaction with foreign macros
626 * Hosts and Cross-Compilation::  Bugward compatibility kludges
627 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
628 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
630 Generating Test Suites with Autotest
632 * Using an Autotest Test Suite::  Autotest and the user
633 * Writing Testsuites::          Autotest macros
634 * testsuite Invocation::        Running @command{testsuite} scripts
635 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
637 Using an Autotest Test Suite
639 * testsuite Scripts::           The concepts of Autotest
640 * Autotest Logs::               Their contents
642 Frequent Autoconf Questions, with answers
644 * Distributing::                Distributing @command{configure} scripts
645 * Why GNU M4::                  Why not use the standard M4?
646 * Bootstrapping::               Autoconf and GNU M4 require each other?
647 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
648 * Defining Directories::        Passing @code{datadir} to program
649 * Autom4te Cache::              What is it?  Can I remove it?
650 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
651 * Expanded Before Required::    Expanded Before Required
652 * Debugging::                   Debugging @command{configure} scripts
654 History of Autoconf
656 * Genesis::                     Prehistory and naming of @command{configure}
657 * Exodus::                      The plagues of M4 and Perl
658 * Leviticus::                   The priestly code of portability arrives
659 * Numbers::                     Growth and contributors
660 * Deuteronomy::                 Approaching the promises of easy configuration
662 Indices
664 * Environment Variable Index::  Index of environment variables used
665 * Output Variable Index::       Index of variables set in output files
666 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
667 * Cache Variable Index::        Index of documented cache variables
668 * Autoconf Macro Index::        Index of Autoconf macros
669 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
670 * Autotest Macro Index::        Index of Autotest macros
671 * Program & Function Index::    Index of those with portability problems
672 * Concept Index::               General index
674 @end detailmenu
675 @end menu
677 @c ============================================================= Introduction.
679 @node Introduction
680 @chapter Introduction
681 @cindex Introduction
683 @flushright
684 A physicist, an engineer, and a computer scientist were discussing the
685 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
686 early in the Creation, God made Light; and you know, Maxwell's
687 equations, the dual nature of electromagnetic waves, the relativistic
688 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
689 before making Light, God split the Chaos into Land and Water; it takes a
690 hell of an engineer to handle that big amount of mud, and orderly
691 separation of solids from liquids@enddots{}'' The computer scientist
692 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
694 ---Anonymous
695 @end flushright
696 @c (via Franc,ois Pinard)
698 Autoconf is a tool for producing shell scripts that automatically
699 configure software source code packages to adapt to many kinds of
700 Posix-like systems.  The configuration scripts produced by Autoconf
701 are independent of Autoconf when they are run, so their users do not
702 need to have Autoconf.
704 The configuration scripts produced by Autoconf require no manual user
705 intervention when run; they do not normally even need an argument
706 specifying the system type.  Instead, they individually test for the
707 presence of each feature that the software package they are for might need.
708 (Before each check, they print a one-line message stating what they are
709 checking for, so the user doesn't get too bored while waiting for the
710 script to finish.)  As a result, they deal well with systems that are
711 hybrids or customized from the more common Posix variants.  There is
712 no need to maintain files that list the features supported by each
713 release of each variant of Posix.
715 For each software package that Autoconf is used with, it creates a
716 configuration script from a template file that lists the system features
717 that the package needs or can use.  After the shell code to recognize
718 and respond to a system feature has been written, Autoconf allows it to
719 be shared by many software packages that can use (or need) that feature.
720 If it later turns out that the shell code needs adjustment for some
721 reason, it needs to be changed in only one place; all of the
722 configuration scripts can be regenerated automatically to take advantage
723 of the updated code.
725 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
726 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
727 Those who do not understand Autoconf are condemned to reinvent it, poorly.
728 The primary goal of Autoconf is making the @emph{user's} life easier;
729 making the @emph{maintainer's} life easier is only a secondary goal.
730 Put another way, the primary goal is not to make the generation of
731 @file{configure} automatic for package maintainers (although patches
732 along that front are welcome, since package maintainers form the user
733 base of Autoconf); rather, the goal is to make @file{configure}
734 painless, portable, and predictable for the end user of each
735 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
736 successful at its goal --- most complaints to the Autoconf list are
737 about difficulties in writing Autoconf input, and not in the behavior of
738 the resulting @file{configure}.  Even packages that don't use Autoconf
739 will generally provide a @file{configure} script, and the most common
740 complaint about these alternative home-grown scripts is that they fail
741 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
742 standards, The GNU Coding Standards}) that users
743 have come to expect from Autoconf-generated @file{configure} scripts.
745 The Metaconfig package is similar in purpose to Autoconf, but the
746 scripts it produces require manual user intervention, which is quite
747 inconvenient when configuring large source trees.  Unlike Metaconfig
748 scripts, Autoconf scripts can support cross-compiling, if some care is
749 taken in writing them.
751 Autoconf does not solve all problems related to making portable
752 software packages---for a more complete solution, it should be used in
753 concert with other GNU build tools like Automake and
754 Libtool.  These other tools take on jobs like the creation of a
755 portable, recursive makefile with all of the standard targets,
756 linking of shared libraries, and so on.  @xref{The GNU Build System},
757 for more information.
759 Autoconf imposes some restrictions on the names of macros used with
760 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
762 Autoconf requires GNU M4 version 1.4.6 or later in order to
763 generate the scripts.  It uses features that some versions of M4,
764 including GNU M4 1.3, do not have.  Autoconf works better
765 with GNU M4 version 1.4.14 or later, though this is not
766 required.
768 @xref{Autoconf 1}, for information about upgrading from version 1.
769 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
770 for answers to some common questions about Autoconf.
772 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
773 Autoconf web page} for up-to-date information, details on the mailing
774 lists, pointers to a list of known bugs, etc.
776 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
777 list}.  Past suggestions are
778 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
780 Mail bug reports to @email{bug-autoconf@@gnu.org, the
781 Autoconf Bugs mailing list}.  Past bug reports are
782 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
784 If possible, first check that your bug is
785 not already solved in current development versions, and that it has not
786 been reported yet.  Be sure to include all the needed information and a
787 short @file{configure.ac} that demonstrates the problem.
789 Autoconf's development tree is accessible via @command{git}; see the
790 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
791 Summary} for details, or view
792 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
793 repository}.  Anonymous CVS access is also available, see
794 @file{README} for more details.  Patches relative to the
795 current @command{git} version can be sent for review to the
796 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
797 discussion on prior patches
798 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
799 archived}; and all commits are posted in the read-only
800 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
801 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
802 archived}.
804 Because of its mission, the Autoconf package itself
805 includes only a set of often-used
806 macros that have already demonstrated their usefulness.  Nevertheless,
807 if you wish to share your macros, or find existing ones, see the
808 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
809 Archive}, which is kindly run by @email{simons@@cryp.to,
810 Peter Simons}.
813 @c ================================================= The GNU Build System
815 @node The GNU Build System
816 @chapter The GNU Build System
817 @cindex GNU build system
819 Autoconf solves an important problem---reliable discovery of
820 system-specific build and runtime information---but this is only one
821 piece of the puzzle for the development of portable software.  To this
822 end, the GNU project has developed a suite of integrated
823 utilities to finish the job Autoconf started: the GNU build
824 system, whose most important components are Autoconf, Automake, and
825 Libtool.  In this chapter, we introduce you to those tools, point you
826 to sources of more information, and try to convince you to use the
827 entire GNU build system for your software.
829 @menu
830 * Automake::                    Escaping makefile hell
831 * Gnulib::                      The GNU portability library
832 * Libtool::                     Building libraries portably
833 * Pointers::                    More info on the GNU build system
834 @end menu
836 @node Automake
837 @section Automake
839 The ubiquity of @command{make} means that a makefile is almost the
840 only viable way to distribute automatic build rules for software, but
841 one quickly runs into its numerous limitations.  Its lack of
842 support for automatic dependency tracking, recursive builds in
843 subdirectories, reliable timestamps (e.g., for network file systems), and
844 so on, mean that developers must painfully (and often incorrectly)
845 reinvent the wheel for each project.  Portability is non-trivial, thanks
846 to the quirks of @command{make} on many systems.  On top of all this is the
847 manual labor required to implement the many standard targets that users
848 have come to expect (@code{make install}, @code{make distclean},
849 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
850 you also have to insert repetitive code in your @file{Makefile.in} to
851 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
852 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
853 @cindex Automake
855 Automake allows you to specify your build needs in a @file{Makefile.am}
856 file with a vastly simpler and more powerful syntax than that of a plain
857 makefile, and then generates a portable @file{Makefile.in} for
858 use with Autoconf.  For example, the @file{Makefile.am} to build and
859 install a simple ``Hello world'' program might look like:
861 @example
862 bin_PROGRAMS = hello
863 hello_SOURCES = hello.c
864 @end example
866 @noindent
867 The resulting @file{Makefile.in} (~400 lines) automatically supports all
868 the standard targets, the substitutions provided by Autoconf, automatic
869 dependency tracking, @code{VPATH} building, and so on.  @command{make}
870 builds the @code{hello} program, and @code{make install} installs it
871 in @file{/usr/local/bin} (or whatever prefix was given to
872 @command{configure}, if not @file{/usr/local}).
874 The benefits of Automake increase for larger packages (especially ones
875 with subdirectories), but even for small programs the added convenience
876 and portability can be substantial.  And that's not all@enddots{}
878 @node Gnulib
879 @section Gnulib
881 GNU software has a well-deserved reputation for running on
882 many different types of systems.  While our primary goal is to write
883 software for the GNU system, many users and developers have
884 been introduced to us through the systems that they were already using.
886 @cindex Gnulib
887 Gnulib is a central location for common GNU code, intended to
888 be shared among free software packages.  Its components are typically
889 shared at the source level, rather than being a library that gets built,
890 installed, and linked against.  The idea is to copy files from Gnulib
891 into your own source tree.  There is no distribution tarball; developers
892 should just grab source modules from the repository.  The source files
893 are available online, under various licenses, mostly GNU
894 GPL or GNU LGPL.
896 Gnulib modules typically contain C source code along with Autoconf
897 macros used to configure the source code.  For example, the Gnulib
898 @code{stdbool} module implements a @file{stdbool.h} header that nearly
899 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
900 This module contains a source file for the replacement header, along
901 with an Autoconf macro that arranges to use the replacement header on
902 old-fashioned systems.
904 @node Libtool
905 @section Libtool
907 Often, one wants to build not only programs, but libraries, so that
908 other programs can benefit from the fruits of your labor.  Ideally, one
909 would like to produce @emph{shared} (dynamically linked) libraries,
910 which can be used by multiple programs without duplication on disk or in
911 memory and can be updated independently of the linked programs.
912 Producing shared libraries portably, however, is the stuff of
913 nightmares---each system has its own incompatible tools, compiler flags,
914 and magic incantations.  Fortunately, GNU provides a solution:
915 @dfn{Libtool}.
916 @cindex Libtool
918 Libtool handles all the requirements of building shared libraries for
919 you, and at this time seems to be the @emph{only} way to do so with any
920 portability.  It also handles many other headaches, such as: the
921 interaction of Make rules with the variable suffixes of
922 shared libraries, linking reliably with shared libraries before they are
923 installed by the superuser, and supplying a consistent versioning system
924 (so that different versions of a library can be installed or upgraded
925 without breaking binary compatibility).  Although Libtool, like
926 Autoconf, can be used without Automake, it is most simply utilized in
927 conjunction with Automake---there, Libtool is used automatically
928 whenever shared libraries are needed, and you need not know its syntax.
930 @node Pointers
931 @section Pointers
933 Developers who are used to the simplicity of @command{make} for small
934 projects on a single system might be daunted at the prospect of
935 learning to use Automake and Autoconf.  As your software is
936 distributed to more and more users, however, you otherwise
937 quickly find yourself putting lots of effort into reinventing the
938 services that the GNU build tools provide, and making the
939 same mistakes that they once made and overcame.  (Besides, since
940 you're already learning Autoconf, Automake is a piece of cake.)
942 There are a number of places that you can go to for more information on
943 the GNU build tools.
945 @itemize @minus
947 @item Web
949 The project home pages for
950 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
951 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
952 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
953 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
955 @item Automake Manual
957 @xref{Top, , Automake, automake, GNU Automake}, for more
958 information on Automake.
960 @item Books
962 The book @cite{GNU Autoconf, Automake and
963 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
964 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
965 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
966 build environment.  You can also find
967 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
969 @end itemize
971 @c ================================================= Making configure Scripts.
973 @node Making configure Scripts
974 @chapter Making @command{configure} Scripts
975 @cindex @file{aclocal.m4}
976 @cindex @command{configure}
978 The configuration scripts that Autoconf produces are by convention
979 called @command{configure}.  When run, @command{configure} creates several
980 files, replacing configuration parameters in them with appropriate
981 values.  The files that @command{configure} creates are:
983 @itemize @minus
984 @item
985 one or more @file{Makefile} files, usually one in each subdirectory of the
986 package (@pxref{Makefile Substitutions});
988 @item
989 optionally, a C header file, the name of which is configurable,
990 containing @code{#define} directives (@pxref{Configuration Headers});
992 @item
993 a shell script called @file{config.status} that, when run, recreates
994 the files listed above (@pxref{config.status Invocation});
996 @item
997 an optional shell script normally called @file{config.cache}
998 (created when using @samp{configure --config-cache}) that
999 saves the results of running many of the tests (@pxref{Cache Files});
1001 @item
1002 a file called @file{config.log} containing any messages produced by
1003 compilers, to help debugging if @command{configure} makes a mistake.
1004 @end itemize
1006 @cindex @file{configure.in}
1007 @cindex @file{configure.ac}
1008 To create a @command{configure} script with Autoconf, you need to write an
1009 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
1010 @command{autoconf} on it.  If you write your own feature tests to
1011 supplement those that come with Autoconf, you might also write files
1012 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1013 file to contain @code{#define} directives, you might also run
1014 @command{autoheader}, and you can distribute the generated file
1015 @file{config.h.in} with the package.
1017 Here is a diagram showing how the files that can be used in
1018 configuration are produced.  Programs that are executed are suffixed by
1019 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1020 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1021 macro files (by reading @file{autoconf.m4}).
1023 @noindent
1024 Files used in preparing a software package for distribution, when using
1025 just Autoconf:
1026 @example
1027 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1029 @group
1030 configure.ac --.
1031                |   .------> autoconf* -----> configure
1032 [aclocal.m4] --+---+
1033                |   `-----> [autoheader*] --> [config.h.in]
1034 [acsite.m4] ---'
1035 @end group
1037 Makefile.in
1038 @end example
1040 @noindent
1041 Additionally, if you use Automake, the following additional productions
1042 come into play:
1044 @example
1045 @group
1046 [acinclude.m4] --.
1047                  |
1048 [local macros] --+--> aclocal* --> aclocal.m4
1049                  |
1050 configure.ac ----'
1051 @end group
1053 @group
1054 configure.ac --.
1055                +--> automake* --> Makefile.in
1056 Makefile.am ---'
1057 @end group
1058 @end example
1060 @noindent
1061 Files used in configuring a software package:
1062 @example
1063 @group
1064                        .-------------> [config.cache]
1065 configure* ------------+-------------> config.log
1066                        |
1067 [config.h.in] -.       v            .-> [config.h] -.
1068                +--> config.status* -+               +--> make*
1069 Makefile.in ---'                    `-> Makefile ---'
1070 @end group
1071 @end example
1073 @menu
1074 * Writing Autoconf Input::      What to put in an Autoconf input file
1075 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1076 * ifnames Invocation::          Listing the conditionals in source code
1077 * autoconf Invocation::         How to create configuration scripts
1078 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1079 @end menu
1081 @node Writing Autoconf Input
1082 @section Writing @file{configure.ac}
1084 To produce a @command{configure} script for a software package, create a
1085 file called @file{configure.ac} that contains invocations of the
1086 Autoconf macros that test the system features your package needs or can
1087 use.  Autoconf macros already exist to check for many features; see
1088 @ref{Existing Tests}, for their descriptions.  For most other features,
1089 you can use Autoconf template macros to produce custom checks; see
1090 @ref{Writing Tests}, for information about them.  For especially tricky
1091 or specialized features, @file{configure.ac} might need to contain some
1092 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1093 Programming}.  The @command{autoscan} program can give you a good start
1094 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1095 information).
1097 Previous versions of Autoconf promoted the name @file{configure.in},
1098 which is somewhat ambiguous (the tool needed to process this file is not
1099 described by its extension), and introduces a slight confusion with
1100 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1101 processed by @command{configure}'').  Using @file{configure.ac} is now
1102 preferred.
1104 @menu
1105 * Shell Script Compiler::       Autoconf as solution of a problem
1106 * Autoconf Language::           Programming in Autoconf
1107 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1108 @end menu
1110 @node Shell Script Compiler
1111 @subsection A Shell Script Compiler
1113 Just as for any other computer language, in order to properly program
1114 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1115 the language tries to address and @emph{how} it does so.
1117 The problem Autoconf addresses is that the world is a mess.  After all,
1118 you are using Autoconf in order to have your package compile easily on
1119 all sorts of different systems, some of them being extremely hostile.
1120 Autoconf itself bears the price for these differences: @command{configure}
1121 must run on all those systems, and thus @command{configure} must limit itself
1122 to their lowest common denominator of features.
1124 Naturally, you might then think of shell scripts; who needs
1125 @command{autoconf}?  A set of properly written shell functions is enough to
1126 make it easy to write @command{configure} scripts by hand.  Sigh!
1127 Unfortunately, even in 2008, where shells without any function support are
1128 far and few between, there are pitfalls to avoid when making use of them.
1129 Also, finding a Bourne shell that accepts shell functions is not trivial,
1130 even though there is almost always one on interesting porting targets.
1132 So, what is really needed is some kind of compiler, @command{autoconf},
1133 that takes an Autoconf program, @file{configure.ac}, and transforms it
1134 into a portable shell script, @command{configure}.
1136 How does @command{autoconf} perform this task?
1138 There are two obvious possibilities: creating a brand new language or
1139 extending an existing one.  The former option is attractive: all
1140 sorts of optimizations could easily be implemented in the compiler and
1141 many rigorous checks could be performed on the Autoconf program
1142 (e.g., rejecting any non-portable construct).  Alternatively, you can
1143 extend an existing language, such as the @code{sh} (Bourne shell)
1144 language.
1146 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1147 therefore most convenient to implement @command{autoconf} as a macro
1148 expander: a program that repeatedly performs @dfn{macro expansions} on
1149 text input, replacing macro calls with macro bodies and producing a pure
1150 @code{sh} script in the end.  Instead of implementing a dedicated
1151 Autoconf macro expander, it is natural to use an existing
1152 general-purpose macro language, such as M4, and implement the extensions
1153 as a set of M4 macros.
1156 @node Autoconf Language
1157 @subsection The Autoconf Language
1158 @cindex quotation
1160 The Autoconf language differs from many other computer
1161 languages because it treats actual code the same as plain text.  Whereas
1162 in C, for instance, data and instructions have different syntactic
1163 status, in Autoconf their status is rigorously the same.  Therefore, we
1164 need a means to distinguish literal strings from text to be expanded:
1165 quotation.
1167 When calling macros that take arguments, there must not be any white
1168 space between the macro name and the open parenthesis.
1170 @example
1171 AC_INIT ([oops], [1.0]) # incorrect
1172 AC_INIT([hello], [1.0]) # good
1173 @end example
1175 Arguments should
1176 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1177 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1178 unless they are quoted.  You should always quote an argument that
1179 might contain a macro name, comma, parenthesis, or a leading blank or
1180 newline.  This rule applies recursively for every macro
1181 call, including macros called from other macros.  For more details on
1182 quoting rules, see @ref{Programming in M4}.
1184 For instance:
1186 @example
1187 AC_CHECK_HEADER([stdio.h],
1188                 [AC_DEFINE([HAVE_STDIO_H], [1],
1189                    [Define to 1 if you have <stdio.h>.])],
1190                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1191 @end example
1193 @noindent
1194 is quoted properly.  You may safely simplify its quotation to:
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 because @samp{1} cannot contain a macro call.  Here, the argument of
1205 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1206 interpreted as an argument separator.  Also, the second and third arguments
1207 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1208 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1209 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1210 if you unwisely defined a macro with a name like @samp{Define} or
1211 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1212 would keep the quotes, but many Autoconf users find such precautions
1213 annoying, and would rewrite the example as follows:
1215 @example
1216 AC_CHECK_HEADER(stdio.h,
1217                 [AC_DEFINE(HAVE_STDIO_H, 1,
1218                    [Define to 1 if you have <stdio.h>.])],
1219                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1220 @end example
1222 @noindent
1223 This is safe, so long as you adopt good naming conventions and do not
1224 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1225 @samp{h}.  Though it is also safe here to omit the quotes around
1226 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1227 message strings are more likely to inadvertently contain commas.
1229 The following example is wrong and dangerous, as it is underquoted:
1231 @example
1232 AC_CHECK_HEADER(stdio.h,
1233                 AC_DEFINE(HAVE_STDIO_H, 1,
1234                    Define to 1 if you have <stdio.h>.),
1235                 AC_MSG_ERROR([sorry, can't do anything for you]))
1236 @end example
1238 In other cases, you may have to use text that also resembles a macro
1239 call.  You must quote that text even when it is not passed as a macro
1240 argument.  For example, these two approaches in @file{configure.ac}
1241 (quoting just the potential problems, or quoting the entire line) will
1242 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1244 @example
1245 echo "Hard rock was here!  --[AC_DC]"
1246 [echo "Hard rock was here!  --AC_DC"]
1247 @end example
1249 @noindent
1250 which results in this text in @file{configure}:
1252 @example
1253 echo "Hard rock was here!  --AC_DC"
1254 echo "Hard rock was here!  --AC_DC"
1255 @end example
1257 @noindent
1258 When you use the same text in a macro argument, you must therefore have
1259 an extra quotation level (since one is stripped away by the macro
1260 substitution).  In general, then, it is a good idea to @emph{use double
1261 quoting for all literal string arguments}, either around just the
1262 problematic portions, or over the entire argument:
1264 @example
1265 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1266 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1267 @end example
1269 However, the above example triggers a warning about a possibly
1270 unexpanded macro when running @command{autoconf}, because it collides
1271 with the namespace of macros reserved for the Autoconf language.  To be
1272 really safe, you can use additional escaping (either a quadrigraph, or
1273 creative shell constructs) to silence that particular warning:
1275 @example
1276 echo "Hard rock was here!  --AC""_DC"
1277 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1278 @end example
1280 You are now able to understand one of the constructs of Autoconf that
1281 has been continually misunderstood@enddots{}  The rule of thumb is that
1282 @emph{whenever you expect macro expansion, expect quote expansion};
1283 i.e., expect one level of quotes to be lost.  For instance:
1285 @example
1286 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1287  [AC_MSG_ERROR([you lose])])
1288 @end example
1290 @noindent
1291 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1292 @samp{char b[10];} and is expanded once, which results in
1293 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1294 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1295 in Autoconf's past to
1296 address this issue via the M4 @code{changequote} primitive, but do not
1297 use it!)  Let's take a closer look: the author meant the first argument
1298 to be understood as a literal, and therefore it must be quoted twice;
1299 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1300 once so that it is only expanded after the rest of the body of
1301 @code{AC_COMPILE_IFELSE} is in place:
1303 @example
1304 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1305   [AC_MSG_ERROR([you lose])])
1306 @end example
1308 @noindent
1309 Voil@`a, you actually produce @samp{char b[10];} this time!
1311 On the other hand, descriptions (e.g., the last parameter of
1312 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1313 are subject to line breaking, for example---and should not be double quoted.
1314 Even if these descriptions are short and are not actually broken, double
1315 quoting them yields weird results.
1317 Some macros take optional arguments, which this documentation represents
1318 as @ovar{arg} (not to be confused with the quote characters).  You may
1319 just leave them empty, or use @samp{[]} to make the emptiness of the
1320 argument explicit, or you may simply omit the trailing commas.  The
1321 three lines below are equivalent:
1323 @example
1324 AC_CHECK_HEADERS([stdio.h], [], [], [])
1325 AC_CHECK_HEADERS([stdio.h],,,)
1326 AC_CHECK_HEADERS([stdio.h])
1327 @end example
1329 It is best to put each macro call on its own line in
1330 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1331 rely on the newline after the macro call to terminate the commands.
1332 This approach makes the generated @command{configure} script a little
1333 easier to read by not inserting lots of blank lines.  It is generally
1334 safe to set shell variables on the same line as a macro call, because
1335 the shell allows assignments without intervening newlines.
1337 You can include comments in @file{configure.ac} files by starting them
1338 with the @samp{#}.  For example, it is helpful to begin
1339 @file{configure.ac} files with a line like this:
1341 @example
1342 # Process this file with autoconf to produce a configure script.
1343 @end example
1345 @node Autoconf Input Layout
1346 @subsection Standard @file{configure.ac} Layout
1348 The order in which @file{configure.ac} calls the Autoconf macros is not
1349 important, with a few exceptions.  Every @file{configure.ac} must
1350 contain a call to @code{AC_INIT} before the checks, and a call to
1351 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1352 rely on other macros having been called first, because they check
1353 previously set values of some variables to decide what to do.  These
1354 macros are noted in the individual descriptions (@pxref{Existing
1355 Tests}), and they also warn you when @command{configure} is created if they
1356 are called out of order.
1358 To encourage consistency, here is a suggested order for calling the
1359 Autoconf macros.  Generally speaking, the things near the end of this
1360 list are those that could depend on things earlier in it.  For example,
1361 library functions could be affected by types and libraries.
1363 @display
1364 @group
1365 Autoconf requirements
1366 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1367 information on the package
1368 checks for programs
1369 checks for libraries
1370 checks for header files
1371 checks for types
1372 checks for structures
1373 checks for compiler characteristics
1374 checks for library functions
1375 checks for system services
1376 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1377 @code{AC_OUTPUT}
1378 @end group
1379 @end display
1382 @node autoscan Invocation
1383 @section Using @command{autoscan} to Create @file{configure.ac}
1384 @cindex @command{autoscan}
1386 The @command{autoscan} program can help you create and/or maintain a
1387 @file{configure.ac} file for a software package.  @command{autoscan}
1388 examines source files in the directory tree rooted at a directory given
1389 as a command line argument, or the current directory if none is given.
1390 It searches the source files for common portability problems and creates
1391 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1392 for that package, and checks a possibly existing @file{configure.ac} for
1393 completeness.
1395 When using @command{autoscan} to create a @file{configure.ac}, you
1396 should manually examine @file{configure.scan} before renaming it to
1397 @file{configure.ac}; it probably needs some adjustments.
1398 Occasionally, @command{autoscan} outputs a macro in the wrong order
1399 relative to another macro, so that @command{autoconf} produces a warning;
1400 you need to move such macros manually.  Also, if you want the package to
1401 use a configuration header file, you must add a call to
1402 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1403 also have to change or add some @code{#if} directives to your program in
1404 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1405 information about a program that can help with that job).
1407 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1408 consider adding its suggestions.  The file @file{autoscan.log}
1409 contains detailed information on why a macro is requested.
1411 @command{autoscan} uses several data files (installed along with Autoconf)
1412 to determine which macros to output when it finds particular symbols in
1413 a package's source files.  These data files all have the same format:
1414 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1415 output if that symbol is encountered.  Lines starting with @samp{#} are
1416 comments.
1418 @command{autoscan} accepts the following options:
1420 @table @option
1421 @item --help
1422 @itemx -h
1423 Print a summary of the command line options and exit.
1425 @item --version
1426 @itemx -V
1427 Print the version number of Autoconf and exit.
1429 @item --verbose
1430 @itemx -v
1431 Print the names of the files it examines and the potentially interesting
1432 symbols it finds in them.  This output can be voluminous.
1434 @item --debug
1435 @itemx -d
1436 Don't remove temporary files.
1438 @item --include=@var{dir}
1439 @itemx -I @var{dir}
1440 Append @var{dir} to the include path.  Multiple invocations accumulate.
1442 @item --prepend-include=@var{dir}
1443 @itemx -B @var{dir}
1444 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1445 @end table
1447 @node ifnames Invocation
1448 @section Using @command{ifnames} to List Conditionals
1449 @cindex @command{ifnames}
1451 @command{ifnames} can help you write @file{configure.ac} for a software
1452 package.  It prints the identifiers that the package already uses in C
1453 preprocessor conditionals.  If a package has already been set up to have
1454 some portability, @command{ifnames} can thus help you figure out what its
1455 @command{configure} needs to check for.  It may help fill in some gaps in a
1456 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1457 Invocation}).
1459 @command{ifnames} scans all of the C source files named on the command line
1460 (or the standard input, if none are given) and writes to the standard
1461 output a sorted list of all the identifiers that appear in those files
1462 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1463 directives.  It prints each identifier on a line, followed by a
1464 space-separated list of the files in which that identifier occurs.
1466 @noindent
1467 @command{ifnames} accepts the following options:
1469 @table @option
1470 @item --help
1471 @itemx -h
1472 Print a summary of the command line options and exit.
1474 @item --version
1475 @itemx -V
1476 Print the version number of Autoconf and exit.
1477 @end table
1479 @node autoconf Invocation
1480 @section Using @command{autoconf} to Create @command{configure}
1481 @cindex @command{autoconf}
1483 To create @command{configure} from @file{configure.ac}, run the
1484 @command{autoconf} program with no arguments.  @command{autoconf} processes
1485 @file{configure.ac} with the M4 macro processor, using the
1486 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1487 file instead of @file{configure.ac} and writes the configuration script
1488 to the standard output instead of to @command{configure}.  If you give
1489 @command{autoconf} the argument @option{-}, it reads from the standard
1490 input instead of @file{configure.ac} and writes the configuration script
1491 to the standard output.
1493 The Autoconf macros are defined in several files.  Some of the files are
1494 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1495 looks for the optional file @file{acsite.m4} in the directory that
1496 contains the distributed Autoconf macro files, and for the optional file
1497 @file{aclocal.m4} in the current directory.  Those files can contain
1498 your site's or the package's own Autoconf macro definitions
1499 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1500 defined in more than one of the files that @command{autoconf} reads, the
1501 last definition it reads overrides the earlier ones.
1503 @command{autoconf} accepts the following options:
1505 @table @option
1506 @item --help
1507 @itemx -h
1508 Print a summary of the command line options and exit.
1510 @item --version
1511 @itemx -V
1512 Print the version number of Autoconf and exit.
1514 @item --verbose
1515 @itemx -v
1516 Report processing steps.
1518 @item --debug
1519 @itemx -d
1520 Don't remove the temporary files.
1522 @item --force
1523 @itemx -f
1524 Remake @file{configure} even if newer than its input files.
1526 @item --include=@var{dir}
1527 @itemx -I @var{dir}
1528 Append @var{dir} to the include path.  Multiple invocations accumulate.
1530 @item --prepend-include=@var{dir}
1531 @itemx -B @var{dir}
1532 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1534 @item --output=@var{file}
1535 @itemx -o @var{file}
1536 Save output (script or trace) to @var{file}.  The file @option{-} stands
1537 for the standard output.
1539 @item --warnings=@var{category}
1540 @itemx -W @var{category}
1541 @evindex WARNINGS
1542 Report the warnings related to @var{category} (which can actually be a
1543 comma separated list).  @xref{Reporting Messages}, macro
1544 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1545 values include:
1547 @table @samp
1548 @item all
1549 report all the warnings
1551 @item none
1552 report none
1554 @item error
1555 treats warnings as errors
1557 @item no-@var{category}
1558 disable warnings falling into @var{category}
1559 @end table
1561 Warnings about @samp{syntax} are enabled by default, and the environment
1562 variable @env{WARNINGS}, a comma separated list of categories, is
1563 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1564 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1565 disable the defaults and @env{WARNINGS}, and then
1566 enable warnings about obsolete constructs, use @option{-W
1567 none,obsolete}.
1569 @cindex Back trace
1570 @cindex Macro invocation stack
1571 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1572 displays a back trace for errors, but not for warnings; if you want
1573 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1574 examples.
1576 @item --trace=@var{macro}[:@var{format}]
1577 @itemx -t @var{macro}[:@var{format}]
1578 Do not create the @command{configure} script, but list the calls to
1579 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1580 arguments can be used to list several macros.  Multiple @option{--trace}
1581 arguments for a single macro are not cumulative; instead, you should
1582 just make @var{format} as long as needed.
1584 The @var{format} is a regular string, with newlines if desired, and
1585 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1586 @ref{autom4te Invocation}, for details on the @var{format}.
1588 @item --initialization
1589 @itemx -i
1590 By default, @option{--trace} does not trace the initialization of the
1591 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1592 results in a noticeable speedup, but can be disabled by this option.
1593 @end table
1596 It is often necessary to check the content of a @file{configure.ac}
1597 file, but parsing it yourself is extremely fragile and error-prone.  It
1598 is suggested that you rely upon @option{--trace} to scan
1599 @file{configure.ac}.  For instance, to find the list of variables that
1600 are substituted, use:
1602 @example
1603 @group
1604 $ @kbd{autoconf -t AC_SUBST}
1605 configure.ac:2:AC_SUBST:ECHO_C
1606 configure.ac:2:AC_SUBST:ECHO_N
1607 configure.ac:2:AC_SUBST:ECHO_T
1608 @i{More traces deleted}
1609 @end group
1610 @end example
1612 @noindent
1613 The example below highlights the difference between @samp{$@@},
1614 @samp{$*}, and @samp{$%}.
1616 @example
1617 @group
1618 $ @kbd{cat configure.ac}
1619 AC_DEFINE(This, is, [an
1620 [example]])
1621 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1622 *: $*
1623 %: $%'
1624 @@: [This],[is],[an
1625 [example]]
1626 *: This,is,an
1627 [example]
1628 %: This:is:an [example]
1629 @end group
1630 @end example
1632 @noindent
1633 The @var{format} gives you a lot of freedom:
1635 @example
1636 @group
1637 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1638 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1639 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1640 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1641 @i{More traces deleted}
1642 @end group
1643 @end example
1645 @noindent
1646 A long @var{separator} can be used to improve the readability of complex
1647 structures, and to ease their parsing (for instance when no single
1648 character is suitable as a separator):
1650 @example
1651 @group
1652 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1653 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1654 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1655 AUTOMAKE|:::::|automake|:::::|$missing_dir
1656 @i{More traces deleted}
1657 @end group
1658 @end example
1660 @node autoreconf Invocation
1661 @section Using @command{autoreconf} to Update @command{configure} Scripts
1662 @cindex @command{autoreconf}
1664 Installing the various components of the GNU Build System can be
1665 tedious: running @command{autopoint} for Gettext, @command{automake} for
1666 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1667 because some tools such as @command{automake} have been updated on your
1668 system, or because some of the sources such as @file{configure.ac} have
1669 been updated, or finally, simply in order to install the GNU Build
1670 System in a fresh tree.
1672 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1673 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1674 @command{autopoint} (when appropriate) repeatedly to update the
1675 GNU Build System in the specified directories and their
1676 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1677 those files that are older than their sources.  The environment variables
1678 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1679 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1680 may be used to override the invocation of the respective tools.
1682 If you install a new version of some tool, you can make
1683 @command{autoreconf} remake @emph{all} of the files by giving it the
1684 @option{--force} option.
1686 @xref{Automatic Remaking}, for Make rules to automatically
1687 rebuild @command{configure} scripts when their source files change.  That
1688 method handles the timestamps of configuration header templates
1689 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1690 @option{--localdir=@var{dir}}.
1692 @cindex Gettext
1693 @cindex @command{autopoint}
1694 Gettext supplies the @command{autopoint} command to add translation
1695 infrastructure to a source package.  If you use @command{autopoint},
1696 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1697 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1698 Invocation, , Invoking the @code{autopoint} Program, gettext,
1699 GNU @code{gettext} utilities}, for further details.
1701 @noindent
1702 @command{autoreconf} accepts the following options:
1704 @table @option
1705 @item --help
1706 @itemx -h
1707 Print a summary of the command line options and exit.
1709 @item --version
1710 @itemx -V
1711 Print the version number of Autoconf and exit.
1713 @item --verbose
1714 @itemx -v
1715 Print the name of each directory @command{autoreconf} examines and the
1716 commands it runs.  If given two or more times, pass @option{--verbose}
1717 to subordinate tools that support it.
1719 @item --debug
1720 @itemx -d
1721 Don't remove the temporary files.
1723 @item --force
1724 @itemx -f
1725 Remake even @file{configure} scripts and configuration headers that are
1726 newer than their input files (@file{configure.ac} and, if present,
1727 @file{aclocal.m4}).
1729 @item --install
1730 @itemx -i
1731 Install the missing auxiliary files in the package.  By default, files
1732 are copied; this can be changed with @option{--symlink}.
1734 If deemed appropriate, this option triggers calls to
1735 @samp{automake --add-missing},
1736 @samp{libtoolize}, @samp{autopoint}, etc.
1738 @item --no-recursive
1739 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1740 macro @code{AC_CONFIG_SUBDIRS}).
1742 @item --symlink
1743 @itemx -s
1744 When used with @option{--install}, install symbolic links to the missing
1745 auxiliary files instead of copying them.
1747 @item --make
1748 @itemx -m
1749 When the directories were configured, update the configuration by
1750 running @samp{./config.status --recheck && ./config.status}, and then
1751 run @samp{make}.
1753 @item --include=@var{dir}
1754 @itemx -I @var{dir}
1755 Append @var{dir} to the include path.  Multiple invocations accumulate.
1756 Passed on to @command{aclocal}, @command{autoconf} and
1757 @command{autoheader} internally.
1759 @item --prepend-include=@var{dir}
1760 @itemx -B @var{dir}
1761 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1762 Passed on to @command{autoconf} and @command{autoheader} internally.
1764 @item --warnings=@var{category}
1765 @itemx -W @var{category}
1766 @evindex WARNINGS
1767 Report the warnings related to @var{category} (which can actually be a
1768 comma separated list).
1770 @table @samp
1771 @item cross
1772 related to cross compilation issues.
1774 @item obsolete
1775 report the uses of obsolete constructs.
1777 @item portability
1778 portability issues
1780 @item syntax
1781 dubious syntactic constructs.
1783 @item all
1784 report all the warnings
1786 @item none
1787 report none
1789 @item error
1790 treats warnings as errors
1792 @item no-@var{category}
1793 disable warnings falling into @var{category}
1794 @end table
1796 Warnings about @samp{syntax} are enabled by default, and the environment
1797 variable @env{WARNINGS}, a comma separated list of categories, is
1798 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1799 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1800 disable the defaults and @env{WARNINGS}, and then
1801 enable warnings about obsolete constructs, use @option{-W
1802 none,obsolete}.
1803 @end table
1805 If you want @command{autoreconf} to pass flags that are not listed here
1806 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1807 Due to a limitation in the Autoconf implementation these flags currently
1808 must be set on a single line in @file{Makefile.am}, without any
1809 backslash-newlines.
1811 @c ========================================= Initialization and Output Files.
1813 @node Setup
1814 @chapter Initialization and Output Files
1816 Autoconf-generated @command{configure} scripts need some information about
1817 how to initialize, such as how to find the package's source files and
1818 about the output files to produce.  The following sections describe the
1819 initialization and the creation of output files.
1821 @menu
1822 * Initializing configure::      Option processing etc.
1823 * Versioning::                  Dealing with Autoconf versions
1824 * Notices::                     Copyright, version numbers in @command{configure}
1825 * Input::                       Where Autoconf should find files
1826 * Output::                      Outputting results from the configuration
1827 * Configuration Actions::       Preparing the output based on results
1828 * Configuration Files::         Creating output files
1829 * Makefile Substitutions::      Using output variables in makefiles
1830 * Configuration Headers::       Creating a configuration header file
1831 * Configuration Commands::      Running arbitrary instantiation commands
1832 * Configuration Links::         Links depending on the configuration
1833 * Subdirectories::              Configuring independent packages together
1834 * Default Prefix::              Changing the default installation prefix
1835 @end menu
1837 @node Initializing configure
1838 @section Initializing @command{configure}
1840 Every @command{configure} script must call @code{AC_INIT} before doing
1841 anything else that produces output.  Calls to silent macros, such as
1842 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1843 are generally used via @file{aclocal.m4}, since that is implicitly
1844 included before the start of @file{configure.ac}.  The only other
1845 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1847 @anchor{AC_INIT}
1848 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1849   @ovar{tarname}, @ovar{url})
1850 @acindex{INIT}
1851 Process any command-line arguments and perform various initializations
1852 and verifications.
1854 Set the name of the @var{package} and its @var{version}.  These are
1855 typically used in @option{--version} support, including that of
1856 @command{configure}.  The optional argument @var{bug-report} should be
1857 the email to which users should send bug reports.  The package
1858 @var{tarname} differs from @var{package}: the latter designates the full
1859 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1860 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1861 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1862 other than alphanumerics and underscores are changed to @samp{-}.  If
1863 provided, @var{url} should be the home page for the package.
1865 The arguments of @code{AC_INIT} must be static, i.e., there should not
1866 be any shell computation, quotes, or newlines, but they can be computed
1867 by M4.  This is because the package information strings are expanded at
1868 M4 time into several contexts, and must give the same text at shell time
1869 whether used in single-quoted strings, double-quoted strings, quoted
1870 here-documents, or unquoted here-documents.  It is permissible to use
1871 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1872 that changes with every commit to a version control system (in fact,
1873 Autoconf does just that, for all builds of the development tree made
1874 between releases).
1876 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1877 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1878 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1880 @table @asis
1881 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1882 @acindex{PACKAGE_NAME}
1883 @ovindex PACKAGE_NAME
1884 @cvindex PACKAGE_NAME
1885 Exactly @var{package}.
1887 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1888 @acindex{PACKAGE_TARNAME}
1889 @ovindex PACKAGE_TARNAME
1890 @cvindex PACKAGE_TARNAME
1891 Exactly @var{tarname}, possibly generated from @var{package}.
1893 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1894 @acindex{PACKAGE_VERSION}
1895 @ovindex PACKAGE_VERSION
1896 @cvindex PACKAGE_VERSION
1897 Exactly @var{version}.
1899 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1900 @acindex{PACKAGE_STRING}
1901 @ovindex PACKAGE_STRING
1902 @cvindex PACKAGE_STRING
1903 Exactly @samp{@var{package} @var{version}}.
1905 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1906 @acindex{PACKAGE_BUGREPORT}
1907 @ovindex PACKAGE_BUGREPORT
1908 @cvindex PACKAGE_BUGREPORT
1909 Exactly @var{bug-report}, if one was provided.  Typically an email
1910 address, or URL to a bug management web page.
1912 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1913 @acindex{PACKAGE_URL}
1914 @ovindex PACKAGE_URL
1915 @cvindex PACKAGE_URL
1916 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1917 @var{package} begins with @samp{GNU }, then this defaults to
1918 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1919 assumed.
1920 @end table
1921 @end defmac
1923 If your @command{configure} script does its own option processing, it
1924 should inspect @samp{$@@} or @samp{$*} immediately after calling
1925 @code{AC_INIT}, because other Autoconf macros liberally use the
1926 @command{set} command to process strings, and this has the side effect
1927 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1928 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1929 implement your own option processing.  @xref{Site Configuration}.
1931 @node Versioning
1932 @section Dealing with Autoconf versions
1933 @cindex Autoconf version
1934 @cindex version, Autoconf
1936 The following optional macros can be used to help choose the minimum
1937 version of Autoconf that can successfully compile a given
1938 @file{configure.ac}.
1940 @defmac AC_PREREQ (@var{version})
1941 @acindex{PREREQ}
1942 @cindex Version
1943 Ensure that a recent enough version of Autoconf is being used.  If the
1944 version of Autoconf being used to create @command{configure} is
1945 earlier than @var{version}, print an error message to the standard
1946 error output and exit with failure (exit status is 63).  For example:
1948 @example
1949 AC_PREREQ([@value{VERSION}])
1950 @end example
1952 This macro may be used before @code{AC_INIT}.
1953 @end defmac
1955 @defmac AC_AUTOCONF_VERSION
1956 @acindex{AUTOCONF_VERSION}
1957 This macro was introduced in Autoconf 2.62.  It identifies the version
1958 of Autoconf that is currently parsing the input file, in a format
1959 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1960 other words, for this release of Autoconf, its value is
1961 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1962 conditional fallbacks based on when a feature was added to Autoconf,
1963 rather than using @code{AC_PREREQ} to require the newer version of
1964 Autoconf.  However, remember that the Autoconf philosophy favors feature
1965 checks over version checks.
1967 You should not expand this macro directly; use
1968 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1969 users might
1970 have a beta version of Autoconf installed, with arbitrary letters
1971 included in its version string.  This means it is possible for the
1972 version string to contain the name of a defined macro, such that
1973 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1974 macro during rescanning, and change the version string to be different
1975 than what you intended to check.
1976 @end defmac
1978 @node Notices
1979 @section Notices in @command{configure}
1980 @cindex Notices in @command{configure}
1982 The following macros manage version numbers for @command{configure}
1983 scripts.  Using them is optional.
1985 @defmac AC_COPYRIGHT (@var{copyright-notice})
1986 @acindex{COPYRIGHT}
1987 @cindex Copyright Notice
1988 State that, in addition to the Free Software Foundation's copyright on
1989 the Autoconf macros, parts of your @command{configure} are covered by the
1990 @var{copyright-notice}.
1992 The @var{copyright-notice} shows up in both the head of
1993 @command{configure} and in @samp{configure --version}.
1994 @end defmac
1997 @defmac AC_REVISION (@var{revision-info})
1998 @acindex{REVISION}
1999 @cindex Revision
2000 Copy revision stamp @var{revision-info} into the @command{configure}
2001 script, with any dollar signs or double-quotes removed.  This macro lets
2002 you put a revision stamp from @file{configure.ac} into @command{configure}
2003 without RCS or CVS changing it when you check in
2004 @command{configure}.  That way, you can determine easily which revision of
2005 @file{configure.ac} a particular @command{configure} corresponds to.
2007 For example, this line in @file{configure.ac}:
2009 @c The @w prevents RCS from changing the example in the manual.
2010 @example
2011 AC_REVISION([@w{$}Revision: 1.30 $])
2012 @end example
2014 @noindent
2015 produces this in @command{configure}:
2017 @example
2018 #!/bin/sh
2019 # From configure.ac Revision: 1.30
2020 @end example
2021 @end defmac
2024 @node Input
2025 @section Finding @command{configure} Input
2027 @anchor{AC_CONFIG_SRCDIR}
2028 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2029 @acindex{CONFIG_SRCDIR}
2030 @var{unique-file-in-source-dir} is some file that is in the package's
2031 source directory; @command{configure} checks for this file's existence to
2032 make sure that the directory that it is told contains the source code in
2033 fact does.  Occasionally people accidentally specify the wrong directory
2034 with @option{--srcdir}; this is a safety check.  @xref{configure
2035 Invocation}, for more information.
2036 @end defmac
2039 @c FIXME: Remove definitively once --install explained.
2041 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2042 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2043 @c to split the macros in several files.  In this case, Autoconf must be
2044 @c told which files to load, and in which order.
2046 @c @defmac AC_INCLUDE (@var{file}@dots{})
2047 @c @acindex{INCLUDE}
2048 @c @c FIXME: There is no longer shell globbing.
2049 @c Read the macro definitions that appear in the listed files.  A list of
2050 @c space-separated file names or shell globbing patterns is expected.  The
2051 @c files are read in the order they're listed.
2053 @c Because the order of definition of macros is important (only the last
2054 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2055 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2056 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2057 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2058 @c the latter case, non-macro lines from included files may end up in the
2059 @c @file{configure} script, whereas in the former case, they'd be discarded
2060 @c just like any text that appear before @code{AC_INIT}.
2061 @c @end defmac
2063 Packages that do manual configuration or use the @command{install} program
2064 might need to tell @command{configure} where to find some other shell
2065 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2066 it looks are correct for most cases.
2068 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2069 @acindex{CONFIG_AUX_DIR}
2070 Use the auxiliary build tools (e.g., @file{install-sh},
2071 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2072 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2073 These are auxiliary files used in configuration.  @var{dir} can be
2074 either absolute or relative to @file{@var{srcdir}}.  The default is
2075 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2076 @file{@var{srcdir}/../..}, whichever is the first that contains
2077 @file{install-sh}.  The other files are not checked for, so that using
2078 @code{AC_PROG_INSTALL} does not automatically require distributing the
2079 other auxiliary files.  It checks for @file{install.sh} also, but that
2080 name is obsolete because some @command{make} have a rule that creates
2081 @file{install} from it if there is no makefile.
2083 The auxiliary directory is commonly named @file{build-aux}.
2084 If you need portability to DOS variants, do not name the
2085 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2086 @end defmac
2088 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2089 @acindex{REQUIRE_AUX_FILE}
2090 Declares that @var{file} is expected in the directory defined above.  In
2091 Autoconf proper, this macro does nothing: its sole purpose is to be
2092 traced by third-party tools to produce a list of expected auxiliary
2093 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2094 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2095 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2096 @end defmac
2098 Similarly, packages that use @command{aclocal} should declare where
2099 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2101 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2102 @acindex{CONFIG_MACRO_DIR}
2103 Specify @var{dir} as the location of additional local Autoconf macros.
2104 This macro is intended for use by future versions of commands like
2105 @command{autoreconf} that trace macro calls.  It should be called
2106 directly from @file{configure.ac} so that tools that install macros for
2107 @command{aclocal} can find the macros' declarations.
2109 Note that if you use @command{aclocal} from Automake to generate
2110 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2111 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2112 the Autoconf implementation of @command{autoreconf}, these include
2113 directives currently must be set on a single line in @file{Makefile.am},
2114 without any backslash-newlines.
2115 @end defmac
2118 @node Output
2119 @section Outputting Files
2120 @cindex Outputting files
2122 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2123 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2124 @file{config.status}, which in turn creates the makefiles and any
2125 other files resulting from configuration.  This is the only required
2126 macro besides @code{AC_INIT} (@pxref{Input}).
2128 @anchor{AC_OUTPUT}
2129 @defmac AC_OUTPUT
2130 @acindex{OUTPUT}
2131 @cindex Instantiation
2132 Generate @file{config.status} and launch it.  Call this macro once, at
2133 the end of @file{configure.ac}.
2135 @file{config.status} performs all the configuration actions: all the
2136 output files (see @ref{Configuration Files}, macro
2137 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2138 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2139 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2140 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2141 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2142 are honored.
2144 The location of your @code{AC_OUTPUT} invocation is the exact point
2145 where configuration actions are taken: any code afterwards is
2146 executed by @command{configure} once @command{config.status} was run.  If
2147 you want to bind actions to @command{config.status} itself
2148 (independently of whether @command{configure} is being run), see
2149 @ref{Configuration Commands, , Running Arbitrary Configuration
2150 Commands}.
2151 @end defmac
2153 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2154 @xref{Obsolete Macros}, for a description of the arguments that
2155 @code{AC_OUTPUT} used to support.
2158 If you run @command{make} in subdirectories, you should run it using the
2159 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2160 @code{MAKE} to the name of the @command{make} program plus any options it
2161 was given.  (But many do not include in it the values of any variables
2162 set on the command line, so those are not passed on automatically.)
2163 Some old versions of @command{make} do not set this variable.  The
2164 following macro allows you to use it even with those versions.
2166 @anchor{AC_PROG_MAKE_SET}
2167 @defmac AC_PROG_MAKE_SET
2168 @acindex{PROG_MAKE_SET}
2169 @ovindex SET_MAKE
2170 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2171 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2172 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2173 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2174 @code{SET_MAKE}.
2175 @end defmac
2177 If you use this macro, place a line like this in each @file{Makefile.in}
2178 that runs @command{MAKE} on other directories:
2180 @example
2181 @@SET_MAKE@@
2182 @end example
2186 @node Configuration Actions
2187 @section Performing Configuration Actions
2188 @cindex Configuration actions
2190 @file{configure} is designed so that it appears to do everything itself,
2191 but there is actually a hidden slave: @file{config.status}.
2192 @file{configure} is in charge of examining your system, but it is
2193 @file{config.status} that actually takes the proper actions based on the
2194 results of @file{configure}.  The most typical task of
2195 @file{config.status} is to @emph{instantiate} files.
2197 @acindex{CONFIG_@var{ITEMS}}
2198 This section describes the common behavior of the four standard
2199 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2200 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2201 have this prototype:
2203 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2204 @c awful.
2205 @example
2206 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2207 @end example
2209 @noindent
2210 where the arguments are:
2212 @table @var
2213 @item tag@dots{}
2214 A blank-or-newline-separated list of tags, which are typically the names of
2215 the files to instantiate.
2217 You are encouraged to use literals as @var{tags}.  In particular, you
2218 should avoid
2220 @example
2221 @dots{} && my_foos="$my_foos fooo"
2222 @dots{} && my_foos="$my_foos foooo"
2223 AC_CONFIG_@var{ITEMS}([$my_foos])
2224 @end example
2226 @noindent
2227 and use this instead:
2229 @example
2230 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2231 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2232 @end example
2234 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2235 special @var{tag} values: they may have the form @samp{@var{output}} or
2236 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2237 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2239 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2240 for example, asks for
2241 the creation of the file @file{Makefile} that contains the expansion of the
2242 output variables in the concatenation of @file{boiler/top.mk} and
2243 @file{boiler/bot.mk}.
2245 The special value @samp{-} might be used to denote the standard output
2246 when used in @var{output}, or the standard input when used in the
2247 @var{inputs}.  You most probably don't need to use this in
2248 @file{configure.ac}, but it is convenient when using the command line
2249 interface of @file{./config.status}, see @ref{config.status Invocation},
2250 for more details.
2252 The @var{inputs} may be absolute or relative file names.  In the latter
2253 case they are first looked for in the build tree, and then in the source
2254 tree.  Input files should be text files, and a line length below 2000
2255 bytes should be safe.
2257 @item commands
2258 Shell commands output literally into @file{config.status}, and
2259 associated with a tag that the user can use to tell @file{config.status}
2260 which commands to run.  The commands are run each time a @var{tag}
2261 request is given to @file{config.status}, typically each time the file
2262 @file{@var{tag}} is created.
2264 The variables set during the execution of @command{configure} are
2265 @emph{not} available here: you first need to set them via the
2266 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2268 @table @code
2269 @item srcdir
2270 @vrindex srcdir
2271 The name of the top source directory, assuming that the working
2272 directory is the top build directory.  This
2273 is what the @command{configure} option @option{--srcdir} sets.
2275 @item ac_top_srcdir
2276 @vrindex ac_top_srcdir
2277 The name of the top source directory, assuming that the working
2278 directory is the current build directory.
2280 @item ac_top_build_prefix
2281 @vrindex ac_top_build_prefix
2282 The name of the top build directory, assuming that the working
2283 directory is the current build directory.
2284 It can be empty, or else ends with a slash, so that you may concatenate
2287 @item ac_srcdir
2288 @vrindex ac_srcdir
2289 The name of the corresponding source directory, assuming that the
2290 working directory is the current build directory.
2292 @item tmp
2293 @vrindex tmp
2294 The name of a temporary directory within the build tree, which you
2295 can use if you need to create additional temporary files.  The
2296 directory is cleaned up when @command{config.status} is done or
2297 interrupted.  Please use package-specific file name prefixes to
2298 avoid clashing with files that @command{config.status} may use
2299 internally.
2300 @end table
2302 @noindent
2303 The @dfn{current} directory refers to the directory (or
2304 pseudo-directory) containing the input part of @var{tags}.  For
2305 instance, running
2307 @example
2308 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2309 @end example
2311 @noindent
2312  with @option{--srcdir=../package} produces the following values:
2314 @example
2315 # Argument of --srcdir
2316 srcdir='../package'
2317 # Reversing deep/dir
2318 ac_top_build_prefix='../../'
2319 # Concatenation of $ac_top_build_prefix and srcdir
2320 ac_top_srcdir='../../../package'
2321 # Concatenation of $ac_top_srcdir and deep/dir
2322 ac_srcdir='../../../package/deep/dir'
2323 @end example
2325 @noindent
2326 independently of @samp{in/in.in}.
2328 @item init-cmds
2329 Shell commands output @emph{unquoted} near the beginning of
2330 @file{config.status}, and executed each time @file{config.status} runs
2331 (regardless of the tag).  Because they are unquoted, for example,
2332 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2333 is typically used by @file{configure} to give @file{config.status} some
2334 variables it needs to run the @var{commands}.
2336 You should be extremely cautious in your variable names: all the
2337 @var{init-cmds} share the same name space and may overwrite each other
2338 in unpredictable ways.  Sorry@enddots{}
2339 @end table
2341 All these macros can be called multiple times, with different
2342 @var{tag} values, of course!
2345 @node Configuration Files
2346 @section Creating Configuration Files
2347 @cindex Creating configuration files
2348 @cindex Configuration file creation
2350 Be sure to read the previous section, @ref{Configuration Actions}.
2352 @anchor{AC_CONFIG_FILES}
2353 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2354 @acindex{CONFIG_FILES}
2355 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2356 file (by default @file{@var{file}.in}), substituting the output variable
2357 values.
2358 @c Before we used to have this feature, which was later rejected
2359 @c because it complicates the writing of makefiles:
2360 @c If the file would be unchanged, it is left untouched, to preserve
2361 @c timestamp.
2362 This macro is one of the instantiating macros; see @ref{Configuration
2363 Actions}.  @xref{Makefile Substitutions}, for more information on using
2364 output variables.  @xref{Setting Output Variables}, for more information
2365 on creating them.  This macro creates the directory that the file is in
2366 if it doesn't exist.  Usually, makefiles are created this way,
2367 but other files, such as @file{.gdbinit}, can be specified as well.
2369 Typical calls to @code{AC_CONFIG_FILES} look like this:
2371 @example
2372 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2373 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2374 @end example
2376 You can override an input file name by appending to @var{file} a
2377 colon-separated list of input files.  Examples:
2379 @example
2380 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2381                 [lib/Makefile:boiler/lib.mk])
2382 @end example
2384 @noindent
2385 Doing this allows you to keep your file names acceptable to
2386 DOS variants, or
2387 to prepend and/or append boilerplate to the file.
2388 @end defmac
2392 @node Makefile Substitutions
2393 @section Substitutions in Makefiles
2394 @cindex Substitutions in makefiles
2395 @cindex Makefile substitutions
2397 Each subdirectory in a distribution that contains something to be
2398 compiled or installed should come with a file @file{Makefile.in}, from
2399 which @command{configure} creates a file @file{Makefile} in that directory.
2400 To create @file{Makefile}, @command{configure} performs a simple variable
2401 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2402 @file{Makefile.in} with the value that @command{configure} has determined
2403 for that variable.  Variables that are substituted into output files in
2404 this way are called @dfn{output variables}.  They are ordinary shell
2405 variables that are set in @command{configure}.  To make @command{configure}
2406 substitute a particular variable into the output files, the macro
2407 @code{AC_SUBST} must be called with that variable name as an argument.
2408 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2409 left unchanged.  @xref{Setting Output Variables}, for more information
2410 on creating output variables with @code{AC_SUBST}.
2412 A software package that uses a @command{configure} script should be
2413 distributed with a file @file{Makefile.in}, but no makefile; that
2414 way, the user has to properly configure the package for the local system
2415 before compiling it.
2417 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2418 GNU Coding Standards}, for more information on what to put in
2419 makefiles.
2421 @menu
2422 * Preset Output Variables::     Output variables that are always set
2423 * Installation Directory Variables::  Other preset output variables
2424 * Changed Directory Variables::  Warnings about @file{datarootdir}
2425 * Build Directories::           Supporting multiple concurrent compiles
2426 * Automatic Remaking::          Makefile rules for configuring
2427 @end menu
2429 @node Preset Output Variables
2430 @subsection Preset Output Variables
2431 @cindex Output variables
2433 Some output variables are preset by the Autoconf macros.  Some of the
2434 Autoconf macros set additional output variables, which are mentioned in
2435 the descriptions for those macros.  @xref{Output Variable Index}, for a
2436 complete list of output variables.  @xref{Installation Directory
2437 Variables}, for the list of the preset ones related to installation
2438 directories.  Below are listed the other preset ones, many of which are
2439 precious variables (@pxref{Setting Output Variables},
2440 @code{AC_ARG_VAR}).
2442 The preset variables which are available during @file{config.status}
2443 (@pxref{Configuration Actions}) may also be used during
2444 @command{configure} tests.  For example, it is permissible to reference
2445 @samp{$srcdir} when constructing a list of directories to pass via
2446 option @option{-I} during a compiler feature check.  When used in this
2447 manner, coupled with the fact that @command{configure} is always run
2448 from the top build directory, it is sufficient to use just
2449 @samp{$srcdir} instead of @samp{$top_srcdir}.
2451 @c Just say no to ASCII sorting!  We're humans, not computers.
2452 @c These variables are listed as they would be in a dictionary:
2453 @c actor
2454 @c Actress
2455 @c actress
2457 @defvar CFLAGS
2458 @evindex CFLAGS
2459 @ovindex CFLAGS
2460 Debugging and optimization options for the C compiler.  If it is not set
2461 in the environment when @command{configure} runs, the default value is set
2462 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2463 uses this variable when compiling or linking programs to test for C features.
2465 If a compiler option affects only the behavior of the preprocessor
2466 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2467 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2468 it should be put into @code{LDFLAGS} instead.  If it
2469 affects only the compiler proper, @code{CFLAGS} is the natural home for
2470 it.  If an option affects multiple phases of the compiler, though,
2471 matters get tricky.  One approach to put such options directly into
2472 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2473 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2475 However, remember that some @file{Makefile} variables are reserved by
2476 the GNU Coding Standards for the use of the ``user''---the person
2477 building the package.  For instance, @code{CFLAGS} is one such variable.
2479 Sometimes package developers are tempted to set user variables such as
2480 @code{CFLAGS} because it appears to make their job easier.  However, the
2481 package itself should never set a user variable, particularly not to
2482 include switches that are required for proper compilation of the
2483 package.  Since these variables are documented as being for the package
2484 builder, that person rightfully expects to be able to override any of
2485 these variables at build time.  If the package developer needs to add
2486 switches without interfering with the user, the proper way to do that is
2487 to introduce an additional variable.  Automake makes this easy by
2488 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2489 automake, GNU Automake}), but the concept is the same even if
2490 Automake is not used.
2491 @end defvar
2493 @defvar configure_input
2494 @ovindex configure_input
2495 A comment saying that the file was generated automatically by
2496 @command{configure} and giving the name of the input file.
2497 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2498 of every makefile it creates.  For other files, you should
2499 reference this variable in a comment at the top of each input file.  For
2500 example, an input shell script should begin like this:
2502 @example
2503 #!/bin/sh
2504 # @@configure_input@@
2505 @end example
2507 @noindent
2508 The presence of that line also reminds people editing the file that it
2509 needs to be processed by @command{configure} in order to be used.
2510 @end defvar
2512 @defvar CPPFLAGS
2513 @evindex CPPFLAGS
2514 @ovindex CPPFLAGS
2515 Preprocessor options for the C, C++, Objective C, and Objective C++
2516 preprocessors and compilers.  If
2517 it is not set in the environment when @command{configure} runs, the default
2518 value is empty.  @command{configure} uses this variable when preprocessing
2519 or compiling programs to test for C, C++, Objective C, and Objective C++
2520 features.
2522 This variable's contents should contain options like @option{-I},
2523 @option{-D}, and @option{-U} that affect only the behavior of the
2524 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2525 can do if an option affects other phases of the compiler as well.
2527 Currently, @command{configure} always links as part of a single
2528 invocation of the compiler that also preprocesses and compiles, so it
2529 uses this variable also when linking programs.  However, it is unwise to
2530 depend on this behavior because the GNU Coding Standards do
2531 not require it and many packages do not use @code{CPPFLAGS} when linking
2532 programs.
2534 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2535 might run into.
2536 @end defvar
2538 @defvar CXXFLAGS
2539 @evindex CXXFLAGS
2540 @ovindex CXXFLAGS
2541 Debugging and optimization options for the C++ compiler.  It acts like
2542 @code{CFLAGS}, but for C++ instead of C.
2543 @end defvar
2545 @defvar DEFS
2546 @ovindex DEFS
2547 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2548 is called, @command{configure} replaces @samp{@@DEFS@@} with
2549 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2550 variable is not defined while @command{configure} is performing its tests,
2551 only when creating the output files.  @xref{Setting Output Variables}, for
2552 how to check the results of previous tests.
2553 @end defvar
2555 @defvar ECHO_C
2556 @defvarx ECHO_N
2557 @defvarx ECHO_T
2558 @ovindex ECHO_C
2559 @ovindex ECHO_N
2560 @ovindex ECHO_T
2561 How does one suppress the trailing newline from @command{echo} for
2562 question-answer message pairs?  These variables provide a way:
2564 @example
2565 echo $ECHO_N "And the winner is... $ECHO_C"
2566 sleep 100000000000
2567 echo "$@{ECHO_T@}dead."
2568 @end example
2570 @noindent
2571 Some old and uncommon @command{echo} implementations offer no means to
2572 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2573 want to use it.
2574 @end defvar
2576 @defvar ERLCFLAGS
2577 @evindex ERLCFLAGS
2578 @ovindex ERLCFLAGS
2579 Debugging and optimization options for the Erlang compiler.  If it is not set
2580 in the environment when @command{configure} runs, the default value is empty.
2581 @command{configure} uses this variable when compiling
2582 programs to test for Erlang features.
2583 @end defvar
2585 @defvar FCFLAGS
2586 @evindex FCFLAGS
2587 @ovindex FCFLAGS
2588 Debugging and optimization options for the Fortran compiler.  If it
2589 is not set in the environment when @command{configure} runs, the default
2590 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2591 @command{configure} uses this variable when compiling or linking
2592 programs to test for Fortran features.
2593 @end defvar
2595 @defvar FFLAGS
2596 @evindex FFLAGS
2597 @ovindex FFLAGS
2598 Debugging and optimization options for the Fortran 77 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_F77} (or empty if you don't).
2601 @command{configure} uses this variable when compiling or linking
2602 programs to test for Fortran 77 features.
2603 @end defvar
2605 @defvar LDFLAGS
2606 @evindex LDFLAGS
2607 @ovindex LDFLAGS
2608 Options for the linker.  If it is not set
2609 in the environment when @command{configure} runs, the default value is empty.
2610 @command{configure} uses this variable when linking programs to test for
2611 C, C++, Objective C, Objective C++, Fortran, and Go features.
2613 This variable's contents should contain options like @option{-s} and
2614 @option{-L} that affect only the behavior of the linker.  Please see the
2615 explanation of @code{CFLAGS} for what you can do if an option also
2616 affects other phases of the compiler.
2618 Don't use this variable to pass library names
2619 (@option{-l}) to the linker; use @code{LIBS} instead.
2620 @end defvar
2622 @defvar LIBS
2623 @evindex LIBS
2624 @ovindex LIBS
2625 @option{-l} options to pass to the linker.  The default value is empty,
2626 but some Autoconf macros may prepend extra libraries to this variable if
2627 those libraries are found and provide necessary functions, see
2628 @ref{Libraries}.  @command{configure} uses this variable when linking
2629 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2630 features.
2631 @end defvar
2633 @defvar OBJCFLAGS
2634 @evindex OBJCFLAGS
2635 @ovindex OBJCFLAGS
2636 Debugging and optimization options for the Objective C compiler.  It
2637 acts like @code{CFLAGS}, but for Objective C instead of C.
2638 @end defvar
2640 @defvar OBJCXXFLAGS
2641 @evindex OBJCXXFLAGS
2642 @ovindex OBJCXXFLAGS
2643 Debugging and optimization options for the Objective C++ compiler.  It
2644 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2645 @end defvar
2647 @defvar GOFLAGS
2648 @evindex GOFLAGS
2649 @ovindex GOFLAGS
2650 Debugging and optimization options for the Go compiler.  It acts like
2651 @code{CFLAGS}, but for Go instead of C.
2652 @end defvar
2654 @defvar builddir
2655 @ovindex builddir
2656 Rigorously equal to @samp{.}.  Added for symmetry only.
2657 @end defvar
2659 @defvar abs_builddir
2660 @ovindex abs_builddir
2661 Absolute name of @code{builddir}.
2662 @end defvar
2664 @defvar top_builddir
2665 @ovindex top_builddir
2666 The relative name of the top level of the current build tree.  In the
2667 top-level directory, this is the same as @code{builddir}.
2668 @end defvar
2670 @defvar top_build_prefix
2671 @ovindex top_build_prefix
2672 The relative name of the top level of the current build tree with final
2673 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2674 it contains zero or more runs of @code{../}, so it should not be
2675 appended with a slash for concatenation.  This helps for @command{make}
2676 implementations that otherwise do not treat @file{./file} and @file{file}
2677 as equal in the toplevel build directory.
2678 @end defvar
2680 @defvar abs_top_builddir
2681 @ovindex abs_top_builddir
2682 Absolute name of @code{top_builddir}.
2683 @end defvar
2685 @defvar srcdir
2686 @ovindex srcdir
2687 The name of the directory that contains the source code for
2688 that makefile.
2689 @end defvar
2691 @defvar abs_srcdir
2692 @ovindex abs_srcdir
2693 Absolute name of @code{srcdir}.
2694 @end defvar
2696 @defvar top_srcdir
2697 @ovindex top_srcdir
2698 The name of the top-level source code directory for the
2699 package.  In the top-level directory, this is the same as @code{srcdir}.
2700 @end defvar
2702 @defvar abs_top_srcdir
2703 @ovindex abs_top_srcdir
2704 Absolute name of @code{top_srcdir}.
2705 @end defvar
2707 @node Installation Directory Variables
2708 @subsection Installation Directory Variables
2709 @cindex Installation directories
2710 @cindex Directories, installation
2712 The following variables specify the directories for
2713 package installation, see @ref{Directory Variables, , Variables for
2714 Installation Directories, standards, The GNU Coding
2715 Standards}, for more information.  Each variable corresponds to an
2716 argument of @command{configure}; trailing slashes are stripped so that
2717 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2718 between directory names.  See the end of this section for
2719 details on when and how to use these variables.
2721 @defvar bindir
2722 @ovindex bindir
2723 The directory for installing executables that users run.
2724 @end defvar
2726 @defvar datadir
2727 @ovindex datadir
2728 The directory for installing idiosyncratic read-only
2729 architecture-independent data.
2730 @end defvar
2732 @defvar datarootdir
2733 @ovindex datarootdir
2734 The root of the directory tree for read-only architecture-independent
2735 data files.
2736 @end defvar
2738 @defvar docdir
2739 @ovindex docdir
2740 The directory for installing documentation files (other than Info and
2741 man).
2742 @end defvar
2744 @defvar dvidir
2745 @ovindex dvidir
2746 The directory for installing documentation files in DVI format.
2747 @end defvar
2749 @defvar exec_prefix
2750 @ovindex exec_prefix
2751 The installation prefix for architecture-dependent files.  By default
2752 it's the same as @code{prefix}.  You should avoid installing anything
2753 directly to @code{exec_prefix}.  However, the default value for
2754 directories containing architecture-dependent files should be relative
2755 to @code{exec_prefix}.
2756 @end defvar
2758 @defvar htmldir
2759 @ovindex htmldir
2760 The directory for installing HTML documentation.
2761 @end defvar
2763 @defvar includedir
2764 @ovindex includedir
2765 The directory for installing C header files.
2766 @end defvar
2768 @defvar infodir
2769 @ovindex infodir
2770 The directory for installing documentation in Info format.
2771 @end defvar
2773 @defvar libdir
2774 @ovindex libdir
2775 The directory for installing object code libraries.
2776 @end defvar
2778 @defvar libexecdir
2779 @ovindex libexecdir
2780 The directory for installing executables that other programs run.
2781 @end defvar
2783 @defvar localedir
2784 @ovindex localedir
2785 The directory for installing locale-dependent but
2786 architecture-independent data, such as message catalogs.  This directory
2787 usually has a subdirectory per locale.
2788 @end defvar
2790 @defvar localstatedir
2791 @ovindex localstatedir
2792 The directory for installing modifiable single-machine data.
2793 @end defvar
2795 @defvar mandir
2796 @ovindex mandir
2797 The top-level directory for installing documentation in man format.
2798 @end defvar
2800 @defvar oldincludedir
2801 @ovindex oldincludedir
2802 The directory for installing C header files for non-GCC compilers.
2803 @end defvar
2805 @defvar pdfdir
2806 @ovindex pdfdir
2807 The directory for installing PDF documentation.
2808 @end defvar
2810 @defvar prefix
2811 @ovindex prefix
2812 The common installation prefix for all files.  If @code{exec_prefix}
2813 is defined to a different value, @code{prefix} is used only for
2814 architecture-independent files.
2815 @end defvar
2817 @defvar psdir
2818 @ovindex psdir
2819 The directory for installing PostScript documentation.
2820 @end defvar
2822 @defvar sbindir
2823 @ovindex sbindir
2824 The directory for installing executables that system
2825 administrators run.
2826 @end defvar
2828 @defvar sharedstatedir
2829 @ovindex sharedstatedir
2830 The directory for installing modifiable architecture-independent data.
2831 @end defvar
2833 @defvar sysconfdir
2834 @ovindex sysconfdir
2835 The directory for installing read-only single-machine data.
2836 @end defvar
2839 Most of these variables have values that rely on @code{prefix} or
2840 @code{exec_prefix}.  It is deliberate that the directory output
2841 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2842 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2843 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2845 This behavior is mandated by the GNU Coding Standards, so that when
2846 the user runs:
2848 @table @samp
2849 @item make
2850 she can still specify a different prefix from the one specified to
2851 @command{configure}, in which case, if needed, the package should hard
2852 code dependencies corresponding to the make-specified prefix.
2854 @item make install
2855 she can specify a different installation location, in which case the
2856 package @emph{must} still depend on the location which was compiled in
2857 (i.e., never recompile when @samp{make install} is run).  This is an
2858 extremely important feature, as many people may decide to install all
2859 the files of a package grouped together, and then install links from
2860 the final locations to there.
2861 @end table
2863 In order to support these features, it is essential that
2864 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2865 so that its value can be expanded based
2866 on the current value of @code{prefix}.
2868 A corollary is that you should not use these variables except in
2869 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2870 in @file{configure} and hard-coding it in makefiles using
2871 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2872 you should add
2873 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2874 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2876 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2877 @code{bindir} and friends in your shell scripts and other files; instead,
2878 let @command{make} manage their replacement.  For instance Autoconf
2879 ships templates of its shell scripts ending with @samp{.in}, and uses a
2880 makefile snippet similar to the following to build scripts like
2881 @command{autoheader} and @command{autom4te}:
2883 @example
2884 @group
2885 edit = sed \
2886         -e 's|@@bindir[@@]|$(bindir)|g' \
2887         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2888         -e 's|@@prefix[@@]|$(prefix)|g'
2889 @end group
2891 @group
2892 autoheader autom4te: Makefile
2893         rm -f $@@ $@@.tmp
2894         srcdir=''; \
2895           test -f ./$@@.in || srcdir=$(srcdir)/; \
2896           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2897 @c $$ restore font-lock
2898         chmod +x $@@.tmp
2899         chmod a-w $@@.tmp
2900         mv $@@.tmp $@@
2901 @end group
2903 @group
2904 autoheader: $(srcdir)/autoheader.in
2905 autom4te: $(srcdir)/autom4te.in
2906 @end group
2907 @end example
2909 Some details are noteworthy:
2911 @table @asis
2912 @item @samp{@@bindir[@@]}
2913 The brackets prevent @command{configure} from replacing
2914 @samp{@@bindir@@} in the Sed expression itself.
2915 Brackets are preferable to a backslash here, since
2916 Posix says @samp{\@@} is not portable.
2918 @item @samp{$(bindir)}
2919 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2920 instead.
2922 @item @samp{$(pkgdatadir)}
2923 The example takes advantage of the variable @samp{$(pkgdatadir)}
2924 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2926 @item @samp{/}
2927 Don't use @samp{/} in the Sed expressions that replace file names since
2928 most likely the
2929 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2930 Use a shell metacharacter instead, such as @samp{|}.
2932 @item special characters
2933 File names, file name components, and the value of @code{VPATH} should
2934 not contain shell metacharacters or white
2935 space.  @xref{Special Chars in Variables}.
2937 @item dependency on @file{Makefile}
2938 Since @code{edit} uses values that depend on the configuration specific
2939 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2940 the output depends on @file{Makefile}, not @file{configure.ac}.
2942 @item @samp{$@@}
2943 The main rule is generic, and uses @samp{$@@} extensively to
2944 avoid the need for multiple copies of the rule.
2946 @item Separated dependencies and single suffix rules
2947 You can't use them!  The above snippet cannot be (portably) rewritten
2950 @example
2951 autoconf autoheader: Makefile
2952 @group
2953 .in:
2954         rm -f $@@ $@@.tmp
2955         $(edit) $< >$@@.tmp
2956         chmod +x $@@.tmp
2957         mv $@@.tmp $@@
2958 @end group
2959 @end example
2961 @xref{Single Suffix Rules}, for details.
2963 @item @samp{$(srcdir)}
2964 Be sure to specify the name of the source directory,
2965 otherwise the package won't support separated builds.
2966 @end table
2968 For the more specific installation of Erlang libraries, the following variables
2969 are defined:
2971 @defvar ERLANG_INSTALL_LIB_DIR
2972 @ovindex ERLANG_INSTALL_LIB_DIR
2973 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2974 The common parent directory of Erlang library installation directories.
2975 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2976 macro in @file{configure.ac}.
2977 @end defvar
2979 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2980 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2981 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2982 The installation directory for Erlang library @var{library}.
2983 This variable is set by using the
2984 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2985 macro in @file{configure.ac}.
2986 @end defvar
2988 @xref{Erlang Libraries}, for details.
2991 @node Changed Directory Variables
2992 @subsection Changed Directory Variables
2993 @cindex @file{datarootdir}
2995 In Autoconf 2.60, the set of directory variables has changed, and the
2996 defaults of some variables have been adjusted
2997 (@pxref{Installation Directory Variables}) to changes in the
2998 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2999 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3000 upgrading from an earlier Autoconf version, you may need to adjust your files
3001 to ensure that the directory variables are substituted correctly
3002 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3003 in place.  For example, in a @file{Makefile.in}, adding
3005 @example
3006 datarootdir = @@datarootdir@@
3007 @end example
3009 @noindent
3010 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3011 it will add this for you.
3013 To help with the transition, Autoconf warns about files that seem to use
3014 @code{datarootdir} without defining it.  In some cases, it then expands
3015 the value of @code{$datarootdir} in substitutions of the directory
3016 variables.  The following example shows such a warning:
3018 @example
3019 $ @kbd{cat configure.ac}
3020 AC_INIT
3021 AC_CONFIG_FILES([Makefile])
3022 AC_OUTPUT
3023 $ @kbd{cat Makefile.in}
3024 prefix = @@prefix@@
3025 datadir = @@datadir@@
3026 $ @kbd{autoconf}
3027 $ @kbd{configure}
3028 configure: creating ./config.status
3029 config.status: creating Makefile
3030 config.status: WARNING:
3031                Makefile.in seems to ignore the --datarootdir setting
3032 $ @kbd{cat Makefile}
3033 prefix = /usr/local
3034 datadir = $@{prefix@}/share
3035 @end example
3037 Usually one can easily change the file to accommodate both older and newer
3038 Autoconf releases:
3040 @example
3041 $ @kbd{cat Makefile.in}
3042 prefix = @@prefix@@
3043 datarootdir = @@datarootdir@@
3044 datadir = @@datadir@@
3045 $ @kbd{configure}
3046 configure: creating ./config.status
3047 config.status: creating Makefile
3048 $ @kbd{cat Makefile}
3049 prefix = /usr/local
3050 datarootdir = $@{prefix@}/share
3051 datadir = $@{datarootdir@}
3052 @end example
3054 @acindex{DATAROOTDIR_CHECKED}
3055 In some cases, however, the checks may not be able to detect that a suitable
3056 initialization of @code{datarootdir} is in place, or they may fail to detect
3057 that such an initialization is necessary in the output file.  If, after
3058 auditing your package, there are still spurious @file{configure} warnings about
3059 @code{datarootdir}, you may add the line
3061 @example
3062 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3063 @end example
3065 @noindent
3066 to your @file{configure.ac} to disable the warnings.  This is an exception
3067 to the usual rule that you should not define a macro whose name begins with
3068 @code{AC_} (@pxref{Macro Names}).
3072 @node Build Directories
3073 @subsection Build Directories
3074 @cindex Build directories
3075 @cindex Directories, build
3077 You can support compiling a software package for several architectures
3078 simultaneously from the same copy of the source code.  The object files
3079 for each architecture are kept in their own directory.
3081 To support doing this, @command{make} uses the @code{VPATH} variable to
3082 find the files that are in the source directory.  GNU Make
3083 can do this.  Most other recent @command{make} programs can do this as
3084 well, though they may have difficulties and it is often simpler to
3085 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3086 @command{make} programs do not support @code{VPATH}; when using them, the
3087 source code must be in the same directory as the object files.
3089 If you are using GNU Automake, the remaining details in this
3090 section are already covered for you, based on the contents of your
3091 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3092 supporting @code{VPATH} requires the following in your
3093 @file{Makefile.in}:
3095 @example
3096 srcdir = @@srcdir@@
3097 VPATH = @@srcdir@@
3098 @end example
3100 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3101 listed in VPATH}.
3103 @command{configure} substitutes the correct value for @code{srcdir} when
3104 it produces @file{Makefile}.
3106 Do not use the @command{make} variable @code{$<}, which expands to the
3107 file name of the file in the source directory (found with @code{VPATH}),
3108 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3109 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3110 versions of @command{make} do not set @code{$<} in explicit rules; they
3111 expand it to an empty value.
3113 Instead, Make command lines should always refer to source
3114 files by prefixing them with @samp{$(srcdir)/}.  For example:
3116 @example
3117 time.info: time.texinfo
3118         $(MAKEINFO) '$(srcdir)/time.texinfo'
3119 @end example
3121 @node Automatic Remaking
3122 @subsection Automatic Remaking
3123 @cindex Automatic remaking
3124 @cindex Remaking automatically
3126 You can put rules like the following in the top-level @file{Makefile.in}
3127 for a package to automatically update the configuration information when
3128 you change the configuration files.  This example includes all of the
3129 optional files, such as @file{aclocal.m4} and those related to
3130 configuration header files.  Omit from the @file{Makefile.in} rules for
3131 any of these files that your package does not use.
3133 The @samp{$(srcdir)/} prefix is included because of limitations in the
3134 @code{VPATH} mechanism.
3136 The @file{stamp-} files are necessary because the timestamps of
3137 @file{config.h.in} and @file{config.h} are not changed if remaking
3138 them does not change their contents.  This feature avoids unnecessary
3139 recompilation.  You should include the file @file{stamp-h.in} in your
3140 package's distribution, so that @command{make} considers
3141 @file{config.h.in} up to date.  Don't use @command{touch}
3142 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3143 @command{echo} (using
3144 @command{date} would cause needless differences, hence CVS
3145 conflicts, etc.).
3147 @example
3148 @group
3149 $(srcdir)/configure: configure.ac aclocal.m4
3150         cd '$(srcdir)' && autoconf
3152 # autoheader might not change config.h.in, so touch a stamp file.
3153 $(srcdir)/config.h.in: stamp-h.in
3154 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3155         cd '$(srcdir)' && autoheader
3156         echo timestamp > '$(srcdir)/stamp-h.in'
3158 config.h: stamp-h
3159 stamp-h: config.h.in config.status
3160         ./config.status
3162 Makefile: Makefile.in config.status
3163         ./config.status
3165 config.status: configure
3166         ./config.status --recheck
3167 @end group
3168 @end example
3170 @noindent
3171 (Be careful if you copy these lines directly into your makefile, as you
3172 need to convert the indented lines to start with the tab character.)
3174 In addition, you should use
3176 @example
3177 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3178 @end example
3180 @noindent
3181 so @file{config.status} ensures that @file{config.h} is considered up to
3182 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3184 @xref{config.status Invocation}, for more examples of handling
3185 configuration-related dependencies.
3187 @node Configuration Headers
3188 @section Configuration Header Files
3189 @cindex Configuration Header
3190 @cindex @file{config.h}
3192 When a package contains more than a few tests that define C preprocessor
3193 symbols, the command lines to pass @option{-D} options to the compiler
3194 can get quite long.  This causes two problems.  One is that the
3195 @command{make} output is hard to visually scan for errors.  More
3196 seriously, the command lines can exceed the length limits of some
3197 operating systems.  As an alternative to passing @option{-D} options to
3198 the compiler, @command{configure} scripts can create a C header file
3199 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3200 macro selects this kind of output.  Though it can be called anywhere
3201 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3202 it right after @code{AC_INIT}.
3204 The package should @samp{#include} the configuration header file before
3205 any other header files, to prevent inconsistencies in declarations (for
3206 example, if it redefines @code{const}).
3208 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3209 option (or @option{-I..}; whichever directory contains @file{config.h}).
3210 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3211 the directory of the currently read file, i.e., the source directory, not
3212 the build directory.
3214 With the appropriate @option{-I} option, you can use
3215 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3216 because in the rare case when the source directory contains another
3217 @file{config.h}, the build directory should be searched first.
3220 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3221 @acindex{CONFIG_HEADERS}
3222 @cvindex HAVE_CONFIG_H
3223 This macro is one of the instantiating macros; see @ref{Configuration
3224 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3225 blank-or-newline-separated list @var{header} containing C preprocessor
3226 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3227 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3228 The usual name for @var{header} is @file{config.h}.
3230 If @var{header} already exists and its contents are identical to what
3231 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3232 making some changes in the configuration without needlessly causing
3233 object files that depend on the header file to be recompiled.
3235 Usually the input file is named @file{@var{header}.in}; however, you can
3236 override the input file name by appending to @var{header} a
3237 colon-separated list of input files.  For example, you might need to make
3238 the input file name acceptable to DOS variants:
3240 @example
3241 AC_CONFIG_HEADERS([config.h:config.hin])
3242 @end example
3244 @end defmac
3246 @defmac AH_HEADER
3247 @ahindex{HEADER}
3248 This macro is defined as the name of the first declared config header
3249 and undefined if no config headers have been declared up to this point.
3250 A third-party macro may, for example, require use of a config header
3251 without invoking AC_CONFIG_HEADERS twice, like this:
3253 @example
3254 AC_CONFIG_COMMANDS_PRE(
3255         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3256 @end example
3258 @end defmac
3260 @xref{Configuration Actions}, for more details on @var{header}.
3262 @menu
3263 * Header Templates::            Input for the configuration headers
3264 * autoheader Invocation::       How to create configuration templates
3265 * Autoheader Macros::           How to specify CPP templates
3266 @end menu
3268 @node Header Templates
3269 @subsection Configuration Header Templates
3270 @cindex Configuration Header Template
3271 @cindex Header templates
3272 @cindex @file{config.h.in}
3274 Your distribution should contain a template file that looks as you want
3275 the final header file to look, including comments, with @code{#undef}
3276 statements which are used as hooks.  For example, suppose your
3277 @file{configure.ac} makes these calls:
3279 @example
3280 AC_CONFIG_HEADERS([conf.h])
3281 AC_CHECK_HEADERS([unistd.h])
3282 @end example
3284 @noindent
3285 Then you could have code like the following in @file{conf.h.in}.
3286 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3287 to 1, if and only if the system has @file{unistd.h}.
3289 @example
3290 @group
3291 /* Define as 1 if you have unistd.h.  */
3292 #undef HAVE_UNISTD_H
3293 @end group
3294 @end example
3296 The format of the template file is stricter than what the C preprocessor
3297 is required to accept.  A directive line should contain only whitespace,
3298 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3299 instead of @samp{#undef}, or of comments on the same line as
3300 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3301 once.  Other preprocessor lines, such as @samp{#ifdef} or
3302 @samp{#include}, are copied verbatim from the template into the
3303 generated header.
3305 Since it is a tedious task to keep a template header up to date, you may
3306 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3308 During the instantiation of the header, each @samp{#undef} line in the
3309 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3310 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3311 been executed during the @command{configure} run, the @samp{#undef} line is
3312 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3313 on many systems, it can be implicitly defined by the compiler, and
3314 undefining it in the header would then break compilation of subsequent
3315 headers.)
3317 Currently, @emph{all} remaining @samp{#undef} lines in the header
3318 template are commented out, whether or not there was a corresponding
3319 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3320 for future releases of Autoconf.
3322 Generally speaking, since you should not use @samp{#define}, and you
3323 cannot guarantee whether a @samp{#undef} directive in the header
3324 template will be converted to a @samp{#define} or commented out in the
3325 generated header file, the template file cannot be used for conditional
3326 definition effects.  Consequently, if you need to use the construct
3328 @example
3329 @group
3330 #ifdef THIS
3331 # define THAT
3332 #endif
3333 @end group
3334 @end example
3336 @noindent
3337 you must place it outside of the template.
3338 If you absolutely need to hook it to the config header itself, please put
3339 the directives to a separate file, and @samp{#include} that file from the
3340 config header template.  If you are using @command{autoheader}, you would
3341 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3344 @node autoheader Invocation
3345 @subsection Using @command{autoheader} to Create @file{config.h.in}
3346 @cindex @command{autoheader}
3348 The @command{autoheader} program can create a template file of C
3349 @samp{#define} statements for @command{configure} to use.
3350 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3351 @file{configure} sources to determine the name of the template.
3352 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3353 input file name, @command{autoheader} uses the first one.)
3355 It is recommended that only one input file is used.  If you want to append
3356 a boilerplate code, it is preferable to use
3357 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3358 File @file{conf_post.h} is not processed during the configuration then,
3359 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3360 prepend a boilerplate code.
3362 In order to do its job, @command{autoheader} needs you to document all
3363 of the symbols that you might use.  Typically this is done via an
3364 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3365 is a literal symbol and whose third argument describes the symbol
3366 (@pxref{Defining Symbols}).  Alternatively, you can use
3367 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3368 suitable input file for a subsequent configuration header file.
3369 Symbols defined by Autoconf's builtin tests are already documented properly;
3370 you need to document only those that you
3371 define yourself.
3373 You might wonder why @command{autoheader} is needed: after all, why
3374 would @command{configure} need to ``patch'' a @file{config.h.in} to
3375 produce a @file{config.h} instead of just creating @file{config.h} from
3376 scratch?  Well, when everything rocks, the answer is just that we are
3377 wasting our time maintaining @command{autoheader}: generating
3378 @file{config.h} directly is all that is needed.  When things go wrong,
3379 however, you'll be thankful for the existence of @command{autoheader}.
3381 The fact that the symbols are documented is important in order to
3382 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3383 well-defined list of symbols that should be defined (or not) is
3384 also important for people who are porting packages to environments where
3385 @command{configure} cannot be run: they just have to @emph{fill in the
3386 blanks}.
3388 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3390 If you give @command{autoheader} an argument, it uses that file instead
3391 of @file{configure.ac} and writes the header file to the standard output
3392 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3393 argument of @option{-}, it reads the standard input instead of
3394 @file{configure.ac} and writes the header file to the standard output.
3396 @command{autoheader} accepts the following options:
3398 @table @option
3399 @item --help
3400 @itemx -h
3401 Print a summary of the command line options and exit.
3403 @item --version
3404 @itemx -V
3405 Print the version number of Autoconf and exit.
3407 @item --verbose
3408 @itemx -v
3409 Report processing steps.
3411 @item --debug
3412 @itemx -d
3413 Don't remove the temporary files.
3415 @item --force
3416 @itemx -f
3417 Remake the template file even if newer than its input files.
3419 @item --include=@var{dir}
3420 @itemx -I @var{dir}
3421 Append @var{dir} to the include path.  Multiple invocations accumulate.
3423 @item --prepend-include=@var{dir}
3424 @itemx -B @var{dir}
3425 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3427 @item --warnings=@var{category}
3428 @itemx -W @var{category}
3429 @evindex WARNINGS
3430 Report the warnings related to @var{category} (which can actually be a
3431 comma separated list).  Current categories include:
3433 @table @samp
3434 @item obsolete
3435 report the uses of obsolete constructs
3437 @item all
3438 report all the warnings
3440 @item none
3441 report none
3443 @item error
3444 treats warnings as errors
3446 @item no-@var{category}
3447 disable warnings falling into @var{category}
3448 @end table
3450 @end table
3454 @node Autoheader Macros
3455 @subsection Autoheader Macros
3456 @cindex Autoheader macros
3458 @command{autoheader} scans @file{configure.ac} and figures out which C
3459 preprocessor symbols it might define.  It knows how to generate
3460 templates for symbols defined by @code{AC_CHECK_HEADERS},
3461 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3462 symbol, you must define a template for it.  If there are missing
3463 templates, @command{autoheader} fails with an error message.
3465 The template for a @var{symbol} is created
3466 by @command{autoheader} from
3467 the @var{description} argument to an @code{AC_DEFINE};
3468 see @ref{Defining Symbols}.
3470 For special needs, you can use the following macros.
3473 @defmac AH_TEMPLATE (@var{key}, @var{description})
3474 @ahindex{TEMPLATE}
3475 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3476 generates standard templates just like @code{AC_DEFINE} when a
3477 @var{description} is given.
3479 For example:
3481 @example
3482 AH_TEMPLATE([CRAY_STACKSEG_END],
3483             [Define to one of _getb67, GETB67, getb67
3484              for Cray-2 and Cray-YMP systems.  This
3485              function is required for alloca.c support
3486              on those systems.])
3487 @end example
3489 @noindent
3490 generates the following template, with the description properly
3491 justified.
3493 @example
3494 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3495    Cray-YMP systems.  This function is required for alloca.c
3496    support on those systems.  */
3497 #undef CRAY_STACKSEG_END
3498 @end example
3499 @end defmac
3502 @defmac AH_VERBATIM (@var{key}, @var{template})
3503 @ahindex{VERBATIM}
3504 Tell @command{autoheader} to include the @var{template} as-is in the header
3505 template file.  This @var{template} is associated with the @var{key},
3506 which is used to sort all the different templates and guarantee their
3507 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3508 @end defmac
3511 @defmac AH_TOP (@var{text})
3512 @ahindex{TOP}
3513 Include @var{text} at the top of the header template file.
3514 @end defmac
3517 @defmac AH_BOTTOM (@var{text})
3518 @ahindex{BOTTOM}
3519 Include @var{text} at the bottom of the header template file.
3520 @end defmac
3523 Please note that @var{text} gets included ``verbatim'' to the template file,
3524 not to the resulting config header, so it can easily get mangled when the
3525 template is processed.  There is rarely a need for something other than
3527 @example
3528 AH_BOTTOM([#include <custom.h>])
3529 @end example
3533 @node Configuration Commands
3534 @section Running Arbitrary Configuration Commands
3535 @cindex Configuration commands
3536 @cindex Commands for configuration
3538 You can execute arbitrary commands before, during, and after
3539 @file{config.status} is run.  The three following macros accumulate the
3540 commands to run when they are called multiple times.
3541 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3542 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3544 @anchor{AC_CONFIG_COMMANDS}
3545 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3546 @acindex{CONFIG_COMMANDS}
3547 Specify additional shell commands to run at the end of
3548 @file{config.status}, and shell commands to initialize any variables
3549 from @command{configure}.  Associate the commands with @var{tag}.
3550 Since typically the @var{cmds} create a file, @var{tag} should
3551 naturally be the name of that file.  If needed, the directory hosting
3552 @var{tag} is created.  This macro is one of the instantiating macros;
3553 see @ref{Configuration Actions}.
3555 Here is an unrealistic example:
3556 @example
3557 fubar=42
3558 AC_CONFIG_COMMANDS([fubar],
3559                    [echo this is extra $fubar, and so on.],
3560                    [fubar=$fubar])
3561 @end example
3563 Here is a better one:
3564 @example
3565 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3566 @end example
3567 @end defmac
3569 The following two macros look similar, but in fact they are not of the same
3570 breed: they are executed directly by @file{configure}, so you cannot use
3571 @file{config.status} to rerun them.
3573 @c Yet it is good to leave them here.  The user sees them together and
3574 @c decides which best fits their needs.
3576 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3577 @acindex{CONFIG_COMMANDS_PRE}
3578 Execute the @var{cmds} right before creating @file{config.status}.
3580 This macro presents the last opportunity to call @code{AC_SUBST},
3581 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3582 @end defmac
3584 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3585 @acindex{CONFIG_COMMANDS_POST}
3586 Execute the @var{cmds} right after creating @file{config.status}.
3587 @end defmac
3592 @node Configuration Links
3593 @section Creating Configuration Links
3594 @cindex Configuration links
3595 @cindex Links for configuration
3597 You may find it convenient to create links whose destinations depend upon
3598 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3599 creation of relative symbolic links can be delicate when the package is
3600 built in a directory different from the source directory.
3602 @anchor{AC_CONFIG_LINKS}
3603 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3604   @ovar{init-cmds})
3605 @acindex{CONFIG_LINKS}
3606 @cindex Links
3607 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3608 the corresponding link name @var{dest}.  Makes a symbolic link if
3609 possible, otherwise a hard link if possible, otherwise a copy.  The
3610 @var{dest} and @var{source} names should be relative to the top level
3611 source or build directory.  This macro is one of the instantiating
3612 macros; see @ref{Configuration Actions}.
3614 For example, this call:
3616 @example
3617 AC_CONFIG_LINKS([host.h:config/$machine.h
3618                 object.h:config/$obj_format.h])
3619 @end example
3621 @noindent
3622 creates in the current directory @file{host.h} as a link to
3623 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3624 link to @file{@var{srcdir}/config/$obj_format.h}.
3626 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3627 impossible for @samp{config.status} to guess the links to establish.
3629 One can then run:
3630 @example
3631 ./config.status host.h object.h
3632 @end example
3633 @noindent
3634 to create the links.
3635 @end defmac
3639 @node Subdirectories
3640 @section Configuring Other Packages in Subdirectories
3641 @cindex Configure subdirectories
3642 @cindex Subdirectory configure
3644 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3645 makefiles in subdirectories.  However, @command{configure} scripts
3646 that control more than one independent package can use
3647 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3648 packages in subdirectories.
3650 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3651 @acindex{CONFIG_SUBDIRS}
3652 @ovindex subdirs
3653 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3654 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3655 be a literal, i.e., please do not use:
3657 @example
3658 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3659 if test "x$package_foo_enabled" = xyes; then
3660   my_subdirs="$my_subdirs foo"
3662 AC_CONFIG_SUBDIRS([$my_subdirs])
3663 @end example
3665 @noindent
3666 because this prevents @samp{./configure --help=recursive} from
3667 displaying the options of the package @code{foo}.  Instead, you should
3668 write:
3670 @example
3671 if test "x$package_foo_enabled" = xyes; then
3672   AC_CONFIG_SUBDIRS([foo])
3674 @end example
3676 If a given @var{dir} is not found at @command{configure} run time, a
3677 warning is reported; if the subdirectory is optional, write:
3679 @example
3680 if test -d "$srcdir/foo"; then
3681   AC_CONFIG_SUBDIRS([foo])
3683 @end example
3685 @c NB: Yes, below we mean configure.in, not configure.ac.
3686 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3687 of @command{configure}.  This is for packages that might use a
3688 non-Autoconf script @command{Configure}, which can't be called through a
3689 wrapper @command{configure} since it would be the same file on
3690 case-insensitive file systems.  Likewise, if a @var{dir} contains
3691 @file{configure.in} but no @command{configure}, the Cygnus
3692 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3694 The subdirectory @command{configure} scripts are given the same command
3695 line options that were given to this @command{configure} script, with minor
3696 changes if needed, which include:
3698 @itemize @minus
3699 @item
3700 adjusting a relative name for the cache file;
3702 @item
3703 adjusting a relative name for the source directory;
3705 @item
3706 propagating the current value of @code{$prefix}, including if it was
3707 defaulted, and if the default values of the top level and of the subdirectory
3708 @file{configure} differ.
3709 @end itemize
3711 This macro also sets the output variable @code{subdirs} to the list of
3712 directories @samp{@var{dir} @dots{}}.  Make rules can use
3713 this variable to determine which subdirectories to recurse into.
3715 This macro may be called multiple times.
3716 @end defmac
3718 @node Default Prefix
3719 @section Default Prefix
3720 @cindex Install prefix
3721 @cindex Prefix for install
3723 By default, @command{configure} sets the prefix for files it installs to
3724 @file{/usr/local}.  The user of @command{configure} can select a different
3725 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3726 There are two ways to change the default: when creating
3727 @command{configure}, and when running it.
3729 Some software packages might want to install in a directory other than
3730 @file{/usr/local} by default.  To accomplish that, use the
3731 @code{AC_PREFIX_DEFAULT} macro.
3733 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3734 @acindex{PREFIX_DEFAULT}
3735 Set the default installation prefix to @var{prefix} instead of
3736 @file{/usr/local}.
3737 @end defmac
3739 It may be convenient for users to have @command{configure} guess the
3740 installation prefix from the location of a related program that they
3741 have already installed.  If you wish to do that, you can call
3742 @code{AC_PREFIX_PROGRAM}.
3744 @anchor{AC_PREFIX_PROGRAM}
3745 @defmac AC_PREFIX_PROGRAM (@var{program})
3746 @acindex{PREFIX_PROGRAM}
3747 If the user did not specify an installation prefix (using the
3748 @option{--prefix} option), guess a value for it by looking for
3749 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3750 is found, set the prefix to the parent of the directory containing
3751 @var{program}, else default the prefix as described above
3752 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3753 @var{program} is @code{gcc} and the @env{PATH} contains
3754 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3755 @end defmac
3759 @c ======================================================== Existing tests
3761 @node Existing Tests
3762 @chapter Existing Tests
3764 These macros test for particular system features that packages might
3765 need or want to use.  If you need to test for a kind of feature that
3766 none of these macros check for, you can probably do it by calling
3767 primitive test macros with appropriate arguments (@pxref{Writing
3768 Tests}).
3770 These tests print messages telling the user which feature they're
3771 checking for, and what they find.  They cache their results for future
3772 @command{configure} runs (@pxref{Caching Results}).
3774 Some of these macros set output variables.  @xref{Makefile
3775 Substitutions}, for how to get their values.  The phrase ``define
3776 @var{name}'' is used below as a shorthand to mean ``define the C
3777 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3778 Symbols}, for how to get those symbol definitions into your program.
3780 @menu
3781 * Common Behavior::             Macros' standard schemes
3782 * Alternative Programs::        Selecting between alternative programs
3783 * Files::                       Checking for the existence of files
3784 * Libraries::                   Library archives that might be missing
3785 * Library Functions::           C library functions that might be missing
3786 * Header Files::                Header files that might be missing
3787 * Declarations::                Declarations that may be missing
3788 * Structures::                  Structures or members that might be missing
3789 * Types::                       Types that might be missing
3790 * Compilers and Preprocessors::  Checking for compiling programs
3791 * System Services::             Operating system services
3792 * Posix Variants::              Special kludges for specific Posix variants
3793 * Erlang Libraries::            Checking for the existence of Erlang libraries
3794 @end menu
3796 @node Common Behavior
3797 @section Common Behavior
3798 @cindex Common autoconf behavior
3800 Much effort has been expended to make Autoconf easy to learn.  The most
3801 obvious way to reach this goal is simply to enforce standard interfaces
3802 and behaviors, avoiding exceptions as much as possible.  Because of
3803 history and inertia, unfortunately, there are still too many exceptions
3804 in Autoconf; nevertheless, this section describes some of the common
3805 rules.
3807 @menu
3808 * Standard Symbols::            Symbols defined by the macros
3809 * Default Includes::            Includes used by the generic macros
3810 @end menu
3812 @node Standard Symbols
3813 @subsection Standard Symbols
3814 @cindex Standard symbols
3816 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3817 their test transform their @var{argument} values to a standard alphabet.
3818 First, @var{argument} is converted to upper case and any asterisks
3819 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3820 that are not alphanumeric are converted to underscores.
3822 For instance,
3824 @example
3825 AC_CHECK_TYPES([struct $Expensive*])
3826 @end example
3828 @noindent
3829 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3830 succeeds.
3833 @node Default Includes
3834 @subsection Default Includes
3835 @cindex Default includes
3836 @cindex Includes, default
3838 Several tests depend upon a set of header files.  Since these headers
3839 are not universally available, tests actually have to provide a set of
3840 protected includes, such as:
3842 @example
3843 @group
3844 #ifdef TIME_WITH_SYS_TIME
3845 # include <sys/time.h>
3846 # include <time.h>
3847 #else
3848 # ifdef HAVE_SYS_TIME_H
3849 #  include <sys/time.h>
3850 # else
3851 #  include <time.h>
3852 # endif
3853 #endif
3854 @end group
3855 @end example
3857 @noindent
3858 Unless you know exactly what you are doing, you should avoid using
3859 unconditional includes, and check the existence of the headers you
3860 include beforehand (@pxref{Header Files}).
3862 Most generic macros use the following macro to provide the default set
3863 of includes:
3865 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3866 @acindex{INCLUDES_DEFAULT}
3867 Expand to @var{include-directives} if defined, otherwise to:
3869 @example
3870 @group
3871 #include <stdio.h>
3872 #ifdef HAVE_SYS_TYPES_H
3873 # include <sys/types.h>
3874 #endif
3875 #ifdef HAVE_SYS_STAT_H
3876 # include <sys/stat.h>
3877 #endif
3878 #ifdef STDC_HEADERS
3879 # include <stdlib.h>
3880 # include <stddef.h>
3881 #else
3882 # ifdef HAVE_STDLIB_H
3883 #  include <stdlib.h>
3884 # endif
3885 #endif
3886 #ifdef HAVE_STRING_H
3887 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3888 #  include <memory.h>
3889 # endif
3890 # include <string.h>
3891 #endif
3892 #ifdef HAVE_STRINGS_H
3893 # include <strings.h>
3894 #endif
3895 #ifdef HAVE_INTTYPES_H
3896 # include <inttypes.h>
3897 #endif
3898 #ifdef HAVE_STDINT_H
3899 # include <stdint.h>
3900 #endif
3901 #ifdef HAVE_UNISTD_H
3902 # include <unistd.h>
3903 #endif
3904 @end group
3905 @end example
3907 If the default includes are used, then check for the presence of these
3908 headers and their compatibility, i.e., you don't need to run
3909 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3911 These headers are checked for in the same order as they are included.
3912 For instance, on some systems @file{string.h} and @file{strings.h} both
3913 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3914 @code{HAVE_STRINGS_H}.
3915 @end defmac
3917 @node Alternative Programs
3918 @section Alternative Programs
3919 @cindex Programs, checking
3921 These macros check for the presence or behavior of particular programs.
3922 They are used to choose between several alternative programs and to
3923 decide what to do once one has been chosen.  If there is no macro
3924 specifically defined to check for a program you need, and you don't need
3925 to check for any special properties of it, then you can use one of the
3926 general program-check macros.
3928 @menu
3929 * Particular Programs::         Special handling to find certain programs
3930 * Generic Programs::            How to find other programs
3931 @end menu
3933 @node Particular Programs
3934 @subsection Particular Program Checks
3936 These macros check for particular programs---whether they exist, and
3937 in some cases whether they support certain features.
3939 @defmac AC_PROG_AWK
3940 @acindex{PROG_AWK}
3941 @ovindex AWK
3942 @caindex prog_AWK
3943 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3944 order, and set output variable @code{AWK} to the first one that is found.
3945 It tries @code{gawk} first because that is reported to be the
3946 best implementation.  The result can be overridden by setting the
3947 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3949 Using this macro is sufficient to avoid the pitfalls of traditional
3950 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3951 @end defmac
3953 @defmac AC_PROG_GREP
3954 @acindex{PROG_GREP}
3955 @ovindex GREP
3956 @caindex prog_GREP
3957 Look for the best available @code{grep} or @code{ggrep} that accepts the
3958 longest input lines possible, and that supports multiple @option{-e} options.
3959 Set the output variable @code{GREP} to whatever is chosen.
3960 @xref{grep, , Limitations of Usual Tools}, for more information about
3961 portability problems with the @command{grep} command family.  The result
3962 can be overridden by setting the @code{GREP} variable and is cached in the
3963 @code{ac_cv_path_GREP} variable.
3964 @end defmac
3966 @defmac AC_PROG_EGREP
3967 @acindex{PROG_EGREP}
3968 @ovindex EGREP
3969 @caindex prog_EGREP
3970 Check whether @code{$GREP -E} works, or else look for the best available
3971 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3972 Set the output variable @code{EGREP} to whatever is chosen.  The result
3973 can be overridden by setting the @code{EGREP} variable and is cached in the
3974 @code{ac_cv_path_EGREP} variable.
3975 @end defmac
3977 @defmac AC_PROG_FGREP
3978 @acindex{PROG_FGREP}
3979 @ovindex FGREP
3980 @caindex prog_FGREP
3981 Check whether @code{$GREP -F} works, or else look for the best available
3982 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3983 Set the output variable @code{FGREP} to whatever is chosen.  The result
3984 can be overridden by setting the @code{FGREP} variable and is cached in the
3985 @code{ac_cv_path_FGREP} variable.
3986 @end defmac
3988 @defmac AC_PROG_INSTALL
3989 @acindex{PROG_INSTALL}
3990 @ovindex INSTALL
3991 @ovindex INSTALL_PROGRAM
3992 @ovindex INSTALL_DATA
3993 @ovindex INSTALL_SCRIPT
3994 @caindex path_install
3995 Set output variable @code{INSTALL} to the name of a BSD-compatible
3996 @command{install} program, if one is found in the current @env{PATH}.
3997 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3998 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3999 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4000 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4001 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4003 @samp{@@INSTALL@@} is special, as its value may vary for different
4004 configuration files.
4006 This macro screens out various instances of @command{install} known not to
4007 work.  It prefers to find a C program rather than a shell script, for
4008 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4009 but that name is obsolete because some @command{make} programs have a rule
4010 that creates @file{install} from it if there is no makefile.  Further, this
4011 macro requires @command{install} to be able to install multiple files into a
4012 target directory in a single invocation.
4014 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4015 you use @code{AC_PROG_INSTALL}, you must include either
4016 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4017 @command{configure} produces an error message saying it can't find
4018 them---even if the system you're on has a good @command{install} program.
4019 This check is a safety measure to prevent you from accidentally leaving
4020 that file out, which would prevent your package from installing on
4021 systems that don't have a BSD-compatible @command{install} program.
4023 If you need to use your own installation program because it has features
4024 not found in standard @command{install} programs, there is no reason to use
4025 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4026 @file{Makefile.in} files.
4028 The result of the test can be overridden by setting the variable
4029 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4030 @end defmac
4032 @defmac AC_PROG_MKDIR_P
4033 @acindex{PROG_MKDIR_P}
4034 @ovindex MKDIR_P
4035 @caindex path_mkdir
4036 Set output variable @code{MKDIR_P} to a program that ensures that for
4037 each argument, a directory named by this argument exists, creating it
4038 and its parent directories if needed, and without race conditions when
4039 two instances of the program attempt to make the same directory at
4040 nearly the same time.
4042 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4043 falls back on invoking @command{install-sh} with the @option{-d} option,
4044 so your package should
4045 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4046 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4047 is vulnerable to race conditions, so if you want to support parallel
4048 installs from
4049 different packages into the same directory you need to make sure you
4050 have an up-to-date @file{install-sh}.  In particular, be careful about
4051 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4053 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4054 in M4sh}), but it sets an output variable intended for use in other
4055 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4056 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4057 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4058 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4059 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4060 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4061 Finally, @code{AS_MKDIR_P} does not check for race condition
4062 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4064 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4065 configuration files.
4067 The result of the test can be overridden by setting the variable
4068 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4069 @end defmac
4071 @anchor{AC_PROG_LEX}
4072 @defmac AC_PROG_LEX
4073 @acindex{PROG_LEX}
4074 @ovindex LEX
4075 @ovindex LEXLIB
4076 @cvindex YYTEXT_POINTER
4077 @ovindex LEX_OUTPUT_ROOT
4078 @caindex prog_LEX
4079 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4080 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4081 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4082 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4083 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4084 alongside the source @file{file.l}, this default allows users without a
4085 lexer generator to still build the package even if the timestamp for
4086 @file{file.l} is inadvertantly changed.
4088 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4089 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4090 the base of the file name that the lexer generates; usually
4091 @file{lex.yy}, but sometimes something else.  These results vary
4092 according to whether @code{lex} or @code{flex} is being used.
4094 You are encouraged to use Flex in your sources, since it is both more
4095 pleasant to use than plain Lex and the C source it produces is portable.
4096 In order to ensure portability, however, you must either provide a
4097 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4098 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4099 statement in the scanner's source.  Once this done, the scanner is
4100 portable (unless @emph{you} felt free to use nonportable constructs) and
4101 does not depend on any library.  In this case, and in this case only, it
4102 is suggested that you use this Autoconf snippet:
4104 @example
4105 AC_PROG_LEX
4106 if test "x$LEX" != xflex; then
4107   LEX="$SHELL $missing_dir/missing flex"
4108   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4109   AC_SUBST([LEXLIB], [''])
4111 @end example
4113 The shell script @command{missing} can be found in the Automake
4114 distribution.
4116 Remember that the user may have supplied an alternate location in
4117 @env{LEX}, so if Flex is required, it is better to check that the user
4118 provided something sufficient by parsing the output of @samp{$LEX
4119 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4121 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4122 (indirectly) this macro twice, which causes an annoying but benign
4123 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4124 of Automake will fix this issue; meanwhile, just ignore this message.
4126 As part of running the test, this macro may delete any file in the
4127 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4129 The result of this test can be influenced by setting the variable
4130 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4131 @end defmac
4133 @anchor{AC_PROG_LN_S}
4134 @defmac AC_PROG_LN_S
4135 @acindex{PROG_LN_S}
4136 @ovindex LN_S
4137 If @samp{ln -s} works on the current file system (the operating system
4138 and file system support symbolic links), set the output variable
4139 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4140 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4142 If you make a link in a directory other than the current directory, its
4143 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4144 create links using @samp{$(LN_S)}, either find out which form is used
4145 and adjust the arguments, or always invoke @code{ln} in the directory
4146 where the link is to be created.
4148 In other words, it does not work to do:
4149 @example
4150 $(LN_S) foo /x/bar
4151 @end example
4153 Instead, do:
4155 @example
4156 (cd /x && $(LN_S) foo bar)
4157 @end example
4158 @end defmac
4160 @defmac AC_PROG_RANLIB
4161 @acindex{PROG_RANLIB}
4162 @ovindex RANLIB
4163 @c @caindex prog_RANLIB
4164 @c @caindex prog_ac_ct_RANLIB
4165 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4166 is found, and otherwise to @samp{:} (do nothing).
4167 @end defmac
4169 @defmac AC_PROG_SED
4170 @acindex{PROG_SED}
4171 @ovindex SED
4172 @caindex path_SED
4173 Set output variable @code{SED} to a Sed implementation that conforms to
4174 Posix and does not have arbitrary length limits.  Report an error if no
4175 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4176 information about portability problems with Sed.
4178 The result of this test can be overridden by setting the @code{SED} variable
4179 and is cached in the @code{ac_cv_path_SED} variable.
4180 @end defmac
4182 @defmac AC_PROG_YACC
4183 @acindex{PROG_YACC}
4184 @evindex YACC
4185 @evindex YFLAGS
4186 @ovindex YACC
4187 @caindex prog_YACC
4188 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4189 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4190 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4191 The result of this test can be influenced by setting the variable
4192 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4193 @end defmac
4195 @node Generic Programs
4196 @subsection Generic Program and File Checks
4198 These macros are used to find programs not covered by the ``particular''
4199 test macros.  If you need to check the behavior of a program as well as
4200 find out whether it is present, you have to write your own test for it
4201 (@pxref{Writing Tests}).  By default, these macros use the environment
4202 variable @env{PATH}.  If you need to check for a program that might not
4203 be in the user's @env{PATH}, you can pass a modified path to use
4204 instead, like this:
4206 @example
4207 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4208              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4209 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4210 @end example
4212 You are strongly encouraged to declare the @var{variable} passed to
4213 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4214 @code{AC_ARG_VAR}, for more details.
4216 @anchor{AC_CHECK_PROG}
4217 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4218   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4219   @ovar{reject})
4220 @acindex{CHECK_PROG}
4221 @caindex prog_@var{variable}
4222 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4223 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4224 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4225 absolute file name) even if it is the first found in the search path; in
4226 that case, set @var{variable} using the absolute file name of the
4227 @var{prog-to-check-for} found that is not @var{reject}.  If
4228 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4229 @var{variable}.  The result of this test can be overridden by setting the
4230 @var{variable} variable or the cache variable
4231 @code{ac_cv_prog_@var{variable}}.
4232 @end defmac
4234 @anchor{AC_CHECK_PROGS}
4235 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4236   @ovar{value-if-not-found}, @dvar{path, $PATH})
4237 @acindex{CHECK_PROGS}
4238 @caindex prog_@var{variable}
4239 Check for each program in the blank-separated list
4240 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4241 @var{variable} to the name of that program.  Otherwise, continue
4242 checking the next program in the list.  If none of the programs in the
4243 list are found, set @var{variable} to @var{value-if-not-found}; if
4244 @var{value-if-not-found} is not specified, the value of @var{variable}
4245 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4246 this test can be overridden by setting the @var{variable} variable or the
4247 cache variable @code{ac_cv_prog_@var{variable}}.
4248 @end defmac
4250 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4251   @ovar{value-if-not-found}, @dvar{path, $PATH})
4252 @acindex{CHECK_TARGET_TOOL}
4253 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4254 with a prefix of the target type as determined by
4255 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4256 If the tool cannot be found with a prefix, and if the build and target
4257 types are equal, then it is also searched for without a prefix.
4259 As noted in @ref{Specifying Target Triplets}, the
4260 target is rarely specified, because most of the time it is the same
4261 as the host: it is the type of system for which any compiler tool in
4262 the package produces code.  What this macro looks for is,
4263 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4264 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4265 uses to produce objects, archives or executables}.
4266 @end defmac
4268 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4269   @ovar{value-if-not-found}, @dvar{path, $PATH})
4270 @acindex{CHECK_TOOL}
4271 @c @caindex prog_@var{VARIABLE}
4272 @c @caindex prog_ac_ct_@var{VARIABLE}
4273 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4274 with a prefix of the host type as specified by @option{--host}, followed by a
4275 dash.  For example, if the user runs
4276 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4277 @example
4278 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4279 @end example
4280 @noindent
4281 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4282 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4283 @var{path}, or to @samp{:} if neither program exists.
4285 When cross-compiling, this macro will issue a warning if no program
4286 prefixed with the host type could be found.
4287 For more information, see @ref{Specifying Target Triplets}.
4288 @end defmac
4290 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4291   @ovar{value-if-not-found}, @dvar{path, $PATH})
4292 @acindex{CHECK_TARGET_TOOLS}
4293 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4294 @var{progs-to-check-for} are checked with a prefix of the target type as
4295 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4296 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4297 prefix, and if the build and target types are equal, then the first one
4298 without a prefix is used.  If a tool is found, set @var{variable} to
4299 the name of that program.  If none of the tools in the list are found,
4300 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4301 is not specified, the value of @var{variable} is not changed.  Calls
4302 @code{AC_SUBST} for @var{variable}.
4303 @end defmac
4305 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4306   @ovar{value-if-not-found}, @dvar{path, $PATH})
4307 @acindex{CHECK_TOOLS}
4308 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4309 @var{progs-to-check-for} are checked with a prefix of the host type as
4310 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4311 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4312 prefix, then the first one without a prefix is used.  If a tool is found,
4313 set @var{variable} to the name of that program.  If none of the tools in
4314 the list are found, set @var{variable} to @var{value-if-not-found}; if
4315 @var{value-if-not-found} is not specified, the value of @var{variable}
4316 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4318 When cross-compiling, this macro will issue a warning if no program
4319 prefixed with the host type could be found.
4320 For more information, see @ref{Specifying Target Triplets}.
4321 @end defmac
4323 @anchor{AC_PATH_PROG}
4324 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4325   @ovar{value-if-not-found}, @dvar{path, $PATH})
4326 @acindex{PATH_PROG}
4327 @caindex path_@var{variable}
4328 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4329 name of @var{prog-to-check-for} if found.  The result of this test
4330 can be overridden by setting the @var{variable} variable.  A positive
4331 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4332 variable.
4333 @end defmac
4335 @anchor{AC_PATH_PROGS}
4336 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4337   @ovar{value-if-not-found}, @dvar{path, $PATH})
4338 @acindex{PATH_PROGS}
4339 @caindex path_@var{variable}
4340 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4341 are found, set @var{variable} to the absolute name of the program
4342 found.  The result of this test can be overridden by setting the
4343 @var{variable} variable.  A positive result of this test is cached in
4344 the @code{ac_cv_path_@var{variable}} variable.
4345 @end defmac
4347 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4348   @var{progs-to-check-for}, @var{feature-test}, @
4349   @ovar{action-if-not-found}, @dvar{path, $PATH})
4350 @acindex{PATH_PROGS_FEATURE_CHECK}
4351 @caindex path_@var{variable}
4352 @vrindex ac_path_@var{variable}
4353 @vrindex ac_path_@var{variable}_found
4354 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4355 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4356 its value.  Otherwise, check for each program in the blank-separated
4357 list @var{progs-to-check-for} existing in @var{path}.  For each program
4358 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4359 set to the absolute name of the candidate program.  If no invocation of
4360 @var{feature-test} sets the shell variable
4361 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4362 executed.  @var{feature-test} will be run even when
4363 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4364 choose a better candidate found later in @var{path}; to accept the
4365 current setting and bypass all futher checks, @var{feature-test} can
4366 execute @code{ac_path_@var{variable}_found=:}.
4368 Note that this macro has some subtle differences from
4369 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4370 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4371 particular, @var{variable} is not set to the final value of
4372 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4373 run.  Also, on failure, any action can be performed, whereas
4374 @code{AC_CHECK_PROGS} only performs
4375 @code{@var{variable}=@var{value-if-not-found}}.
4377 Here is an example, similar to what Autoconf uses in its own configure
4378 script.  It will search for an implementation of @command{m4} that
4379 supports the @code{indir} builtin, even if it goes by the name
4380 @command{gm4} or is not the first implementation on @env{PATH}.
4382 @example
4383 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4384   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4385     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4386       test "x$m4out" = x0 \
4387       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4388     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4389 AC_SUBST([M4], [$ac_cv_path_M4])
4390 @end example
4391 @end defmac
4393 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4394   @ovar{value-if-not-found}, @dvar{path, $PATH})
4395 @acindex{PATH_TARGET_TOOL}
4396 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4397 name of the program if it is found.
4398 @end defmac
4400 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4401   @ovar{value-if-not-found}, @dvar{path, $PATH})
4402 @acindex{PATH_TOOL}
4403 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4404 name of the program if it is found.
4406 When cross-compiling, this macro will issue a warning if no program
4407 prefixed with the host type could be found.
4408 For more information, see @ref{Specifying Target Triplets}.
4409 @end defmac
4412 @node Files
4413 @section Files
4414 @cindex File, checking
4416 You might also need to check for the existence of files.  Before using
4417 these macros, ask yourself whether a runtime test might not be a better
4418 solution.  Be aware that, like most Autoconf macros, they test a feature
4419 of the host machine, and therefore, they die when cross-compiling.
4421 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4422   @ovar{action-if-not-found})
4423 @acindex{CHECK_FILE}
4424 @caindex file_@var{file}
4425 Check whether file @var{file} exists on the native system.  If it is
4426 found, execute @var{action-if-found}, otherwise do
4427 @var{action-if-not-found}, if given.  The result of this test is cached
4428 in the @code{ac_cv_file_@var{file}} variable, with characters not
4429 suitable for a variable name mapped to underscores.
4430 @end defmac
4432 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4433   @ovar{action-if-not-found})
4434 @acindex{CHECK_FILES}
4435 @caindex file_@var{file}
4436 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4437 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4438 for each file found.  The results of each test are cached in the
4439 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4440 a variable name mapped to underscores.
4441 @end defmac
4444 @node Libraries
4445 @section Library Files
4446 @cindex Library, checking
4448 The following macros check for the presence of certain C, C++, Fortran,
4449 or Go library archive files.
4451 @anchor{AC_CHECK_LIB}
4452 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4453   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4454 @acindex{CHECK_LIB}
4455 @caindex lib_@var{library}_@var{function}
4456 Test whether the library @var{library} is available by trying to link
4457 a test program that calls function @var{function} with the library.
4458 @var{function} should be a function provided by the library.
4459 Use the base
4460 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4461 the @var{library} argument.
4463 @var{action-if-found} is a list of shell commands to run if the link
4464 with the library succeeds; @var{action-if-not-found} is a list of shell
4465 commands to run if the link fails.  If @var{action-if-found} is not
4466 specified, the default action prepends @option{-l@var{library}} to
4467 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4468 capitals).  This macro is intended to support building @code{LIBS} in
4469 a right-to-left (least-dependent to most-dependent) fashion such that
4470 library dependencies are satisfied as a natural side effect of
4471 consecutive tests.  Linkers are sensitive to library ordering
4472 so the order in which @code{LIBS} is generated is important to reliable
4473 detection of libraries.
4475 If linking with @var{library} results in unresolved symbols that would
4476 be resolved by linking with additional libraries, give those libraries
4477 as the @var{other-libraries} argument, separated by spaces:
4478 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4479 that @var{library} is present, because linking the test program can
4480 fail with unresolved symbols.  The @var{other-libraries} argument
4481 should be limited to cases where it is desirable to test for one library
4482 in the presence of another that is not already in @code{LIBS}.
4484 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4485 in some common cases.  Many standard functions like @code{gethostbyname}
4486 appear in the standard C library on some hosts, and in special libraries
4487 like @code{nsl} on other hosts.  On some hosts the special libraries
4488 contain variant implementations that you may not want to use.  These
4489 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4490 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4492 The result of this test is cached in the
4493 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4494 @end defmac
4496 @anchor{AC_SEARCH_LIBS}
4497 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4498   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4499 @acindex{SEARCH_LIBS}
4500 @caindex search_@var{function}
4501 Search for a library defining @var{function} if it's not already
4502 available.  This equates to calling
4503 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4504 no libraries, then for each library listed in @var{search-libs}.
4506 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4507 to contain @var{function}, and run @var{action-if-found}.  If the
4508 function is not found, run @var{action-if-not-found}.
4510 If linking with @var{library} results in unresolved symbols that would
4511 be resolved by linking with additional libraries, give those libraries
4512 as the @var{other-libraries} argument, separated by spaces:
4513 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4514 that @var{function} is present, because linking the test program
4515 always fails with unresolved symbols.
4517 The result of this test is cached in the
4518 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4519 @var{function} is already available, as @samp{no} if no library
4520 containing @var{function} was found, otherwise as the
4521 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4522 @end defmac
4526 @node Library Functions
4527 @section Library Functions
4529 The following macros check for particular C library functions.
4530 If there is no macro specifically defined to check for a function you need,
4531 and you don't need to check for any special properties of
4532 it, then you can use one of the general function-check macros.
4534 @menu
4535 * Function Portability::        Pitfalls with usual functions
4536 * Particular Functions::        Special handling to find certain functions
4537 * Generic Functions::           How to find other functions
4538 @end menu
4540 @node Function Portability
4541 @subsection Portability of C Functions
4542 @cindex Portability of C functions
4543 @cindex C function portability
4545 Most usual functions can either be missing, or be buggy, or be limited
4546 on some architectures.  This section tries to make an inventory of these
4547 portability issues.  By definition, this list always requires
4548 additions.  A much more complete list is maintained by the Gnulib
4549 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4550 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4551 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4552 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4553 help us keep the gnulib list as complete as possible.
4555 @table @asis
4556 @item @code{exit}
4557 @c @fuindex exit
4558 @prindex @code{exit}
4559 On ancient hosts, @code{exit} returned @code{int}.
4560 This is because @code{exit} predates @code{void}, and there was a long
4561 tradition of it returning @code{int}.
4563 On current hosts, the problem more likely is that @code{exit} is not
4564 declared, due to C++ problems of some sort or another.  For this reason
4565 we suggest that test programs not invoke @code{exit}, but return from
4566 @code{main} instead.
4568 @item @code{free}
4569 @c @fuindex free
4570 @prindex @code{free}
4571 The C standard says a call @code{free (NULL)} does nothing, but
4572 some old systems don't support this (e.g., NextStep).
4574 @item @code{isinf}
4575 @itemx @code{isnan}
4576 @c @fuindex isinf
4577 @c @fuindex isnan
4578 @prindex @code{isinf}
4579 @prindex @code{isnan}
4580 The C99 standard says that @code{isinf} and @code{isnan} are
4581 macros.  On some systems just macros are available
4582 (e.g., HP-UX and Solaris 10), on
4583 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4584 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4585 these functions are declared in nonstandard headers like
4586 @code{<sunmath.h>} and defined in non-default libraries like
4587 @option{-lm} or @option{-lsunmath}.
4589 The C99 @code{isinf} and @code{isnan} macros work correctly with
4590 @code{long double} arguments, but pre-C99 systems that use functions
4591 typically assume @code{double} arguments.  On such a system,
4592 @code{isinf} incorrectly returns true for a finite @code{long double}
4593 argument that is outside the range of @code{double}.
4595 The best workaround for these issues is to use gnulib modules
4596 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4597 solution involves code like the following.
4599 @smallexample
4600 #include <math.h>
4602 #ifndef isnan
4603 # define isnan(x) \
4604     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4605      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4606      : isnan_f (x))
4607 static inline int isnan_f  (float       x) @{ return x != x; @}
4608 static inline int isnan_d  (double      x) @{ return x != x; @}
4609 static inline int isnan_ld (long double x) @{ return x != x; @}
4610 #endif
4612 #ifndef isinf
4613 # define isinf(x) \
4614     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4615      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4616      : isinf_f (x))
4617 static inline int isinf_f  (float       x)
4618 @{ return !isnan (x) && isnan (x - x); @}
4619 static inline int isinf_d  (double      x)
4620 @{ return !isnan (x) && isnan (x - x); @}
4621 static inline int isinf_ld (long double x)
4622 @{ return !isnan (x) && isnan (x - x); @}
4623 #endif
4624 @end smallexample
4626 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4627 compilers that lack the @code{inline} keyword.  Some optimizing
4628 compilers mishandle these definitions, but systems with that bug
4629 typically have many other floating point corner-case compliance problems
4630 anyway, so it's probably not worth worrying about.
4632 @item @code{malloc}
4633 @c @fuindex malloc
4634 @prindex @code{malloc}
4635 The C standard says a call @code{malloc (0)} is implementation
4636 dependent.  It can return either @code{NULL} or a new non-null pointer.
4637 The latter is more common (e.g., the GNU C Library) but is by
4638 no means universal.  @code{AC_FUNC_MALLOC}
4639 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4641 @item @code{putenv}
4642 @c @fuindex putenv
4643 @prindex @code{putenv}
4644 Posix prefers @code{setenv} to @code{putenv}; among other things,
4645 @code{putenv} is not required of all Posix implementations, but
4646 @code{setenv} is.
4648 Posix specifies that @code{putenv} puts the given string directly in
4649 @code{environ}, but some systems make a copy of it instead (e.g.,
4650 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4651 not free it, causing a memory leak (e.g., FreeBSD 4).
4653 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4654 environment, but this is not standard usage and it dumps core
4655 on some systems (e.g., AIX).
4657 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4658 environment, rather than inserting it with an empty value.
4660 @item @code{realloc}
4661 @c @fuindex realloc
4662 @prindex @code{realloc}
4663 The C standard says a call @code{realloc (NULL, size)} is equivalent
4664 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4665 NextStep).
4667 @item @code{signal} handler
4668 @c @fuindex signal
4669 @prindex @code{signal}
4670 @prindex @code{sigaction}
4671 Normally @code{signal} takes a handler function with a return type of
4672 @code{void}, but some old systems required @code{int} instead.  Any
4673 actual @code{int} value returned is not used; this is only a
4674 difference in the function prototype demanded.
4676 All systems we know of in current use return @code{void}.  The
4677 @code{int} was to support K&R C, where of course @code{void} is not
4678 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4679 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4680 all cases.
4682 In most cases, it is more robust to use @code{sigaction} when it is
4683 available, rather than @code{signal}.
4685 @item @code{snprintf}
4686 @c @fuindex snprintf
4687 @prindex @code{snprintf}
4688 @c @fuindex vsnprintf
4689 @prindex @code{vsnprintf}
4690 The C99 standard says that if the output array isn't big enough
4691 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4692 truncate the output and return the number of bytes that ought to have
4693 been produced.  Some older systems return the truncated length (e.g.,
4694 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4695 (e.g., earlier GNU C Library versions), and some the buffer
4696 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4697 older systems ignore the length and overrun the buffer (e.g., 64-bit
4698 Solaris 7).
4700 @item @code{sprintf}
4701 @c @fuindex sprintf
4702 @prindex @code{sprintf}
4703 @c @fuindex vsprintf
4704 @prindex @code{vsprintf}
4705 The C standard says @code{sprintf} and @code{vsprintf} return the
4706 number of bytes written.  On some ancient systems (SunOS 4 for
4707 instance) they return the buffer pointer instead, but these no
4708 longer need to be worried about.
4710 @item @code{sscanf}
4711 @c @fuindex sscanf
4712 @prindex @code{sscanf}
4713 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4714 that its
4715 input string be writable (though it doesn't actually change it).  This
4716 can be a problem when using @command{gcc} since it normally puts
4717 constant strings in read-only memory (@pxref{Incompatibilities,
4718 Incompatibilities of GCC, , gcc, Using and
4719 Porting the GNU Compiler Collection}).  Apparently in some cases even
4720 having format strings read-only can be a problem.
4722 @item @code{strerror_r}
4723 @c @fuindex strerror_r
4724 @prindex @code{strerror_r}
4725 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4726 systems (e.g., GNU C Library version 2.2.4) provide a
4727 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4728 can detect which is in use (@pxref{Particular Functions}).
4730 @item @code{strnlen}
4731 @c @fuindex strnlen
4732 @prindex @code{strnlen}
4733 AIX 4.3 provides a broken version which produces the
4734 following results:
4736 @example
4737 strnlen ("foobar", 0) = 0
4738 strnlen ("foobar", 1) = 3
4739 strnlen ("foobar", 2) = 2
4740 strnlen ("foobar", 3) = 1
4741 strnlen ("foobar", 4) = 0
4742 strnlen ("foobar", 5) = 6
4743 strnlen ("foobar", 6) = 6
4744 strnlen ("foobar", 7) = 6
4745 strnlen ("foobar", 8) = 6
4746 strnlen ("foobar", 9) = 6
4747 @end example
4749 @item @code{sysconf}
4750 @c @fuindex sysconf
4751 @prindex @code{sysconf}
4752 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4753 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4754 @code{#ifdef}.
4756 @item @code{unlink}
4757 @c @fuindex unlink
4758 @prindex @code{unlink}
4759 The Posix spec says that @code{unlink} causes the given file to be
4760 removed only after there are no more open file handles for it.  Some
4761 non-Posix hosts have trouble with this requirement, though,
4762 and some DOS variants even corrupt the file system.
4764 @item @code{unsetenv}
4765 @c @fuindex unsetenv
4766 @prindex @code{unsetenv}
4767 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4768 can be removed with a call @code{putenv ("FOO=")}, as described under
4769 @code{putenv} above.
4771 @item @code{va_copy}
4772 @c @fuindex va_copy
4773 @prindex @code{va_copy}
4774 The C99 standard provides @code{va_copy} for copying
4775 @code{va_list} variables.  It may be available in older environments
4776 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4777 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4778 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4779 portability.
4781 @item @code{va_list}
4782 @c @fuindex va_list
4783 @prindex @code{va_list}
4784 @code{va_list} is not necessarily just a pointer.  It can be a
4785 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4786 not portable.  Or it can be an array (e.g., @command{gcc} in some
4787 PowerPC configurations), which means as a function parameter it can be
4788 effectively call-by-reference and library routines might modify the
4789 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4790 2.1).
4792 @item Signed @code{>>}
4793 Normally the C @code{>>} right shift of a signed type replicates the
4794 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4795 taken since Standard C doesn't require that behavior.  On those
4796 few processors without a native arithmetic shift (for instance Cray
4797 vector systems) zero bits may be shifted in, the same as a shift of an
4798 unsigned type.
4800 @item Integer @code{/}
4801 C divides signed integers by truncating their quotient toward zero,
4802 yielding the same result as Fortran.  However, before C99 the standard
4803 allowed C implementations to take the floor or ceiling of the quotient
4804 in some cases.  Hardly any implementations took advantage of this
4805 freedom, though, and it's probably not worth worrying about this issue
4806 nowadays.
4807 @end table
4810 @node Particular Functions
4811 @subsection Particular Function Checks
4812 @cindex Function, checking
4814 These macros check for particular C functions---whether they exist, and
4815 in some cases how they respond when given certain arguments.
4817 @anchor{AC_FUNC_ALLOCA}
4818 @defmac AC_FUNC_ALLOCA
4819 @acindex{FUNC_ALLOCA}
4820 @cvindex C_ALLOCA
4821 @cvindex HAVE_ALLOCA_H
4822 @ovindex ALLOCA
4823 @c @fuindex alloca
4824 @prindex @code{alloca}
4825 @hdrindex{alloca.h}
4826 @c @caindex working_alloca_h
4827 Check how to get @code{alloca}.  Tries to get a builtin version by
4828 checking for @file{alloca.h} or the predefined C preprocessor macros
4829 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4830 it defines @code{HAVE_ALLOCA_H}.
4832 If those attempts fail, it looks for the function in the standard C
4833 library.  If any of those methods succeed, it defines
4834 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4835 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4836 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4837 garbage collect).  This variable is separate from @code{LIBOBJS} so
4838 multiple programs can share the value of @code{ALLOCA} without needing
4839 to create an actual library, in case only some of them use the code in
4840 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4841 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4843 This macro does not try to get @code{alloca} from the System V R3
4844 @file{libPW} or the System V R4 @file{libucb} because those libraries
4845 contain some incompatible functions that cause trouble.  Some versions
4846 do not even contain @code{alloca} or contain a buggy version.  If you
4847 still want to use their @code{alloca}, use @code{ar} to extract
4848 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4850 Source files that use @code{alloca} should start with a piece of code
4851 like the following, to declare it properly.
4853 @example
4854 @group
4855 #ifdef STDC_HEADERS
4856 # include <stdlib.h>
4857 # include <stddef.h>
4858 #else
4859 # ifdef HAVE_STDLIB_H
4860 #  include <stdlib.h>
4861 # endif
4862 #endif
4863 #ifdef HAVE_ALLOCA_H
4864 # include <alloca.h>
4865 #elif defined __GNUC__
4866 # define alloca __builtin_alloca
4867 #elif defined _AIX
4868 # define alloca __alloca
4869 #elif defined _MSC_VER
4870 # include <malloc.h>
4871 # define alloca _alloca
4872 #else
4873 # ifndef HAVE_ALLOCA
4874 #  ifdef  __cplusplus
4875 extern "C"
4876 #  endif
4877 void *alloca (size_t);
4878 # endif
4879 #endif
4880 @end group
4881 @end example
4882 @end defmac
4884 @defmac AC_FUNC_CHOWN
4885 @acindex{FUNC_CHOWN}
4886 @cvindex HAVE_CHOWN
4887 @c @fuindex chown
4888 @prindex @code{chown}
4889 @caindex func_chown_works
4890 If the @code{chown} function is available and works (in particular, it
4891 should accept @option{-1} for @code{uid} and @code{gid}), define
4892 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4893 @code{ac_cv_func_chown_works} variable.
4894 @end defmac
4896 @anchor{AC_FUNC_CLOSEDIR_VOID}
4897 @defmac AC_FUNC_CLOSEDIR_VOID
4898 @acindex{FUNC_CLOSEDIR_VOID}
4899 @cvindex CLOSEDIR_VOID
4900 @c @fuindex closedir
4901 @prindex @code{closedir}
4902 @caindex func_closedir_void
4903 If the @code{closedir} function does not return a meaningful value,
4904 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4905 return value for an error indicator.
4907 Currently this test is implemented by running a test program.  When
4908 cross compiling the pessimistic assumption that @code{closedir} does not
4909 return a meaningful value is made.
4911 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4912 variable.
4914 This macro is obsolescent, as @code{closedir} returns a meaningful value
4915 on current systems.  New programs need not use this macro.
4916 @end defmac
4918 @defmac AC_FUNC_ERROR_AT_LINE
4919 @acindex{FUNC_ERROR_AT_LINE}
4920 @c @fuindex error_at_line
4921 @prindex @code{error_at_line}
4922 @caindex lib_error_at_line
4923 If the @code{error_at_line} function is not found, require an
4924 @code{AC_LIBOBJ} replacement of @samp{error}.
4926 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4927 variable.
4929 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4930 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4931 @end defmac
4933 @defmac AC_FUNC_FNMATCH
4934 @acindex{FUNC_FNMATCH}
4935 @c @fuindex fnmatch
4936 @prindex @code{fnmatch}
4937 @caindex func_fnmatch_works
4938 If the @code{fnmatch} function conforms to Posix, define
4939 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4940 the bugs in Solaris 2.4.
4942 Unlike the other specific
4943 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4944 broken/missing @code{fnmatch}.  This is for historical reasons.
4945 See @code{AC_REPLACE_FNMATCH} below.
4947 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4948 variable.
4950 This macro is obsolescent.  New programs should use Gnulib's
4951 @code{fnmatch-posix} module.  @xref{Gnulib}.
4952 @end defmac
4954 @defmac AC_FUNC_FNMATCH_GNU
4955 @acindex{FUNC_FNMATCH_GNU}
4956 @c @fuindex fnmatch
4957 @prindex @code{fnmatch}
4958 @caindex func_fnmatch_gnu
4959 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4960 whether @code{fnmatch} supports GNU extensions.  Detect common
4961 implementation bugs, for example, the bugs in the GNU C
4962 Library 2.1.
4964 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4965 variable.
4967 This macro is obsolescent.  New programs should use Gnulib's
4968 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4969 @end defmac
4971 @anchor{AC_FUNC_FORK}
4972 @defmac AC_FUNC_FORK
4973 @acindex{FUNC_FORK}
4974 @cvindex HAVE_VFORK_H
4975 @cvindex HAVE_WORKING_FORK
4976 @cvindex HAVE_WORKING_VFORK
4977 @cvindex vfork
4978 @c @fuindex fork
4979 @prindex @code{fork}
4980 @c @fuindex vfork
4981 @prindex @code{vfork}
4982 @hdrindex{vfork.h}
4983 @c @caindex func_fork
4984 @c @caindex func_fork_works
4985 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4986 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4987 checks whether @code{fork} is just a stub by trying to run it.
4989 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4990 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4991 define @code{vfork} to be @code{fork} for backward compatibility with
4992 previous versions of @command{autoconf}.  This macro checks for several known
4993 errors in implementations of @code{vfork} and considers the system to not
4994 have a working @code{vfork} if it detects any of them.  It is not considered
4995 to be an implementation error if a child's invocation of @code{signal}
4996 modifies the parent's signal handler, since child processes rarely change
4997 their signal handlers.
4999 Since this macro defines @code{vfork} only for backward compatibility with
5000 previous versions of @command{autoconf} you're encouraged to define it
5001 yourself in new code:
5002 @example
5003 @group
5004 #ifndef HAVE_WORKING_VFORK
5005 # define vfork fork
5006 #endif
5007 @end group
5008 @end example
5010 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5011 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5012 test, you also need to set the @code{ac_cv_func_fork} and
5013 @code{ac_cv_func_vfork} variables.
5014 @end defmac
5016 @defmac AC_FUNC_FSEEKO
5017 @acindex{FUNC_FSEEKO}
5018 @cvindex _LARGEFILE_SOURCE
5019 @cvindex HAVE_FSEEKO
5020 @c @fuindex fseeko
5021 @prindex @code{fseeko}
5022 @c @fuindex ftello
5023 @prindex @code{ftello}
5024 @c @caindex sys_largefile_source
5025 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5026 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5027 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5028 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5029 largefile-sensitive systems where @code{off_t} does not default to a
5030 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5031 @end defmac
5033 @defmac AC_FUNC_GETGROUPS
5034 @acindex{FUNC_GETGROUPS}
5035 @cvindex HAVE_GETGROUPS
5036 @ovindex GETGROUPS_LIBS
5037 @c @fuindex getgroups
5038 @prindex @code{getgroups}
5039 @caindex func_getgroups_works
5040 If the @code{getgroups} function is available and works (unlike on
5041 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5042 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5043 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5044 @end defmac
5046 @anchor{AC_FUNC_GETLOADAVG}
5047 @defmac AC_FUNC_GETLOADAVG
5048 @acindex{FUNC_GETLOADAVG}
5049 @cvindex SVR4
5050 @cvindex DGUX
5051 @cvindex UMAX
5052 @cvindex UMAX4_3
5053 @cvindex HAVE_NLIST_H
5054 @cvindex NLIST_NAME_UNION
5055 @cvindex GETLOADAVG_PRIVILEGED
5056 @cvindex NEED_SETGID
5057 @cvindex C_GETLOADAVG
5058 @ovindex LIBOBJS
5059 @ovindex NEED_SETGID
5060 @ovindex KMEM_GROUP
5061 @ovindex GETLOADAVG_LIBS
5062 @c @fuindex getloadavg
5063 @prindex @code{getloadavg}
5064 Check how to get the system load averages.  To perform its tests
5065 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5066 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5067 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5069 If the system has the @code{getloadavg} function, define
5070 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5071 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5072 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5073 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5074 possibly define several other C preprocessor macros and output
5075 variables:
5077 @enumerate
5078 @item
5079 Define @code{C_GETLOADAVG}.
5081 @item
5082 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5083 those systems.
5085 @item
5086 @hdrindex{nlist.h}
5087 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5089 @item
5090 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5091 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5092 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5094 @item
5095 Programs may need to be installed set-group-ID (or set-user-ID) for
5096 @code{getloadavg} to work.  In this case, define
5097 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5098 to @samp{true} (and otherwise to @samp{false}), and set
5099 @code{KMEM_GROUP} to the name of the group that should own the installed
5100 program.
5101 @end enumerate
5103 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5104 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5105 @end defmac
5107 @anchor{AC_FUNC_GETMNTENT}
5108 @defmac AC_FUNC_GETMNTENT
5109 @acindex{FUNC_GETMNTENT}
5110 @cvindex HAVE_GETMNTENT
5111 @c @fuindex getmntent
5112 @prindex @code{getmntent}
5113 @caindex search_getmntent
5114 Check for @code{getmntent} in the standard C library, and then in the
5115 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5116 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5117 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5118 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5119 @code{ac_cv_func_getmntent} to @code{no}.
5121 The result of this macro can be overridden by setting the cache variable
5122 @code{ac_cv_search_getmntent}.
5123 @end defmac
5125 @defmac AC_FUNC_GETPGRP
5126 @acindex{FUNC_GETPGRP}
5127 @cvindex GETPGRP_VOID
5128 @c @fuindex getpgid
5129 @c @fuindex getpgrp
5130 @prindex @code{getpgid}
5131 @prindex @code{getpgrp}
5132 @caindex func_getpgrp_void
5133 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5134 @code{getpgrp}; this is the Posix behavior.  On older BSD
5135 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5136 behaves like Posix's @code{getpgid}.
5138 @example
5139 #ifdef GETPGRP_VOID
5140   pid = getpgrp ();
5141 #else
5142   pid = getpgrp (0);
5143 #endif
5144 @end example
5146 This macro does not check whether
5147 @code{getpgrp} exists at all; if you need to work in that situation,
5148 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5150 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5151 variable.
5153 This macro is obsolescent, as current systems have a @code{getpgrp}
5154 whose signature conforms to Posix.  New programs need not use this macro.
5155 @end defmac
5157 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5158 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5159 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5160 @c @fuindex lstat
5161 @prindex @code{lstat}
5162 @caindex func_lstat_dereferences_slashed_symlink
5163 If @file{link} is a symbolic link, then @code{lstat} should treat
5164 @file{link/} the same as @file{link/.}.  However, many older
5165 @code{lstat} implementations incorrectly ignore trailing slashes.
5167 It is safe to assume that if @code{lstat} incorrectly ignores
5168 trailing slashes, then other symbolic-link-aware functions like
5169 @code{unlink} also incorrectly ignore trailing slashes.
5171 If @code{lstat} behaves properly, define
5172 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5173 @code{AC_LIBOBJ} replacement of @code{lstat}.
5175 The result of this macro is cached in the
5176 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5178 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5179 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5180 @end defmac
5182 @defmac AC_FUNC_MALLOC
5183 @acindex{FUNC_MALLOC}
5184 @cvindex HAVE_MALLOC
5185 @cvindex malloc
5186 @c @fuindex malloc
5187 @prindex @code{malloc}
5188 @caindex func_malloc_0_nonnull
5189 If the @code{malloc} function is compatible with the GNU C
5190 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5191 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5192 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5193 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5194 native @code{malloc} is not used in the main project.
5196 Typically, the replacement file @file{malloc.c} should look like (note
5197 the @samp{#undef malloc}):
5199 @verbatim
5200 #include <config.h>
5201 #undef malloc
5203 #include <sys/types.h>
5205 void *malloc ();
5207 /* Allocate an N-byte block of memory from the heap.
5208    If N is zero, allocate a 1-byte block.  */
5210 void *
5211 rpl_malloc (size_t n)
5213   if (n == 0)
5214     n = 1;
5215   return malloc (n);
5217 @end verbatim
5219 The result of this macro is cached in the
5220 @code{ac_cv_func_malloc_0_nonnull} variable.
5221 @end defmac
5223 @defmac AC_FUNC_MBRTOWC
5224 @acindex{FUNC_MBRTOWC}
5225 @cvindex HAVE_MBRTOWC
5226 @c @fuindex mbrtowc
5227 @prindex @code{mbrtowc}
5228 @caindex func_mbrtowc
5229 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5230 type @code{mbstate_t} are properly declared.
5232 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5233 variable.
5234 @end defmac
5236 @defmac AC_FUNC_MEMCMP
5237 @acindex{FUNC_MEMCMP}
5238 @ovindex LIBOBJS
5239 @c @fuindex memcmp
5240 @prindex @code{memcmp}
5241 @caindex func_memcmp_working
5242 If the @code{memcmp} function is not available, or does not work on
5243 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5244 bytes or more and with at least one buffer not starting on a 4-byte
5245 boundary (such as the one on NeXT x86 OpenStep), require an
5246 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5248 The result of this macro is cached in the
5249 @code{ac_cv_func_memcmp_working} variable.
5251 This macro is obsolescent, as current systems have a working
5252 @code{memcmp}.  New programs need not use this macro.
5253 @end defmac
5255 @defmac AC_FUNC_MKTIME
5256 @acindex{FUNC_MKTIME}
5257 @ovindex LIBOBJS
5258 @c @fuindex mktime
5259 @prindex @code{mktime}
5260 @caindex func_working_mktime
5261 If the @code{mktime} function is not available, or does not work
5262 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5263 For the purposes of this test, @code{mktime} should conform to the
5264 Posix standard and should be the inverse of
5265 @code{localtime}.
5267 The result of this macro is cached in the
5268 @code{ac_cv_func_working_mktime} variable.
5270 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5271 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5272 @end defmac
5274 @anchor{AC_FUNC_MMAP}
5275 @defmac AC_FUNC_MMAP
5276 @acindex{FUNC_MMAP}
5277 @cvindex HAVE_MMAP
5278 @c @fuindex mmap
5279 @prindex @code{mmap}
5280 @caindex func_mmap_fixed_mapped
5281 If the @code{mmap} function exists and works correctly, define
5282 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5283 memory.
5285 The result of this macro is cached in the
5286 @code{ac_cv_func_mmap_fixed_mapped} variable.
5287 @end defmac
5289 @defmac AC_FUNC_OBSTACK
5290 @acindex{FUNC_OBSTACK}
5291 @cvindex HAVE_OBSTACK
5292 @cindex obstack
5293 @caindex func_obstack
5294 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5295 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5297 The result of this macro is cached in the @code{ac_cv_func_obstack}
5298 variable.
5299 @end defmac
5301 @defmac AC_FUNC_REALLOC
5302 @acindex{FUNC_REALLOC}
5303 @cvindex HAVE_REALLOC
5304 @cvindex realloc
5305 @c @fuindex realloc
5306 @prindex @code{realloc}
5307 @caindex func_realloc_0_nonnull
5308 If the @code{realloc} function is compatible with the GNU C
5309 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5310 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5311 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5312 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5313 the native @code{realloc} is not used in the main project.  See
5314 @code{AC_FUNC_MALLOC} for details.
5316 The result of this macro is cached in the
5317 @code{ac_cv_func_realloc_0_nonnull} variable.
5318 @end defmac
5320 @defmac AC_FUNC_SELECT_ARGTYPES
5321 @acindex{FUNC_SELECT_ARGTYPES}
5322 @cvindex SELECT_TYPE_ARG1
5323 @cvindex SELECT_TYPE_ARG234
5324 @cvindex SELECT_TYPE_ARG5
5325 @c @fuindex select
5326 @prindex @code{select}
5327 @c @caindex func_select_args
5328 Determines the correct type to be passed for each of the
5329 @code{select} function's arguments, and defines those types
5330 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5331 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5332 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5333 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5335 This macro is obsolescent, as current systems have a @code{select} whose
5336 signature conforms to Posix.  New programs need not use this macro.
5337 @end defmac
5339 @defmac AC_FUNC_SETPGRP
5340 @acindex{FUNC_SETPGRP}
5341 @cvindex SETPGRP_VOID
5342 @c @fuindex setpgrp
5343 @prindex @code{setpgrp}
5344 @caindex func_setpgrp_void
5345 If @code{setpgrp} takes no argument (the Posix version), define
5346 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5347 two process IDs as arguments.  This macro does not check whether
5348 @code{setpgrp} exists at all; if you need to work in that situation,
5349 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5351 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5352 variable.
5354 This macro is obsolescent, as current systems have a @code{setpgrp}
5355 whose signature conforms to Posix.  New programs need not use this macro.
5356 @end defmac
5358 @defmac AC_FUNC_STAT
5359 @defmacx AC_FUNC_LSTAT
5360 @acindex{FUNC_STAT}
5361 @acindex{FUNC_LSTAT}
5362 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5363 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5364 @c @fuindex stat
5365 @prindex @code{stat}
5366 @c @fuindex lstat
5367 @prindex @code{lstat}
5368 @caindex func_stat_empty_string_bug
5369 @caindex func_lstat_empty_string_bug
5370 Determine whether @code{stat} or @code{lstat} have the bug that it
5371 succeeds when given the zero-length file name as argument.  The @code{stat}
5372 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5373 this.
5375 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5376 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5377 replacement of it.
5379 The results of these macros are cached in the
5380 @code{ac_cv_func_stat_empty_string_bug} and the
5381 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5383 These macros are obsolescent, as no current systems have the bug.
5384 New programs need not use these macros.
5385 @end defmac
5387 @anchor{AC_FUNC_STRCOLL}
5388 @defmac AC_FUNC_STRCOLL
5389 @acindex{FUNC_STRCOLL}
5390 @cvindex HAVE_STRCOLL
5391 @c @fuindex strcoll
5392 @prindex @code{strcoll}
5393 @caindex func_strcoll_works
5394 If the @code{strcoll} function exists and works correctly, define
5395 @code{HAVE_STRCOLL}.  This does a bit more than
5396 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5397 definitions of @code{strcoll} that should not be used.
5399 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5400 variable.
5401 @end defmac
5403 @defmac AC_FUNC_STRERROR_R
5404 @acindex{FUNC_STRERROR_R}
5405 @cvindex HAVE_STRERROR_R
5406 @cvindex HAVE_DECL_STRERROR_R
5407 @cvindex STRERROR_R_CHAR_P
5408 @c @fuindex strerror_r
5409 @caindex func_strerror_r_char_p
5410 @prindex @code{strerror_r}
5411 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5412 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5413 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5414 returns an @code{int} error number.  The Thread-Safe Functions option of
5415 Posix requires @code{strerror_r} to return @code{int}, but
5416 many systems (including, for example, version 2.2.4 of the GNU C
5417 Library) return a @code{char *} value that is not necessarily equal to
5418 the buffer argument.
5420 The result of this macro is cached in the
5421 @code{ac_cv_func_strerror_r_char_p} variable.
5422 @end defmac
5424 @anchor{AC_FUNC_STRFTIME}
5425 @defmac AC_FUNC_STRFTIME
5426 @acindex{FUNC_STRFTIME}
5427 @cvindex HAVE_STRFTIME
5428 @c @fuindex strftime
5429 @prindex @code{strftime}
5430 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5431 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5433 This macro is obsolescent, as no current systems require the @file{intl}
5434 library for @code{strftime}.  New programs need not use this macro.
5435 @end defmac
5437 @defmac AC_FUNC_STRTOD
5438 @acindex{FUNC_STRTOD}
5439 @ovindex POW_LIB
5440 @c @fuindex strtod
5441 @prindex @code{strtod}
5442 @caindex func_strtod
5443 @caindex func_pow
5444 If the @code{strtod} function does not exist or doesn't work correctly,
5445 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5446 because @file{strtod.c} is likely to need @samp{pow}, set the output
5447 variable @code{POW_LIB} to the extra library needed.
5449 This macro caches its result in the @code{ac_cv_func_strtod} variable
5450 and depends upon the result in the @code{ac_cv_func_pow} variable.
5452 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5453 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5454 @end defmac
5456 @defmac AC_FUNC_STRTOLD
5457 @acindex{FUNC_STRTOLD}
5458 @cvindex HAVE_STRTOLD
5459 @prindex @code{strtold}
5460 @caindex func_strtold
5461 If the @code{strtold} function exists and conforms to C99, define
5462 @code{HAVE_STRTOLD}.
5464 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5465 @end defmac
5467 @defmac AC_FUNC_STRNLEN
5468 @acindex{FUNC_STRNLEN}
5469 @cvindex HAVE_STRNLEN
5470 @c @fuindex strnlen
5471 @prindex @code{strnlen}
5472 @caindex func_strnlen_working
5473 If the @code{strnlen} function is not available, or is buggy (like the one
5474 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5476 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5477 variable.
5478 @end defmac
5480 @anchor{AC_FUNC_UTIME_NULL}
5481 @defmac AC_FUNC_UTIME_NULL
5482 @acindex{FUNC_UTIME_NULL}
5483 @cvindex HAVE_UTIME_NULL
5484 @c @fuindex utime
5485 @prindex @code{utime}
5486 @caindex func_utime_null
5487 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5488 the present, define @code{HAVE_UTIME_NULL}.
5490 This macro caches its result in the @code{ac_cv_func_utime_null}
5491 variable.
5493 This macro is obsolescent, as all current systems have a @code{utime}
5494 that behaves this way.  New programs need not use this macro.
5495 @end defmac
5497 @anchor{AC_FUNC_VPRINTF}
5498 @defmac AC_FUNC_VPRINTF
5499 @acindex{FUNC_VPRINTF}
5500 @cvindex HAVE_VPRINTF
5501 @cvindex HAVE_DOPRNT
5502 @c @fuindex vprintf
5503 @prindex @code{vprintf}
5504 @c @fuindex vsprintf
5505 @prindex @code{vsprintf}
5506 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5507 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5508 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5509 are also available.)
5511 This macro is obsolescent, as all current systems have @code{vprintf}.
5512 New programs need not use this macro.
5513 @end defmac
5515 @defmac AC_REPLACE_FNMATCH
5516 @acindex{REPLACE_FNMATCH}
5517 @c @fuindex fnmatch
5518 @prindex @code{fnmatch}
5519 @hdrindex{fnmatch.h}
5520 @caindex func_fnmatch_works
5521 If the @code{fnmatch} function does not conform to Posix (see
5522 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5524 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5525 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5526 copy of the source code of GNU @code{fnmatch}.  If necessary,
5527 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5528 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5529 included in place of the system @code{<fnmatch.h>}.
5531 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5532 variable.
5534 This macro is obsolescent, as it assumes the use of particular source
5535 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5536 which provides this macro along with the source files.  @xref{Gnulib}.
5537 @end defmac
5541 @node Generic Functions
5542 @subsection Generic Function Checks
5544 These macros are used to find functions not covered by the ``particular''
5545 test macros.  If the functions might be in libraries other than the
5546 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5547 If you need to check the behavior of a function as well as find out
5548 whether it is present, you have to write your own test for
5549 it (@pxref{Writing Tests}).
5551 @anchor{AC_CHECK_FUNC}
5552 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5553   @ovar{action-if-not-found})
5554 @acindex{CHECK_FUNC}
5555 @caindex func_@var{function}
5556 If C function @var{function} is available, run shell commands
5557 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5558 want to define a symbol if the function is available, consider using
5559 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5560 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5561 standardized than C++.  (@pxref{Language Choice}, for more information
5562 about selecting the language for checks.)
5564 This macro caches its result in the @code{ac_cv_func_@var{function}}
5565 variable.
5566 @end defmac
5568 @anchor{AC_CHECK_FUNCS}
5569 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5570   @ovar{action-if-not-found})
5571 @acindex{CHECK_FUNCS}
5572 @cvindex HAVE_@var{function}
5573 For each @var{function} enumerated in the blank-or-newline-separated argument
5574 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5575 If @var{action-if-found} is given, it is additional shell code to
5576 execute when one of the functions is found.  You can give it a value of
5577 @samp{break} to break out of the loop on the first match.  If
5578 @var{action-if-not-found} is given, it is executed when one of the
5579 functions is not found.
5581 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5582 @end defmac
5584 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5585 @acindex{CHECK_FUNCS_ONCE}
5586 @cvindex HAVE_@var{function}
5587 For each @var{function} enumerated in the blank-or-newline-separated argument
5588 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5589 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5590 checking code at most once, so that @command{configure} is smaller and
5591 faster; but the checks cannot be conditionalized and are always done once,
5592 early during the @command{configure} run.
5593 @end defmac
5595 @sp 1
5597 Autoconf follows a philosophy that was formed over the years by those
5598 who have struggled for portability: isolate the portability issues in
5599 specific files, and then program as if you were in a Posix
5600 environment.  Some functions may be missing or unfixable, and your
5601 package must be ready to replace them.
5603 Suitable replacements for many such problem functions are available from
5604 Gnulib (@pxref{Gnulib}).
5606 @defmac AC_LIBOBJ (@var{function})
5607 @acindex{LIBOBJ}
5608 @ovindex LIBOBJS
5609 Specify that @samp{@var{function}.c} must be included in the executables
5610 to replace a missing or broken implementation of @var{function}.
5612 @vrindex ac_objext
5613 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5614 variable @code{LIBOBJS} if it is not already in, and calls
5615 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5616 directly change @code{LIBOBJS}, since this is not traceable.
5617 @end defmac
5619 @defmac AC_LIBSOURCE (@var{file})
5620 @acindex{LIBSOURCE}
5621 Specify that @var{file} might be needed to compile the project.  If you
5622 need to know what files might be needed by a @file{configure.ac}, you
5623 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5625 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5626 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5627 that case, since shell variables cannot be traced statically, you must
5628 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5629 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5630 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5631 @code{"foo"} or @code{"bar"}, you should do:
5633 @example
5634 AC_LIBSOURCE([foo.c])
5635 AC_LIBSOURCE([bar.c])
5636 AC_LIBOBJ([$foo_or_bar])
5637 @end example
5639 @noindent
5640 There is usually a way to avoid this, however, and you are encouraged to
5641 simply call @code{AC_LIBOBJ} with literal arguments.
5643 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5644 slightly different semantics: the old macro took the function name,
5645 e.g., @code{foo}, as its argument rather than the file name.
5646 @end defmac
5648 @defmac AC_LIBSOURCES (@var{files})
5649 @acindex{LIBSOURCES}
5650 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5651 comma-separated M4 list.  Thus, the above example might be rewritten:
5653 @example
5654 AC_LIBSOURCES([foo.c, bar.c])
5655 AC_LIBOBJ([$foo_or_bar])
5656 @end example
5657 @end defmac
5659 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5660 @acindex{CONFIG_LIBOBJ_DIR}
5661 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5662 @var{directory}, a name relative to the top level of the
5663 source tree.  The replacement directory defaults to @file{.}, the top
5664 level directory, and the most typical value is @file{lib}, corresponding
5665 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5667 @command{configure} might need to know the replacement directory for the
5668 following reasons: (i) some checks use the replacement files, (ii) some
5669 macros bypass broken system headers by installing links to the
5670 replacement headers (iii) when used in conjunction with Automake,
5671 within each makefile, @var{directory} is used as a relative path
5672 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5673 @code{LTLIBOBJS}, etc.
5674 @end defmac
5676 @sp 1
5678 It is common to merely check for the existence of a function, and ask
5679 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5680 a convenient shorthand.
5682 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5683 @acindex{REPLACE_FUNCS}
5684 @cvindex HAVE_@var{function}
5685 @ovindex LIBOBJS
5686 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5687 @var{action-if-not-found}.  You can declare your replacement function by
5688 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5689 system has the function, it probably declares it in a header file you
5690 should be including, so you shouldn't redeclare it lest your declaration
5691 conflict.
5692 @end defmac
5694 @node Header Files
5695 @section Header Files
5696 @cindex Header, checking
5698 The following macros check for the presence of certain C header files.
5699 If there is no macro specifically defined to check for a header file you need,
5700 and you don't need to check for any special properties of
5701 it, then you can use one of the general header-file check macros.
5703 @menu
5704 * Header Portability::          Collected knowledge on common headers
5705 * Particular Headers::          Special handling to find certain headers
5706 * Generic Headers::             How to find other headers
5707 @end menu
5709 @node Header Portability
5710 @subsection Portability of Headers
5711 @cindex Portability of headers
5712 @cindex Header portability
5714 This section documents some collected knowledge about common headers,
5715 and the problems they cause.  By definition, this list always requires
5716 additions.  A much more complete list is maintained by the Gnulib
5717 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5718 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5719 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5720 the gnulib list as complete as possible.
5722 @table @asis
5724 @item @file{limits.h}
5725 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5726 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5727 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5728 define them.
5730 @item @file{inttypes.h} vs.@: @file{stdint.h}
5731 @hdrindex{inttypes.h}
5732 @hdrindex{stdint.h}
5733 The C99 standard says that @file{inttypes.h} includes
5734 @file{stdint.h}, so there's no need to include @file{stdint.h}
5735 separately in a standard environment.  Some implementations have
5736 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5737 know of any implementation that has @file{stdint.h} but not
5738 @file{inttypes.h}.
5740 @item @file{linux/irda.h}
5741 @hdrindex{linux/irda.h}
5742 It requires @file{linux/types.h} and @file{sys/socket.h}.
5744 @item @file{linux/random.h}
5745 @hdrindex{linux/random.h}
5746 It requires @file{linux/types.h}.
5748 @item @file{net/if.h}
5749 @hdrindex{net/if.h}
5750 On Darwin, this file requires that @file{sys/socket.h} be included
5751 beforehand.  One should run:
5753 @example
5754 AC_CHECK_HEADERS([sys/socket.h])
5755 AC_CHECK_HEADERS([net/if.h], [], [],
5756 [#include <stdio.h>
5757 #ifdef STDC_HEADERS
5758 # include <stdlib.h>
5759 # include <stddef.h>
5760 #else
5761 # ifdef HAVE_STDLIB_H
5762 #  include <stdlib.h>
5763 # endif
5764 #endif
5765 #ifdef HAVE_SYS_SOCKET_H
5766 # include <sys/socket.h>
5767 #endif
5769 @end example
5771 @item @file{netinet/if_ether.h}
5772 @hdrindex{netinet/if_ether.h}
5773 On Darwin, this file requires that @file{stdio.h} and
5774 @file{sys/socket.h} be included beforehand.  One should run:
5776 @example
5777 AC_CHECK_HEADERS([sys/socket.h])
5778 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5779 [#include <stdio.h>
5780 #ifdef STDC_HEADERS
5781 # include <stdlib.h>
5782 # include <stddef.h>
5783 #else
5784 # ifdef HAVE_STDLIB_H
5785 #  include <stdlib.h>
5786 # endif
5787 #endif
5788 #ifdef HAVE_SYS_SOCKET_H
5789 # include <sys/socket.h>
5790 #endif
5792 @end example
5794 @item @file{stdint.h}
5795 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5797 @item @file{stdlib.h}
5798 @hdrindex{stdlib.h}
5799 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5801 @item @file{sys/mount.h}
5802 @hdrindex{sys/mount.h}
5803 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5804 @file{sys/params.h} is a prerequisite.
5806 @item @file{sys/ptem.h}
5807 @hdrindex{sys/ptem.h}
5808 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5810 @item @file{sys/socket.h}
5811 @hdrindex{sys/socket.h}
5812 On Darwin, @file{stdlib.h} is a prerequisite.
5814 @item @file{sys/ucred.h}
5815 @hdrindex{sys/ucred.h}
5816 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5818 @item @file{X11/extensions/scrnsaver.h}
5819 @hdrindex{X11/extensions/scrnsaver.h}
5820 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5821 so required that you might not even consider looking for it.
5823 @example
5824 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5825 [[#include <X11/Xlib.h>
5827 @end example
5828 @end table
5831 @node Particular Headers
5832 @subsection Particular Header Checks
5834 These macros check for particular system header files---whether they
5835 exist, and in some cases whether they declare certain symbols.
5837 @defmac AC_CHECK_HEADER_STDBOOL
5838 @acindex{CHECK_HEADER_STDBOOL}
5839 @cvindex HAVE__BOOL
5840 @hdrindex{stdbool.h}
5841 @caindex header_stdbool_h
5842 Check whether @file{stdbool.h} exists and conforms to C99, and cache the
5843 result in the @code{ac_cv_header_stdbool_h} variable.  If the type
5844 @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5846 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5847 packages that supply a substitute @file{stdbool.h} on platforms lacking
5848 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5849 that explicitly checks for @file{stdbool.h}.
5850 @end defmac
5852 @defmac AC_HEADER_ASSERT
5853 @acindex{HEADER_ASSERT}
5854 @cvindex NDEBUG
5855 @hdrindex{assert.h}
5856 Check whether to enable assertions in the style of @file{assert.h}.
5857 Assertions are enabled by default, but the user can override this by
5858 invoking @command{configure} with the @option{--disable-assert} option.
5859 @end defmac
5861 @anchor{AC_HEADER_DIRENT}
5862 @defmac AC_HEADER_DIRENT
5863 @acindex{HEADER_DIRENT}
5864 @cvindex HAVE_DIRENT_H
5865 @cvindex HAVE_NDIR_H
5866 @cvindex HAVE_SYS_DIR_H
5867 @cvindex HAVE_SYS_NDIR_H
5868 @hdrindex{dirent.h}
5869 @hdrindex{sys/ndir.h}
5870 @hdrindex{sys/dir.h}
5871 @hdrindex{ndir.h}
5872 Check for the following header files.  For the first one that is
5873 found and defines @samp{DIR}, define the listed C preprocessor macro:
5875 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5876 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5877 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5878 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5879 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5880 @end multitable
5882 The directory-library declarations in your source code should look
5883 something like the following:
5885 @example
5886 @group
5887 #include <sys/types.h>
5888 #ifdef HAVE_DIRENT_H
5889 # include <dirent.h>
5890 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5891 #else
5892 # define dirent direct
5893 # define NAMLEN(dirent) ((dirent)->d_namlen)
5894 # ifdef HAVE_SYS_NDIR_H
5895 #  include <sys/ndir.h>
5896 # endif
5897 # ifdef HAVE_SYS_DIR_H
5898 #  include <sys/dir.h>
5899 # endif
5900 # ifdef HAVE_NDIR_H
5901 #  include <ndir.h>
5902 # endif
5903 #endif
5904 @end group
5905 @end example
5907 Using the above declarations, the program would declare variables to be
5908 of type @code{struct dirent}, not @code{struct direct}, and would access
5909 the length of a directory entry name by passing a pointer to a
5910 @code{struct dirent} to the @code{NAMLEN} macro.
5912 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5914 This macro is obsolescent, as all current systems with directory
5915 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5917 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5918 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5919 @end defmac
5921 @anchor{AC_HEADER_MAJOR}
5922 @defmac AC_HEADER_MAJOR
5923 @acindex{HEADER_MAJOR}
5924 @cvindex MAJOR_IN_MKDEV
5925 @cvindex MAJOR_IN_SYSMACROS
5926 @hdrindex{sys/mkdev.h}
5927 @hdrindex{sys/sysmacros.h}
5928 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5929 @code{makedev}, but @file{sys/mkdev.h} does, define
5930 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5931 @code{MAJOR_IN_SYSMACROS}.
5932 @end defmac
5934 @defmac AC_HEADER_RESOLV
5935 @acindex{HEADER_RESOLV}
5936 @cvindex HAVE_RESOLV_H
5937 @hdrindex{resolv.h}
5938 Checks for header @file{resolv.h}, checking for prerequisites first.
5939 To properly use @file{resolv.h}, your code should contain something like
5940 the following:
5942 @verbatim
5943 #ifdef HAVE_SYS_TYPES_H
5944 #  include <sys/types.h>
5945 #endif
5946 #ifdef HAVE_NETINET_IN_H
5947 #  include <netinet/in.h>   /* inet_ functions / structs */
5948 #endif
5949 #ifdef HAVE_ARPA_NAMESER_H
5950 #  include <arpa/nameser.h> /* DNS HEADER struct */
5951 #endif
5952 #ifdef HAVE_NETDB_H
5953 #  include <netdb.h>
5954 #endif
5955 #include <resolv.h>
5956 @end verbatim
5957 @end defmac
5959 @anchor{AC_HEADER_STAT}
5960 @defmac AC_HEADER_STAT
5961 @acindex{HEADER_STAT}
5962 @cvindex STAT_MACROS_BROKEN
5963 @hdrindex{sys/stat.h}
5964 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5965 @file{sys/stat.h} do not work properly (returning false positives),
5966 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5967 Amdahl UTS and Motorola System V/88.
5969 This macro is obsolescent, as no current systems have the bug.
5970 New programs need not use this macro.
5971 @end defmac
5973 @defmac AC_HEADER_STDBOOL
5974 @acindex{HEADER_STDBOOL}
5975 @cvindex HAVE_STDBOOL_H
5976 @cvindex HAVE__BOOL
5977 @hdrindex{stdbool.h}
5978 @caindex header_stdbool_h
5979 If @file{stdbool.h} exists and conforms to C99, define
5980 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5981 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5982 program could contain the following code:
5984 @example
5985 @group
5986 #ifdef HAVE_STDBOOL_H
5987 # include <stdbool.h>
5988 #else
5989 # ifndef HAVE__BOOL
5990 #  ifdef __cplusplus
5991 typedef bool _Bool;
5992 #  else
5993 #   define _Bool signed char
5994 #  endif
5995 # endif
5996 # define bool _Bool
5997 # define false 0
5998 # define true 1
5999 # define __bool_true_false_are_defined 1
6000 #endif
6001 @end group
6002 @end example
6004 Alternatively you can use the @samp{stdbool} package of Gnulib
6005 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6006 @code{#include <stdbool.h>}, and it adds support for less-common
6007 platforms.
6009 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6010 variable.
6012 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6013 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6014 does not.
6015 @end defmac
6017 @anchor{AC_HEADER_STDC}
6018 @defmac AC_HEADER_STDC
6019 @acindex{HEADER_STDC}
6020 @cvindex STDC_HEADERS
6021 @hdrindex{stdlib.h}
6022 @hdrindex{stdarg.h}
6023 @hdrindex{string.h}
6024 @hdrindex{float.h}
6025 @hdrindex{ctype.h}
6026 @caindex header_stdc
6027 Define @code{STDC_HEADERS} if the system has C header files
6028 conforming to ANSI C89 (ISO C90).
6029 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
6030 @file{string.h}, and @file{float.h}; if the system has those, it
6031 probably has the rest of the C89 header files.  This macro also
6032 checks whether @file{string.h} declares @code{memchr} (and thus
6033 presumably the other @code{mem} functions), whether @file{stdlib.h}
6034 declare @code{free} (and thus presumably @code{malloc} and other related
6035 functions), and whether the @file{ctype.h} macros work on characters
6036 with the high bit set, as the C standard requires.
6038 If you use this macro, your code can refer to @code{STDC_HEADERS} to
6039 determine whether the system has conforming header files (and probably C
6040 library functions).
6042 This macro caches its result in the @code{ac_cv_header_stdc} variable.
6044 This macro is obsolescent, as current systems have conforming header
6045 files.  New programs need not use this macro.
6047 @hdrindex{string.h}
6048 @hdrindex{strings.h}
6049 Nowadays @file{string.h} is part of the C standard and declares functions like
6050 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
6051 BSD functions like @code{bcopy}; but
6052 historically, string functions were a major sticking point in this area.
6053 If you still want to worry about portability to ancient systems without
6054 standard headers, there is so much variation
6055 that it is probably easier to declare the functions you use than to
6056 figure out exactly what the system header files declare.  Some ancient systems
6057 contained a mix of functions from the C standard and from BSD;
6058 some were mostly standard but lacked @samp{memmove}; some defined the
6059 BSD functions as macros in @file{string.h} or
6060 @file{strings.h}; some had only the BSD functions but
6061 @file{string.h}; some declared the memory functions in @file{memory.h},
6062 some in @file{string.h}; etc.  It is probably sufficient to check for
6063 one string function and one memory function; if the library had the
6064 standard versions of those then it probably had most of the others.
6065 If you put the following in @file{configure.ac}:
6067 @example
6068 # This example is obsolescent.
6069 # Nowadays you can omit these macro calls.
6070 AC_HEADER_STDC
6071 AC_CHECK_FUNCS([strchr memcpy])
6072 @end example
6074 @noindent
6075 then, in your code, you can use declarations like this:
6077 @example
6078 @group
6079 /* This example is obsolescent.
6080    Nowadays you can just #include <string.h>.  */
6081 #ifdef STDC_HEADERS
6082 # include <string.h>
6083 #else
6084 # ifndef HAVE_STRCHR
6085 #  define strchr index
6086 #  define strrchr rindex
6087 # endif
6088 char *strchr (), *strrchr ();
6089 # ifndef HAVE_MEMCPY
6090 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
6091 #  define memmove(d, s, n) bcopy ((s), (d), (n))
6092 # endif
6093 #endif
6094 @end group
6095 @end example
6097 @noindent
6098 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6099 or @code{strspn}, which have no BSD equivalent, then macros don't
6100 suffice to port to ancient hosts; you must provide an implementation of
6101 each function.  An easy
6102 way to incorporate your implementations only when needed (since the ones
6103 in system C libraries may be hand optimized) is to, taking @code{memchr}
6104 for example, put it in @file{memchr.c} and use
6105 @samp{AC_REPLACE_FUNCS([memchr])}.
6106 @end defmac
6108 @defmac AC_HEADER_SYS_WAIT
6109 @acindex{HEADER_SYS_WAIT}
6110 @cvindex HAVE_SYS_WAIT_H
6111 @hdrindex{sys/wait.h}
6112 @caindex header_sys_wait_h
6113 If @file{sys/wait.h} exists and is compatible with Posix, define
6114 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6115 does not exist, or if it uses the old BSD @code{union wait} instead
6116 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6117 Posix compatible, then instead of including it, define the
6118 Posix macros with their usual interpretations.  Here is an
6119 example:
6121 @example
6122 @group
6123 #include <sys/types.h>
6124 #ifdef HAVE_SYS_WAIT_H
6125 # include <sys/wait.h>
6126 #endif
6127 #ifndef WEXITSTATUS
6128 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6129 #endif
6130 #ifndef WIFEXITED
6131 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6132 #endif
6133 @end group
6134 @end example
6136 @noindent
6137 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6138 variable.
6140 This macro is obsolescent, as current systems are compatible with Posix.
6141 New programs need not use this macro.
6142 @end defmac
6144 @cvindex _POSIX_VERSION
6145 @hdrindex{unistd.h}
6146 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6147 Posix systems.  If there is no @file{unistd.h}, it is definitely
6148 not a Posix system.  However, some non-Posix systems do
6149 have @file{unistd.h}.
6151 The way to check whether the system supports Posix is:
6153 @example
6154 @group
6155 #ifdef HAVE_UNISTD_H
6156 # include <sys/types.h>
6157 # include <unistd.h>
6158 #endif
6160 #ifdef _POSIX_VERSION
6161 /* Code for Posix systems.  */
6162 #endif
6163 @end group
6164 @end example
6166 @anchor{AC_HEADER_TIME}
6167 @defmac AC_HEADER_TIME
6168 @acindex{HEADER_TIME}
6169 @cvindex TIME_WITH_SYS_TIME
6170 @hdrindex{time.h}
6171 @hdrindex{sys/time.h}
6172 @caindex header_time
6173 If a program may include both @file{time.h} and @file{sys/time.h},
6174 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6175 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6176 protected against multiple inclusion, so programs could not explicitly
6177 include both files.  This macro is useful in programs that use, for
6178 example, @code{struct timeval} as well as
6179 @code{struct tm}.  It is best used in conjunction with
6180 @code{HAVE_SYS_TIME_H}, which can be checked for using
6181 @code{AC_CHECK_HEADERS([sys/time.h])}.
6183 @example
6184 @group
6185 #ifdef TIME_WITH_SYS_TIME
6186 # include <sys/time.h>
6187 # include <time.h>
6188 #else
6189 # ifdef HAVE_SYS_TIME_H
6190 #  include <sys/time.h>
6191 # else
6192 #  include <time.h>
6193 # endif
6194 #endif
6195 @end group
6196 @end example
6198 @noindent
6199 This macro caches its result in the @code{ac_cv_header_time} variable.
6201 This macro is obsolescent, as current systems can include both files
6202 when they exist.  New programs need not use this macro.
6203 @end defmac
6206 @defmac AC_HEADER_TIOCGWINSZ
6207 @acindex{HEADER_TIOCGWINSZ}
6208 @cvindex GWINSZ_IN_SYS_IOCTL
6209 @hdrindex{sys/ioctl.h}
6210 @hdrindex{termios.h}
6211 @c FIXME: I need clarifications from Jim.
6212 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6213 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6214 found in @file{<termios.h>}.
6216 Use:
6218 @example
6219 @group
6220 #ifdef HAVE_TERMIOS_H
6221 # include <termios.h>
6222 #endif
6224 #ifdef GWINSZ_IN_SYS_IOCTL
6225 # include <sys/ioctl.h>
6226 #endif
6227 @end group
6228 @end example
6229 @end defmac
6231 @node Generic Headers
6232 @subsection Generic Header Checks
6234 These macros are used to find system header files not covered by the
6235 ``particular'' test macros.  If you need to check the contents of a header
6236 as well as find out whether it is present, you have to write your own
6237 test for it (@pxref{Writing Tests}).
6239 @anchor{AC_CHECK_HEADER}
6240 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6241   @ovar{action-if-not-found}, @ovar{includes})
6242 @acindex{CHECK_HEADER}
6243 @caindex header_@var{header-file}
6244 If the system header file @var{header-file} is compilable, execute shell
6245 commands @var{action-if-found}, otherwise execute
6246 @var{action-if-not-found}.  If you just want to define a symbol if the
6247 header file is available, consider using @code{AC_CHECK_HEADERS}
6248 instead.
6250 @var{includes} is decoded to determine the appropriate include
6251 directives.  If omitted or empty, @file{configure} will check for both header
6252 existence (with the preprocessor) and usability (with the compiler),
6253 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6254 there is a discrepancy between the results, a warning is issued to the
6255 user, and the compiler results are favored (@pxref{Present But
6256 Cannot Be Compiled}).  In general, favoring the compiler results means
6257 that a header will be treated as not found even though the file exists,
6258 because you did not provide enough prerequisites.
6260 Providing a non-empty @var{includes} argument allows the code to provide
6261 any prerequisites prior to including the header under test; it is common
6262 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6263 Includes}).  With an explicit fourth argument, no preprocessor test is
6264 needed.  As a special case, an @var{includes} of exactly @samp{-}
6265 triggers the older preprocessor check, which merely determines existence
6266 of the file in the preprocessor search path; this should only be used as
6267 a last resort (it is safer to determine the actual prerequisites and
6268 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6269 it obvious that only a preprocessor check is desired).
6271 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6272 variable, with characters not suitable for a variable name mapped to
6273 underscores.
6274 @end defmac
6276 @anchor{AC_CHECK_HEADERS}
6277 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6278   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6279   @ovar{includes})
6280 @acindex{CHECK_HEADERS}
6281 @cvindex HAVE_@var{header}
6282 @caindex header_@var{header-file}
6283 For each given system header file @var{header-file} in the
6284 blank-separated argument list that exists, define
6285 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6286 is given, it is additional shell code to execute when one of the header
6287 files is found.  You can give it a value of @samp{break} to break out of
6288 the loop on the first match.  If @var{action-if-not-found} is given, it
6289 is executed when one of the header files is not found.
6291 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6292 choose the set of preprocessor directives supplied before the header
6293 under test.
6295 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6296 variable, with characters not suitable for a variable name mapped to
6297 underscores.
6298 @end defmac
6300 Previous versions of Autoconf merely checked whether the header was
6301 accepted by the preprocessor.  This was changed because the old test was
6302 inappropriate for typical uses.  Headers are typically used to compile,
6303 not merely to preprocess, and the old behavior sometimes accepted
6304 headers that clashed at compile-time (@pxref{Present But Cannot Be
6305 Compiled}).  If you need to check whether a header is preprocessable,
6306 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6308 Actually requiring a header to compile improves the robustness of the
6309 test, but it also requires
6310 that you make sure that headers that must be included before the
6311 @var{header-file} be part of the @var{includes}, (@pxref{Default
6312 Includes}).  If looking for @file{bar.h}, which requires that
6313 @file{foo.h} be included before if it exists, we suggest the following
6314 scheme:
6316 @verbatim
6317 AC_CHECK_HEADERS([foo.h])
6318 AC_CHECK_HEADERS([bar.h], [], [],
6319 [#ifdef HAVE_FOO_H
6320 # include <foo.h>
6321 #endif
6323 @end verbatim
6325 The following variant generates smaller, faster @command{configure}
6326 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6328 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6329 @acindex{CHECK_HEADERS_ONCE}
6330 @cvindex HAVE_@var{header}
6331 For each given system header file @var{header-file} in the
6332 blank-separated argument list that exists, define
6333 @code{HAVE_@var{header-file}} (in all capitals).
6334 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6335 checking code at most once, so that @command{configure} is smaller and
6336 faster; but the checks cannot be conditionalized and are always done once,
6337 early during the @command{configure} run.  Thus, this macro is only safe
6338 for checking headers that do not have prerequisites beyond what
6339 @code{AC_INCLUDES_DEFAULT} provides.
6340 @end defmac
6342 @node Declarations
6343 @section Declarations
6344 @cindex Declaration, checking
6346 The following macros check for the declaration of variables and
6347 functions.  If there is no macro specifically defined to check for a
6348 symbol you need, then you can use the general macros (@pxref{Generic
6349 Declarations}) or, for more complex tests, you may use
6350 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6352 @menu
6353 * Particular Declarations::     Macros to check for certain declarations
6354 * Generic Declarations::        How to find other declarations
6355 @end menu
6357 @node Particular Declarations
6358 @subsection Particular Declaration Checks
6360 There are no specific macros for declarations.
6362 @node Generic Declarations
6363 @subsection Generic Declaration Checks
6365 These macros are used to find declarations not covered by the ``particular''
6366 test macros.
6368 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6369   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6370 @acindex{CHECK_DECL}
6371 @caindex have_decl_@var{symbol}
6372 If @var{symbol} (a function, variable, or constant) is not declared in
6373 @var{includes} and a declaration is needed, run the shell commands
6374 @var{action-if-not-found}, otherwise @var{action-if-found}.
6375 @var{includes} is a series of include directives, defaulting to
6376 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6377 prior to the declaration under test.
6379 This macro actually tests whether @var{symbol} is defined as a macro or
6380 can be used as an r-value, not whether it is really declared, because it
6381 is much safer to avoid introducing extra declarations when they are not
6382 needed.  In order to facilitate use of C++ and overloaded function
6383 declarations, it is possible to specify function argument types in
6384 parentheses for types which can be zero-initialized:
6386 @example
6387 AC_CHECK_DECL([basename(char *)])
6388 @end example
6390 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6391 variable, with characters not suitable for a variable name mapped to
6392 underscores.
6393 @end defmac
6395 @anchor{AC_CHECK_DECLS}
6396 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6397   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6398 @acindex{CHECK_DECLS}
6399 @cvindex HAVE_DECL_@var{symbol}
6400 @caindex have_decl_@var{symbol}
6401 For each of the @var{symbols} (@emph{comma}-separated list with optional
6402 function argument types for C++ overloads), define
6403 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6404 @var{symbol} is declared, otherwise to @samp{0}.  If
6405 @var{action-if-not-found} is given, it is additional shell code to
6406 execute when one of the function declarations is needed, otherwise
6407 @var{action-if-found} is executed.
6409 @var{includes} is a series of include directives, defaulting to
6410 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6411 prior to the declarations under test.
6413 This macro uses an M4 list as first argument:
6414 @example
6415 AC_CHECK_DECLS([strdup])
6416 AC_CHECK_DECLS([strlen])
6417 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6418 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6419 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6420 @end example
6422 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6423 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6424 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6425 @emph{sure} that the check was performed, use
6426 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6428 @example
6429 #if !HAVE_DECL_SYMBOL
6430 extern char *symbol;
6431 #endif
6432 @end example
6434 @noindent
6435 If the test may have not been performed, however, because it is safer
6436 @emph{not} to declare a symbol than to use a declaration that conflicts
6437 with the system's one, you should use:
6439 @example
6440 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6441 void *malloc (size_t *s);
6442 #endif
6443 @end example
6445 @noindent
6446 You fall into the second category only in extreme situations: either
6447 your files may be used without being configured, or they are used during
6448 the configuration.  In most cases the traditional approach is enough.
6450 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6451 variables, with characters not suitable for a variable name mapped to
6452 underscores.
6453 @end defmac
6455 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6456 @acindex{CHECK_DECLS_ONCE}
6457 @cvindex HAVE_DECL_@var{symbol}
6458 For each of the @var{symbols} (@emph{comma}-separated list), define
6459 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6460 @var{symbol} is declared in the default include files, otherwise to
6461 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6462 generates the checking code at most once, so that @command{configure} is
6463 smaller and faster; but the checks cannot be conditionalized and are
6464 always done once, early during the @command{configure} run.
6465 @end defmac
6468 @node Structures
6469 @section Structures
6470 @cindex Structure, checking
6472 The following macros check for the presence of certain members in C
6473 structures.  If there is no macro specifically defined to check for a
6474 member you need, then you can use the general structure-member macros
6475 (@pxref{Generic Structures}) or, for more complex tests, you may use
6476 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6478 @menu
6479 * Particular Structures::       Macros to check for certain structure members
6480 * Generic Structures::          How to find other structure members
6481 @end menu
6483 @node Particular Structures
6484 @subsection Particular Structure Checks
6486 The following macros check for certain structures or structure members.
6488 @defmac AC_STRUCT_DIRENT_D_INO
6489 @acindex{STRUCT_DIRENT_D_INO}
6490 @cvindex HAVE_STRUCT_DIRENT_D_INO
6491 @c @caindex header_dirent_dirent_h
6492 @c @caindex member_struct_dirent_d_ino
6493 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6494 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6495 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6497 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6498 @code{d_ino}, not whether its contents are always reliable.
6499 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6500 though current systems hide this detail from the user and never return
6501 zero @code{d_ino} values.
6502 Many current systems report an incorrect @code{d_ino} for a directory
6503 entry that is a mount point.
6504 @end defmac
6506 @defmac AC_STRUCT_DIRENT_D_TYPE
6507 @acindex{STRUCT_DIRENT_D_TYPE}
6508 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6509 @c @caindex header_dirent_dirent_h
6510 @c @caindex member_struct_dirent_d_type
6511 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6512 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6513 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6514 @end defmac
6516 @anchor{AC_STRUCT_ST_BLOCKS}
6517 @defmac AC_STRUCT_ST_BLOCKS
6518 @acindex{STRUCT_ST_BLOCKS}
6519 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6520 @cvindex HAVE_ST_BLOCKS
6521 @ovindex LIBOBJS
6522 @caindex member_struct_stat_st_blocks
6523 If @code{struct stat} contains an @code{st_blocks} member, define
6524 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6525 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6526 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6527 future.
6529 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6530 variable.
6531 @end defmac
6533 @defmac AC_STRUCT_TM
6534 @acindex{STRUCT_TM}
6535 @cvindex TM_IN_SYS_TIME
6536 @hdrindex{time.h}
6537 @hdrindex{sys/time.h}
6538 If @file{time.h} does not define @code{struct tm}, define
6539 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6540 had better define @code{struct tm}.
6542 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6543 current systems.  New programs need not use this macro.
6544 @end defmac
6546 @anchor{AC_STRUCT_TIMEZONE}
6547 @defmac AC_STRUCT_TIMEZONE
6548 @acindex{STRUCT_TIMEZONE}
6549 @cvindex HAVE_DECL_TZNAME
6550 @cvindex HAVE_STRUCT_TM_TM_ZONE
6551 @cvindex HAVE_TM_ZONE
6552 @cvindex HAVE_TZNAME
6553 @c @caindex member_struct_tm_tm_zone
6554 @c @caindex struct_tm
6555 Figure out how to get the current timezone.  If @code{struct tm} has a
6556 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6557 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6558 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6559 define @code{HAVE_DECL_TZNAME}.
6560 @end defmac
6562 @node Generic Structures
6563 @subsection Generic Structure Checks
6565 These macros are used to find structure members not covered by the
6566 ``particular'' test macros.
6568 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6569   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6570   @dvar{includes, AC_INCLUDES_DEFAULT})
6571 @acindex{CHECK_MEMBER}
6572 @caindex member_@var{aggregate}_@var{member}
6573 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6574 If no @var{includes} are specified, the default includes are used
6575 (@pxref{Default Includes}).
6577 @example
6578 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6579                 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6580                 [[#include <pwd.h>]])
6581 @end example
6583 You can use this macro for submembers:
6585 @example
6586 AC_CHECK_MEMBER(struct top.middle.bot)
6587 @end example
6589 This macro caches its result in the
6590 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6591 characters not suitable for a variable name mapped to underscores.
6592 @end defmac
6594 @anchor{AC_CHECK_MEMBERS}
6595 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6596   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6597 @acindex{CHECK_MEMBERS}
6598 @cvindex HAVE_@var{aggregate}_@var{member}
6599 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6600 @var{members} using the previous macro.  When @var{member} belongs to
6601 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6602 capitals, with spaces and dots replaced by underscores).  If
6603 @var{action-if-found} is given, it is executed for each of the found
6604 members.  If @var{action-if-not-found} is given, it is executed for each
6605 of the members that could not be found.
6607 @var{includes} is a series of include directives, defaulting to
6608 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6609 prior to the members under test.
6611 This macro uses M4 lists:
6612 @example
6613 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6614 @end example
6615 @end defmac
6618 @node Types
6619 @section Types
6620 @cindex Types
6621 @cindex C types
6623 The following macros check for C types, either builtin or typedefs.  If
6624 there is no macro specifically defined to check for a type you need, and
6625 you don't need to check for any special properties of it, then you can
6626 use a general type-check macro.
6628 @menu
6629 * Particular Types::            Special handling to find certain types
6630 * Generic Types::               How to find other types
6631 @end menu
6633 @node Particular Types
6634 @subsection Particular Type Checks
6636 @hdrindex{sys/types.h}
6637 @hdrindex{stdlib.h}
6638 @hdrindex{stdint.h}
6639 @hdrindex{inttypes.h}
6640 These macros check for particular C types in @file{sys/types.h},
6641 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6642 exist.
6644 The Gnulib @code{stdint} module is an alternate way to define many of
6645 these symbols; it is useful if you prefer your code to assume a
6646 C99-or-better environment.  @xref{Gnulib}.
6648 @anchor{AC_TYPE_GETGROUPS}
6649 @defmac AC_TYPE_GETGROUPS
6650 @acindex{TYPE_GETGROUPS}
6651 @cvindex GETGROUPS_T
6652 @caindex type_getgroups
6653 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6654 is the base type of the array argument to @code{getgroups}.
6656 This macro caches the base type in the @code{ac_cv_type_getgroups}
6657 variable.
6658 @end defmac
6660 @defmac AC_TYPE_INT8_T
6661 @acindex{TYPE_INT8_T}
6662 @cvindex HAVE_INT8_T
6663 @cvindex int8_t
6664 @caindex c_int8_t
6665 If @file{stdint.h} or @file{inttypes.h} does not define the type
6666 @code{int8_t}, define @code{int8_t} to a signed
6667 integer type that is exactly 8 bits wide and that uses two's complement
6668 representation, if such a type exists.
6669 If you are worried about porting to hosts that lack such a type, you can
6670 use the results of this macro in C89-or-later code as follows:
6672 @example
6673 #if HAVE_STDINT_H
6674 # include <stdint.h>
6675 #endif
6676 #if defined INT8_MAX || defined int8_t
6677  @emph{code using int8_t}
6678 #else
6679  @emph{complicated alternative using >8-bit 'signed char'}
6680 #endif
6681 @end example
6683 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6684 @end defmac
6686 @defmac AC_TYPE_INT16_T
6687 @acindex{TYPE_INT16_T}
6688 @cvindex HAVE_INT16_T
6689 @cvindex int16_t
6690 @caindex c_int16_t
6691 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6692 @end defmac
6694 @defmac AC_TYPE_INT32_T
6695 @acindex{TYPE_INT32_T}
6696 @cvindex HAVE_INT32_T
6697 @cvindex int32_t
6698 @caindex c_int32_t
6699 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6700 @end defmac
6702 @defmac AC_TYPE_INT64_T
6703 @acindex{TYPE_INT64_T}
6704 @cvindex HAVE_INT64_T
6705 @cvindex int64_t
6706 @caindex c_int64_t
6707 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6708 @end defmac
6710 @defmac AC_TYPE_INTMAX_T
6711 @acindex{TYPE_INTMAX_T}
6712 @cvindex HAVE_INTMAX_T
6713 @cvindex intmax_t
6714 @c @caindex type_intmax_t
6715 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6716 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6717 widest signed integer type.
6718 @end defmac
6720 @defmac AC_TYPE_INTPTR_T
6721 @acindex{TYPE_INTPTR_T}
6722 @cvindex HAVE_INTPTR_T
6723 @cvindex intptr_t
6724 @c @caindex type_intptr_t
6725 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6726 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6727 signed integer type wide enough to hold a pointer, if such a type
6728 exists.
6729 @end defmac
6731 @defmac AC_TYPE_LONG_DOUBLE
6732 @acindex{TYPE_LONG_DOUBLE}
6733 @cvindex HAVE_LONG_DOUBLE
6734 @caindex type_long_double
6735 If the C compiler supports a working @code{long double} type, define
6736 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6737 same range and precision as @code{double}.
6739 This macro caches its result in the @code{ac_cv_type_long_double}
6740 variable.
6742 This macro is obsolescent, as current C compilers support @code{long
6743 double}.  New programs need not use this macro.
6744 @end defmac
6746 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6747 @acindex{TYPE_LONG_DOUBLE_WIDER}
6748 @cvindex HAVE_LONG_DOUBLE_WIDER
6749 @caindex type_long_double_wider
6750 If the C compiler supports a working @code{long double} type with more
6751 range or precision than the @code{double} type, define
6752 @code{HAVE_LONG_DOUBLE_WIDER}.
6754 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6755 variable.
6756 @end defmac
6758 @defmac AC_TYPE_LONG_LONG_INT
6759 @acindex{TYPE_LONG_LONG_INT}
6760 @cvindex HAVE_LONG_LONG_INT
6761 @caindex type_long_long_int
6762 If the C compiler supports a working @code{long long int} type, define
6763 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6764 @code{long long int} values in preprocessor @code{#if} expressions,
6765 because too many compilers mishandle such expressions.
6766 @xref{Preprocessor Arithmetic}.
6768 This macro caches its result in the @code{ac_cv_type_long_long_int}
6769 variable.
6770 @end defmac
6772 @defmac AC_TYPE_MBSTATE_T
6773 @acindex{TYPE_MBSTATE_T}
6774 @cvindex mbstate_t
6775 @hdrindex{wchar.h}
6776 @caindex type_mbstate_t
6777 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6778 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6779 @code{<wchar.h>} does not declare it.
6781 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6782 variable.
6783 @end defmac
6785 @anchor{AC_TYPE_MODE_T}
6786 @defmac AC_TYPE_MODE_T
6787 @acindex{TYPE_MODE_T}
6788 @cvindex mode_t
6789 @caindex type_mode_t
6790 Define @code{mode_t} to a suitable type, if standard headers do not
6791 define it.
6793 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6794 @end defmac
6796 @anchor{AC_TYPE_OFF_T}
6797 @defmac AC_TYPE_OFF_T
6798 @acindex{TYPE_OFF_T}
6799 @cvindex off_t
6800 @caindex type_off_t
6801 Define @code{off_t} to a suitable type, if standard headers do not
6802 define it.
6804 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6805 @end defmac
6807 @anchor{AC_TYPE_PID_T}
6808 @defmac AC_TYPE_PID_T
6809 @acindex{TYPE_PID_T}
6810 @cvindex pid_t
6811 @caindex type_pid_t
6812 Define @code{pid_t} to a suitable type, if standard headers do not
6813 define it.
6815 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6816 @end defmac
6818 @anchor{AC_TYPE_SIZE_T}
6819 @defmac AC_TYPE_SIZE_T
6820 @acindex{TYPE_SIZE_T}
6821 @cvindex size_t
6822 @caindex type_size_t
6823 Define @code{size_t} to a suitable type, if standard headers do not
6824 define it.
6826 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6827 @end defmac
6829 @defmac AC_TYPE_SSIZE_T
6830 @acindex{TYPE_SSIZE_T}
6831 @cvindex ssize_t
6832 @caindex type_ssize_t
6833 Define @code{ssize_t} to a suitable type, if standard headers do not
6834 define it.
6836 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6837 @end defmac
6839 @anchor{AC_TYPE_UID_T}
6840 @defmac AC_TYPE_UID_T
6841 @acindex{TYPE_UID_T}
6842 @cvindex uid_t
6843 @cvindex gid_t
6844 @caindex type_uid_t
6845 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6846 headers do not define them.
6848 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6849 @end defmac
6851 @defmac AC_TYPE_UINT8_T
6852 @acindex{TYPE_UINT8_T}
6853 @cvindex HAVE_UINT8_T
6854 @cvindex uint8_t
6855 @caindex c_uint8_t
6856 If @file{stdint.h} or @file{inttypes.h} does not define the type
6857 @code{uint8_t}, define @code{uint8_t} to an
6858 unsigned integer type that is exactly 8 bits wide, if such a type
6859 exists.
6860 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6861 @end defmac
6863 @defmac AC_TYPE_UINT16_T
6864 @acindex{TYPE_UINT16_T}
6865 @cvindex HAVE_UINT16_T
6866 @cvindex uint16_t
6867 @caindex c_uint16_t
6868 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6869 @end defmac
6871 @defmac AC_TYPE_UINT32_T
6872 @acindex{TYPE_UINT32_T}
6873 @cvindex HAVE_UINT32_T
6874 @cvindex uint32_t
6875 @caindex c_uint32_t
6876 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6877 @end defmac
6879 @defmac AC_TYPE_UINT64_T
6880 @acindex{TYPE_UINT64_T}
6881 @cvindex HAVE_UINT64_T
6882 @cvindex uint64_t
6883 @caindex c_uint64_t
6884 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6885 @end defmac
6887 @defmac AC_TYPE_UINTMAX_T
6888 @acindex{TYPE_UINTMAX_T}
6889 @cvindex HAVE_UINTMAX_T
6890 @cvindex uintmax_t
6891 @c @caindex type_uintmax_t
6892 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6893 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6894 widest unsigned integer type.
6895 @end defmac
6897 @defmac AC_TYPE_UINTPTR_T
6898 @acindex{TYPE_UINTPTR_T}
6899 @cvindex HAVE_UINTPTR_T
6900 @cvindex uintptr_t
6901 @c @caindex type_uintptr_t
6902 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6903 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6904 unsigned integer type wide enough to hold a pointer, if such a type
6905 exists.
6906 @end defmac
6908 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6909 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6910 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6911 @caindex type_unsigned_long_long_int
6912 If the C compiler supports a working @code{unsigned long long int} type,
6913 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6914 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6915 because too many compilers mishandle such expressions.
6916 @xref{Preprocessor Arithmetic}.
6918 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6919 variable.
6920 @end defmac
6922 @node Generic Types
6923 @subsection Generic Type Checks
6925 These macros are used to check for types not covered by the ``particular''
6926 test macros.
6928 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6929   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6930 @acindex{CHECK_TYPE}
6931 @caindex type_@var{type}
6932 Check whether @var{type} is defined.  It may be a compiler builtin type
6933 or defined by the @var{includes}.  @var{includes} is a series of include
6934 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6935 Includes}), which are used prior to the type under test.
6937 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6938 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6939 same test is applied when compiling for C++, which means that in C++
6940 @var{type} should be a type-id and should not be an anonymous
6941 @samp{struct} or @samp{union}.
6943 This macro caches its result in the @code{ac_cv_type_@var{type}}
6944 variable, with @samp{*} mapped to @samp{p} and other characters not
6945 suitable for a variable name mapped to underscores.
6946 @end defmac
6949 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6950   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6951 @acindex{CHECK_TYPES}
6952 @cvindex HAVE_@var{type}
6953 For each @var{type} of the @var{types} that is defined, define
6954 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6955 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6956 specified, the default includes are used (@pxref{Default Includes}).  If
6957 @var{action-if-found} is given, it is additional shell code to execute
6958 when one of the types is found.  If @var{action-if-not-found} is given,
6959 it is executed when one of the types is not found.
6961 This macro uses M4 lists:
6962 @example
6963 AC_CHECK_TYPES([ptrdiff_t])
6964 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6965 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6966 @end example
6968 @end defmac
6970 Autoconf, up to 2.13, used to provide to another version of
6971 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6972 compatibility, a simple heuristic, quite safe but not totally, is
6973 implemented.  In case of doubt, read the documentation of the former
6974 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6977 @node Compilers and Preprocessors
6978 @section Compilers and Preprocessors
6979 @cindex Compilers
6980 @cindex Preprocessors
6982 @ovindex EXEEXT
6983 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6984 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6985 the output of the compiler, typically to the empty string if
6986 Posix and @samp{.exe} if a DOS variant.
6988 @ovindex OBJEXT
6989 They also define the output variable @code{OBJEXT} based on the
6990 output of the compiler, after @file{.c} files have been excluded, typically
6991 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6993 If the compiler being used does not produce executables, the tests fail.  If
6994 the executables can't be run, and cross-compilation is not enabled, they
6995 fail too.  @xref{Manual Configuration}, for more on support for cross
6996 compiling.
6998 @menu
6999 * Specific Compiler Characteristics::  Some portability issues
7000 * Generic Compiler Characteristics::  Language independent tests and features
7001 * C Compiler::                  Checking its characteristics
7002 * C++ Compiler::                Likewise
7003 * Objective C Compiler::        Likewise
7004 * Objective C++ Compiler::      Likewise
7005 * Erlang Compiler and Interpreter::  Likewise
7006 * Fortran Compiler::            Likewise
7007 * Go Compiler::                 Likewise
7008 @end menu
7010 @node Specific Compiler Characteristics
7011 @subsection Specific Compiler Characteristics
7013 Some compilers exhibit different behaviors.
7015 @table @asis
7016 @item Static/Dynamic Expressions
7017 Autoconf relies on a trick to extract one bit of information from the C
7018 compiler: using negative array sizes.  For instance the following
7019 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7020 bytes wide:
7022 @example
7023 static int test_array[sizeof (int) == 4 ? 1 : -1];
7024 @end example
7026 @noindent
7027 To our knowledge, there is a single compiler that does not support this
7028 trick: the HP C compilers (the real ones, not only the
7029 ``bundled'') on HP-UX 11.00.
7030 They incorrectly reject the above program with the diagnostic
7031 ``Variable-length arrays cannot have static storage.''
7032 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7033 not from the @code{? 1 : -1}, and
7034 Autoconf works around this problem by casting @code{sizeof (int)} to
7035 @code{long int} before comparing it.
7036 @end table
7038 @node Generic Compiler Characteristics
7039 @subsection Generic Compiler Characteristics
7041 @anchor{AC_CHECK_SIZEOF}
7042 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7043   @dvar{includes, AC_INCLUDES_DEFAULT})
7044 @acindex{CHECK_SIZEOF}
7045 @cvindex SIZEOF_@var{type-or-expr}
7046 @caindex sizeof_@var{type-or-expr}
7047 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7048 the size in bytes of @var{type-or-expr}, which may be either a type or
7049 an expression returning a value that has a size.  If the expression
7050 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7051 @var{includes} is a series of include directives, defaulting to
7052 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7053 prior to the expression under test.
7055 This macro now works even when cross-compiling.  The @var{unused}
7056 argument was used when cross-compiling.
7058 For example, the call
7060 @example
7061 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7062 AC_CHECK_SIZEOF([int *])
7063 @end example
7065 @noindent
7066 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7068 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7069 variable, with @samp{*} mapped to @samp{p} and other characters not
7070 suitable for a variable name mapped to underscores.
7071 @end defmac
7073 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7074 @acindex{CHECK_ALIGNOF}
7075 @cvindex ALIGNOF_@var{type}
7076 @caindex alignof_@var{type-or-expr}
7077 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7078 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7079 a structure member declaration.  If @samp{type} is unknown, the result
7080 is 0.  If no @var{includes} are specified, the default includes are used
7081 (@pxref{Default Includes}).
7083 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7084 variable, with @samp{*} mapped to @samp{p} and other characters not
7085 suitable for a variable name mapped to underscores.
7086 @end defmac
7088 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7089   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7090 @acindex{COMPUTE_INT}
7091 Store into the shell variable @var{var} the value of the integer
7092 @var{expression}.  The
7093 value should fit in an initializer in a C variable of type @code{signed
7094 long}.  To support cross compilation (in which case, the macro only works on
7095 hosts that use twos-complement arithmetic), it should be possible to evaluate
7096 the expression at compile-time.  If no @var{includes} are specified, the
7097 default includes are used (@pxref{Default Includes}).
7099 Execute @var{action-if-fails} if the value cannot be determined correctly.
7100 @end defmac
7102 @defmac AC_LANG_WERROR
7103 @acindex{LANG_WERROR}
7104 Normally Autoconf ignores warnings generated by the compiler, linker, and
7105 preprocessor.  If this macro is used, warnings count as fatal
7106 errors for the current language.  This macro is useful when the
7107 results of configuration are used where warnings are unacceptable; for
7108 instance, if parts of a program are built with the GCC
7109 @option{-Werror}
7110 option.  If the whole program is built using @option{-Werror} it is
7111 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7112 etc.).
7113 @end defmac
7115 @defmac AC_OPENMP
7116 @acindex{OPENMP}
7117 @cvindex _OPENMP
7118 @ovindex OPENMP_CFLAGS
7119 @ovindex OPENMP_CXXFLAGS
7120 @ovindex OPENMP_FFLAGS
7121 @ovindex OPENMP_FCFLAGS
7122 @caindex prog_c_openmp
7123 @caindex prog_cxx_openmp
7124 @caindex prog_f77_openmp
7125 @caindex prog_fc_openmp
7126 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7127 and Fortran that simplify optimization of shared memory parallelism,
7128 which is a common problem on multicore CPUs.
7130 If the current language is C, the macro @code{AC_OPENMP} sets the
7131 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7132 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7133 compiler already supports OpenMP, if it has no way to activate OpenMP
7134 support, or if the user rejects OpenMP support by invoking
7135 @samp{configure} with the @samp{--disable-openmp} option.
7137 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7138 preprocessing program source, and when linking programs.  Therefore you
7139 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7140 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7141 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7142 OpenMP support is revealed at compile time by the preprocessor macro
7143 @code{_OPENMP}.
7145 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7146 shared library to the program's dependencies, so its use is recommended
7147 only on programs that actually require OpenMP.
7149 If the current language is C++, @code{AC_OPENMP} sets the variable
7150 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7151 hold as for C.
7153 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7154 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7155 respectively.  Similar remarks as for C hold, except that
7156 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7157 signals OpenMP support.
7159 For portability, it is best to avoid spaces between @samp{#} and
7160 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7161 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7162 latter.
7164 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7165 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7166 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7167 @end defmac
7169 @node C Compiler
7170 @subsection C Compiler Characteristics
7172 The following macros provide ways to find and exercise a C Compiler.
7173 There are a few constructs that ought to be avoided, but do not deserve
7174 being checked for, since they can easily be worked around.
7176 @table @asis
7177 @item Don't use lines containing solitary backslashes
7178 They tickle a bug in the HP-UX C compiler (checked on
7179 HP-UX 10.20,
7180 11.00, and 11i).  When given the following source:
7182 @example
7183 #ifdef __STDC__
7185 * A comment with backslash-newlines in it.  %@{ %@} *\
7188 char str[] = "\\
7189 " A string with backslash-newlines in it %@{ %@} \\
7191 char apostrophe = '\\
7195 #endif
7196 @end example
7198 @noindent
7199 the compiler incorrectly fails with the diagnostics ``Non-terminating
7200 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7201 Removing the lines with solitary backslashes solves the problem.
7203 @item Don't compile several files at once if output matters to you
7204 Some compilers, such as HP's, report names of files being
7205 compiled when given more than one file operand.  For instance:
7207 @example
7208 $ @kbd{cc a.c b.c}
7209 a.c:
7210 b.c:
7211 @end example
7213 @noindent
7214 This can cause problems if you observe the output of the compiler to
7215 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7216 b.o} solves the issue.
7218 @item Don't rely on @code{#error} failing
7219 The IRIX C compiler does not fail when #error is preprocessed; it
7220 simply emits a diagnostic and continues, exiting successfully.  So,
7221 instead of an error directive like @code{#error "Unsupported word size"}
7222 it is more portable to use an invalid directive like @code{#Unsupported
7223 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7224 OK, since installers with inadequate compilers like IRIX can simply
7225 examine these compilers' diagnostic output.
7227 @item Don't rely on correct @code{#line} support
7228 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7229 diagnoses @code{#line} directives whose line
7230 numbers are greater than 32767.  Nothing in Posix
7231 makes this invalid.  That is why Autoconf stopped issuing
7232 @code{#line} directives.
7233 @end table
7235 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7236 @acindex{PROG_CC}
7237 @evindex CC
7238 @evindex CFLAGS
7239 @ovindex CC
7240 @ovindex CFLAGS
7241 @caindex prog_cc_c89
7242 Determine a C compiler to use.  If @code{CC} is not already set in the
7243 environment, check for @code{gcc} and @code{cc}, then for other C
7244 compilers.  Set output variable @code{CC} to the name of the compiler
7245 found.
7247 This macro may, however, be invoked with an optional first argument
7248 which, if specified, must be a blank-separated list of C compilers to
7249 search for.  This just gives the user an opportunity to specify an
7250 alternative search list for the C compiler.  For example, if you didn't
7251 like the default order, then you could invoke @code{AC_PROG_CC} like
7252 this:
7254 @example
7255 AC_PROG_CC([gcc cl cc])
7256 @end example
7258 If the C compiler does not handle function prototypes correctly by
7259 default, try to add an option to output variable @code{CC} to make it
7260 so.  This macro tries various options that select standard-conformance
7261 modes on various systems.
7263 After calling this macro you can check whether the C compiler has been
7264 set to accept ANSI C89 (ISO C90); if not, the shell
7265 variable
7266 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7267 @code{AC_C_PROTOTYPES} below.
7269 If using the GNU C compiler, set shell variable @code{GCC} to
7270 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7271 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7272 where GCC does not accept @option{-g}), or @option{-g} for
7273 other compilers.  If your package does not like this default, then it is
7274 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7275 and before @code{AC_PROG_CC} to select an empty default instead.
7277 Many Autoconf macros use a compiler, and thus call
7278 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7279 determined before the body of the outermost @code{AC_DEFUN} macro.
7280 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7281 performs certain checks (such as the proper value of @env{EXEEXT}) only
7282 on the first invocation.  Therefore, care must be used when invoking
7283 this macro from within another macro rather than at the top level
7284 (@pxref{Expanded Before Required}).
7285 @end defmac
7287 @anchor{AC_PROG_CC_C_O}
7288 @defmac AC_PROG_CC_C_O
7289 @acindex{PROG_CC_C_O}
7290 @cvindex NO_MINUS_C_MINUS_O
7291 @caindex prog_cc_@var{compiler}_c_o
7292 If the C compiler does not accept the @option{-c} and @option{-o} options
7293 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7294 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7295 the first @code{cc} in the path.  The test fails if one fails.  This
7296 macro was created for GNU Make to choose the default C compilation
7297 rule.
7299 For the compiler @var{compiler}, this macro caches its result in the
7300 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7301 @end defmac
7304 @defmac AC_PROG_CPP
7305 @acindex{PROG_CPP}
7306 @evindex CPP
7307 @ovindex CPP
7308 Set output variable @code{CPP} to a command that runs the
7309 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7310 It is only portable to run @code{CPP} on files with a @file{.c}
7311 extension.
7313 Some preprocessors don't indicate missing include files by the error
7314 status.  For such preprocessors an internal variable is set that causes
7315 other macros to check the standard error from the preprocessor and
7316 consider the test failed if any warnings have been reported.
7317 For most preprocessors, though, warnings do not cause include-file
7318 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7319 @end defmac
7321 @defmac AC_PROG_CPP_WERROR
7322 @acindex{PROG_CPP_WERROR}
7323 @ovindex CPP
7324 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7325 preprocessor as errors even if the preprocessor exit status indicates
7326 success.  This is useful for avoiding headers that generate mandatory
7327 warnings, such as deprecation notices.
7328 @end defmac
7331 The following macros check for C compiler or machine architecture
7332 features.  To check for characteristics not listed here, use
7333 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7334 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7336 @defmac AC_PROG_CC_STDC
7337 @acindex{PROG_CC_STDC}
7338 @caindex prog_cc_stdc
7339 If the C compiler cannot compile ISO Standard C (currently
7340 C99), try to add an option to output variable @code{CC} to make it work.
7341 If the compiler does not support C99, fall back to supporting
7342 ANSI C89 (ISO C90).
7344 After calling this macro you can check whether the C compiler has been
7345 set to accept Standard C; if not, the shell variable
7346 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7347 @end defmac
7349 @defmac AC_PROG_CC_C89
7350 @acindex{PROG_CC_C89}
7351 @caindex prog_cc_c89
7352 If the C compiler is not in ANSI C89 (ISO C90) mode by
7353 default, try to add an option to output variable @code{CC} to make it
7354 so.  This macro tries various options that select ANSI C89 on
7355 some system or another, preferring extended functionality modes over
7356 strict conformance modes.  It considers the compiler to be in
7357 ANSI C89 mode if it handles function prototypes correctly.
7359 After calling this macro you can check whether the C compiler has been
7360 set to accept ANSI C89; if not, the shell variable
7361 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7363 This macro is called automatically by @code{AC_PROG_CC}.
7364 @end defmac
7366 @defmac AC_PROG_CC_C99
7367 @acindex{PROG_CC_C99}
7368 @caindex prog_cc_c99
7369 If the C compiler is not in C99 mode by default, try to add an
7370 option to output variable @code{CC} to make it so.  This macro tries
7371 various options that select C99 on some system or another, preferring
7372 extended functionality modes over strict conformance modes.  It
7373 considers the compiler to be in C99 mode if it handles @code{_Bool},
7374 @code{//} comments, flexible array members, @code{inline}, signed and
7375 unsigned @code{long long int}, mixed code and declarations, named
7376 initialization of structs,
7377 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7378 in @code{for} loops, and variable length arrays.
7380 After calling this macro you can check whether the C compiler has been
7381 set to accept C99; if not, the shell variable
7382 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7383 @end defmac
7385 @defmac AC_C_BACKSLASH_A
7386 @acindex{C_BACKSLASH_A}
7387 @cvindex HAVE_C_BACKSLASH_A
7388 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7389 @samp{\a}.
7391 This macro is obsolescent, as current C compilers understand @samp{\a}.
7392 New programs need not use this macro.
7393 @end defmac
7395 @anchor{AC_C_BIGENDIAN}
7396 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7397   @ovar{action-if-unknown}, @ovar{action-if-universal})
7398 @acindex{C_BIGENDIAN}
7399 @cvindex WORDS_BIGENDIAN
7400 @cindex Endianness
7401 If words are stored with the most significant byte first (like Motorola
7402 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7403 the least significant byte first (like Intel and VAX CPUs), execute
7404 @var{action-if-false}.
7406 This macro runs a test-case if endianness cannot be determined from the
7407 system header files.  When cross-compiling, the test-case is not run but
7408 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7409 the latter case fails to determine the byte sex of the host system.
7411 In some cases a single run of a compiler can generate code for multiple
7412 architectures.  This can happen, for example, when generating Mac OS X
7413 universal binary files, which work on both PowerPC and Intel
7414 architectures.  In this case, the different variants might be for
7415 different architectures whose endiannesses differ.  If
7416 @command{configure} detects this, it executes @var{action-if-universal}
7417 instead of @var{action-if-unknown}.
7419 The default for @var{action-if-true} is to define
7420 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7421 nothing.  The default for @var{action-if-unknown} is to
7422 abort configure and tell the installer how to bypass this test.
7423 And finally, the default for @var{action-if-universal} is to ensure that
7424 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7425 detected and the current code is big-endian; this default works only if
7426 @command{autoheader} is used (@pxref{autoheader Invocation}).
7428 If you use this macro without specifying @var{action-if-universal}, you
7429 should also use @code{AC_CONFIG_HEADERS}; otherwise
7430 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7431 binary files.
7432 @end defmac
7434 @anchor{AC_C_CONST}
7435 @defmac AC_C_CONST
7436 @acindex{C_CONST}
7437 @cvindex const
7438 @caindex c_const
7439 If the C compiler does not fully support the @code{const} keyword,
7440 define @code{const} to be empty.  Some C compilers that do
7441 not define @code{__STDC__} do support @code{const}; some compilers that
7442 define @code{__STDC__} do not completely support @code{const}.  Programs
7443 can simply use @code{const} as if every C compiler supported it; for
7444 those that don't, the makefile or configuration header file
7445 defines it as empty.
7447 Occasionally installers use a C++ compiler to compile C code, typically
7448 because they lack a C compiler.  This causes problems with @code{const},
7449 because C and C++ treat @code{const} differently.  For example:
7451 @example
7452 const int foo;
7453 @end example
7455 @noindent
7456 is valid in C but not in C++.  These differences unfortunately cannot be
7457 papered over by defining @code{const} to be empty.
7459 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7460 as this generally yields better results in practice.  However, using a
7461 C++ compiler to compile C code is not recommended or supported, and
7462 installers who run into trouble in this area should get a C compiler
7463 like GCC to compile their C code.
7465 This macro caches its result in the @code{ac_cv_c_const} variable.
7467 This macro is obsolescent, as current C compilers support @code{const}.
7468 New programs need not use this macro.
7469 @end defmac
7471 @defmac AC_C_RESTRICT
7472 @acindex{C_RESTRICT}
7473 @cvindex restrict
7474 @caindex c_restrict
7475 If the C compiler recognizes a variant spelling for the @code{restrict}
7476 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7477 then define @code{restrict} to that; this is more likely to do the right
7478 thing with compilers that support language variants where plain
7479 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7480 recognizes the @code{restrict} keyword, don't do anything.
7481 Otherwise, define @code{restrict} to be empty.
7482 Thus, programs may simply use @code{restrict} as if every C compiler
7483 supported it; for those that do not, the makefile
7484 or configuration header defines it away.
7486 Although support in C++ for the @code{restrict} keyword is not
7487 required, several C++ compilers do accept the keyword.
7488 This macro works for them, too.
7490 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7491 if @code{restrict} is not supported, and a supported spelling otherwise.
7492 @end defmac
7494 @defmac AC_C_VOLATILE
7495 @acindex{C_VOLATILE}
7496 @cvindex volatile
7497 If the C compiler does not understand the keyword @code{volatile},
7498 define @code{volatile} to be empty.  Programs can simply use
7499 @code{volatile} as if every C compiler supported it; for those that do
7500 not, the makefile or configuration header defines it as
7501 empty.
7503 If the correctness of your program depends on the semantics of
7504 @code{volatile}, simply defining it to be empty does, in a sense, break
7505 your code.  However, given that the compiler does not support
7506 @code{volatile}, you are at its mercy anyway.  At least your
7507 program compiles, when it wouldn't before.
7508 @xref{Volatile Objects}, for more about @code{volatile}.
7510 In general, the @code{volatile} keyword is a standard C feature, so
7511 you might expect that @code{volatile} is available only when
7512 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7513 support volatile, but does not define @code{__STDC__}.
7515 This macro is obsolescent, as current C compilers support @code{volatile}.
7516 New programs need not use this macro.
7517 @end defmac
7519 @anchor{AC_C_INLINE}
7520 @defmac AC_C_INLINE
7521 @acindex{C_INLINE}
7522 @cvindex inline
7523 If the C compiler supports the keyword @code{inline}, do nothing.
7524 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7525 if it accepts one of those, otherwise define @code{inline} to be empty.
7526 @end defmac
7528 @anchor{AC_C_CHAR_UNSIGNED}
7529 @defmac AC_C_CHAR_UNSIGNED
7530 @acindex{C_CHAR_UNSIGNED}
7531 @cvindex __CHAR_UNSIGNED__
7532 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7533 unless the C compiler predefines it.
7535 These days, using this macro is not necessary.  The same information can
7536 be determined by this portable alternative, thus avoiding the use of
7537 preprocessor macros in the namespace reserved for the implementation.
7539 @example
7540 #include <limits.h>
7541 #if CHAR_MIN == 0
7542 # define CHAR_UNSIGNED 1
7543 #endif
7544 @end example
7545 @end defmac
7547 @defmac AC_C_STRINGIZE
7548 @acindex{C_STRINGIZE}
7549 @cvindex HAVE_STRINGIZE
7550 If the C preprocessor supports the stringizing operator, define
7551 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7552 found in macros such as this:
7554 @example
7555 #define x(y) #y
7556 @end example
7558 This macro is obsolescent, as current C compilers support the
7559 stringizing operator.  New programs need not use this macro.
7560 @end defmac
7562 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7563 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7564 @cvindex FLEXIBLE_ARRAY_MEMBER
7565 If the C compiler supports flexible array members, define
7566 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7567 That way, a declaration like this:
7569 @example
7570 struct s
7571   @{
7572     size_t n_vals;
7573     double val[FLEXIBLE_ARRAY_MEMBER];
7574   @};
7575 @end example
7577 @noindent
7578 will let applications use the ``struct hack'' even with compilers that
7579 do not support flexible array members.  To allocate and use such an
7580 object, you can use code like this:
7582 @example
7583 size_t i;
7584 size_t n = compute_value_count ();
7585 struct s *p =
7586    malloc (offsetof (struct s, val)
7587            + n * sizeof (double));
7588 p->n_vals = n;
7589 for (i = 0; i < n; i++)
7590   p->val[i] = compute_value (i);
7591 @end example
7592 @end defmac
7594 @defmac AC_C_VARARRAYS
7595 @acindex{C_VARARRAYS}
7596 @cvindex HAVE_C_VARARRAYS
7597 If the C compiler supports variable-length arrays, define
7598 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7599 storage duration whose length is determined at run time, when the array
7600 is declared.
7601 @end defmac
7603 @defmac AC_C_TYPEOF
7604 @acindex{C_TYPEOF}
7605 @cvindex HAVE_TYPEOF
7606 @cvindex typeof
7607 If the C compiler supports GCC's @code{typeof} syntax either
7608 directly or
7609 through a different spelling of the keyword (e.g., @code{__typeof__}),
7610 define @code{HAVE_TYPEOF}.  If the support is available only through a
7611 different spelling, define @code{typeof} to that spelling.
7612 @end defmac
7614 @defmac AC_C_PROTOTYPES
7615 @acindex{C_PROTOTYPES}
7616 @cvindex PROTOTYPES
7617 @cvindex __PROTOTYPES
7618 @cvindex PARAMS
7619 If function prototypes are understood by the compiler (as determined by
7620 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7621 Defining @code{__PROTOTYPES} is for the benefit of
7622 header files that cannot use macros that infringe on user name space.
7624 This macro is obsolescent, as current C compilers support prototypes.
7625 New programs need not use this macro.
7626 @end defmac
7628 @anchor{AC_PROG_GCC_TRADITIONAL}
7629 @defmac AC_PROG_GCC_TRADITIONAL
7630 @acindex{PROG_GCC_TRADITIONAL}
7631 @ovindex CC
7632 Add @option{-traditional} to output variable @code{CC} if using the
7633 GNU C compiler and @code{ioctl} does not work properly without
7634 @option{-traditional}.  That usually happens when the fixed header files
7635 have not been installed on an old system.
7637 This macro is obsolescent, since current versions of the GNU C
7638 compiler fix the header files automatically when installed.
7639 @end defmac
7642 @node C++ Compiler
7643 @subsection C++ Compiler Characteristics
7646 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7647 @acindex{PROG_CXX}
7648 @evindex CXX
7649 @evindex CXXFLAGS
7650 @ovindex CXX
7651 @ovindex CXXFLAGS
7652 Determine a C++ compiler to use.  Check whether the environment variable
7653 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7654 variable @code{CXX} to its value.
7656 Otherwise, if the macro is invoked without an argument, then search for
7657 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7658 then other names).  If none of those checks succeed, then as a last
7659 resort set @code{CXX} to @code{g++}.
7661 This macro may, however, be invoked with an optional first argument
7662 which, if specified, must be a blank-separated list of C++ compilers to
7663 search for.  This just gives the user an opportunity to specify an
7664 alternative search list for the C++ compiler.  For example, if you
7665 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7666 like this:
7668 @example
7669 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7670 @end example
7672 If using the GNU C++ compiler, set shell variable @code{GXX} to
7673 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7674 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7675 systems where G++ does not accept @option{-g}), or @option{-g} for other
7676 compilers.  If your package does not like this default, then it is
7677 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7678 and before @code{AC_PROG_CXX} to select an empty default instead.
7680 @end defmac
7682 @defmac AC_PROG_CXXCPP
7683 @acindex{PROG_CXXCPP}
7684 @evindex CXXCPP
7685 @ovindex CXXCPP
7686 Set output variable @code{CXXCPP} to a command that runs the C++
7687 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7688 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7689 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7691 Some preprocessors don't indicate missing include files by the error
7692 status.  For such preprocessors an internal variable is set that causes
7693 other macros to check the standard error from the preprocessor and
7694 consider the test failed if any warnings have been reported.  However,
7695 it is not known whether such broken preprocessors exist for C++.
7696 @end defmac
7698 @defmac AC_PROG_CXX_C_O
7699 @acindex{PROG_CXX_C_O}
7700 @cvindex CXX_NO_MINUS_C_MINUS_O
7701 Test whether the C++ compiler accepts the options @option{-c} and
7702 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7703 if it does not.
7704 @end defmac
7707 @node Objective C Compiler
7708 @subsection Objective C Compiler Characteristics
7711 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7712 @acindex{PROG_OBJC}
7713 @evindex OBJC
7714 @evindex OBJCFLAGS
7715 @ovindex OBJC
7716 @ovindex OBJCFLAGS
7717 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7718 set in the environment, check for Objective C compilers.  Set output
7719 variable @code{OBJC} to the name of the compiler found.
7721 This macro may, however, be invoked with an optional first argument
7722 which, if specified, must be a blank-separated list of Objective C compilers to
7723 search for.  This just gives the user an opportunity to specify an
7724 alternative search list for the Objective C compiler.  For example, if you
7725 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7726 like this:
7728 @example
7729 AC_PROG_OBJC([gcc objcc objc])
7730 @end example
7732 If using the GNU Objective C compiler, set shell variable
7733 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7734 already set, set it to @option{-g -O2} for the GNU Objective C
7735 compiler (@option{-O2} on systems where @command{gcc} does not accept
7736 @option{-g}), or @option{-g} for other compilers.
7737 @end defmac
7739 @defmac AC_PROG_OBJCPP
7740 @acindex{PROG_OBJCPP}
7741 @evindex OBJCPP
7742 @ovindex OBJCPP
7743 Set output variable @code{OBJCPP} to a command that runs the Objective C
7744 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7745 @end defmac
7748 @node Objective C++ Compiler
7749 @subsection Objective C++ Compiler Characteristics
7752 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7753 @acindex{PROG_OBJCXX}
7754 @evindex OBJCXX
7755 @evindex OBJCXXFLAGS
7756 @ovindex OBJCXX
7757 @ovindex OBJCXXFLAGS
7758 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7759 set in the environment, check for Objective C++ compilers.  Set output
7760 variable @code{OBJCXX} to the name of the compiler found.
7762 This macro may, however, be invoked with an optional first argument
7763 which, if specified, must be a blank-separated list of Objective C++ compilers
7764 to search for.  This just gives the user an opportunity to specify an
7765 alternative search list for the Objective C++ compiler.  For example, if you
7766 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7767 like this:
7769 @example
7770 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7771 @end example
7773 If using the GNU Objective C++ compiler, set shell variable
7774 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7775 already set, set it to @option{-g -O2} for the GNU Objective C++
7776 compiler (@option{-O2} on systems where @command{gcc} does not accept
7777 @option{-g}), or @option{-g} for other compilers.
7778 @end defmac
7780 @defmac AC_PROG_OBJCXXCPP
7781 @acindex{PROG_OBJCXXCPP}
7782 @evindex OBJCXXCPP
7783 @ovindex OBJCXXCPP
7784 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7785 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7786 @end defmac
7789 @node Erlang Compiler and Interpreter
7790 @subsection Erlang Compiler and Interpreter Characteristics
7791 @cindex Erlang
7793 Autoconf defines the following macros for determining paths to the essential
7794 Erlang/OTP programs:
7796 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7797 @acindex{ERLANG_PATH_ERLC}
7798 @evindex ERLC
7799 @evindex ERLCFLAGS
7800 @ovindex ERLC
7801 @ovindex ERLCFLAGS
7802 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7803 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7804 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7805 is not set in the environment, set it to an empty value.
7807 The two optional arguments have the same meaning as the two last arguments of
7808 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7809 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7810 directory:
7812 @example
7813 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7814 @end example
7815 @end defmac
7817 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7818 @acindex{ERLANG_NEED_ERLC}
7819 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7820 error message and exits the @command{configure} script if the @command{erlc}
7821 program is not found.
7822 @end defmac
7824 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7825 @acindex{ERLANG_PATH_ERL}
7826 @evindex ERL
7827 @ovindex ERL
7828 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7829 set in the
7830 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7831 complete path of the interpreter command found.
7833 The two optional arguments have the same meaning as the two last arguments of
7834 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7835 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7836 directory:
7838 @example
7839 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7840 @end example
7841 @end defmac
7843 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7844 @acindex{ERLANG_NEED_ERL}
7845 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7846 error message and exits the @command{configure} script if the @command{erl}
7847 program is not found.
7848 @end defmac
7851 @node Fortran Compiler
7852 @subsection Fortran Compiler Characteristics
7853 @cindex Fortran
7854 @cindex F77
7856 The Autoconf Fortran support is divided into two categories: legacy
7857 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7858 The former are intended for traditional Fortran 77 code, and have output
7859 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7860 are for newer programs that can (or must) compile under the newer
7861 Fortran standards, and have output variables like @code{FC},
7862 @code{FCFLAGS}, and @code{FCLIBS}.
7864 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7865 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7866 @code{FC} and @code{F77} macros behave almost identically, and so they
7867 are documented together in this section.
7870 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7871 @acindex{PROG_F77}
7872 @evindex F77
7873 @evindex FFLAGS
7874 @ovindex F77
7875 @ovindex FFLAGS
7876 @caindex f77_compiler_gnu
7877 @caindex prog_f77_g
7878 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7879 set in the environment, then check for @code{g77} and @code{f77}, and
7880 then some other names.  Set the output variable @code{F77} to the name
7881 of the compiler found.
7883 This macro may, however, be invoked with an optional first argument
7884 which, if specified, must be a blank-separated list of Fortran 77
7885 compilers to search for.  This just gives the user an opportunity to
7886 specify an alternative search list for the Fortran 77 compiler.  For
7887 example, if you didn't like the default order, then you could invoke
7888 @code{AC_PROG_F77} like this:
7890 @example
7891 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7892 @end example
7894 If using @code{g77} (the GNU Fortran 77 compiler), then
7895 set the shell variable @code{G77} to @samp{yes}.
7896 If the output variable @code{FFLAGS} was not already set in the
7897 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7898 where @code{g77} does not accept @option{-g}).  Otherwise, set
7899 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7901 The result of the GNU test is cached in the
7902 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7903 @code{ac_cv_prog_f77_g} variable.
7904 @end defmac
7906 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7907 @acindex{PROG_FC}
7908 @evindex FC
7909 @evindex FCFLAGS
7910 @ovindex FC
7911 @ovindex FCFLAGS
7912 @caindex fc_compiler_gnu
7913 @caindex prog_fc_g
7914 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7915 the environment, then @code{dialect} is a hint to indicate what Fortran
7916 dialect to search for; the default is to search for the newest available
7917 dialect.  Set the output variable @code{FC} to the name of the compiler
7918 found.
7920 By default, newer dialects are preferred over older dialects, but if
7921 @code{dialect} is specified then older dialects are preferred starting
7922 with the specified dialect.  @code{dialect} can currently be one of
7923 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7924 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7925 and no attempt is made to guarantee that a particular language standard
7926 is actually supported.  Thus, it is preferable that you avoid the
7927 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7928 the latest Fortran standard.
7930 This macro may, alternatively, be invoked with an optional first argument
7931 which, if specified, must be a blank-separated list of Fortran
7932 compilers to search for, just as in @code{AC_PROG_F77}.
7934 If using @code{gfortran} or @code{g77} (the GNU Fortran compilers), then
7935 set the shell variable @code{GFC} to @samp{yes}.
7936 If the output variable @code{FCFLAGS} was not already set in the
7937 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7938 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7939 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7941 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7942 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7943 variable.
7944 @end defmac
7946 @defmac AC_PROG_F77_C_O
7947 @defmacx AC_PROG_FC_C_O
7948 @acindex{PROG_F77_C_O}
7949 @acindex{PROG_FC_C_O}
7950 @cvindex F77_NO_MINUS_C_MINUS_O
7951 @cvindex FC_NO_MINUS_C_MINUS_O
7952 @caindex prog_f77_c_o
7953 @caindex prog_fc_c_o
7954 Test whether the Fortran compiler accepts the options @option{-c} and
7955 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7956 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7958 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7959 @code{ac_cv_prog_fc_c_o} variable, respectively.
7960 @end defmac
7962 The following macros check for Fortran compiler characteristics.
7963 To check for characteristics not listed here, use
7964 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7965 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7966 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7967 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7970 @defmac AC_F77_LIBRARY_LDFLAGS
7971 @defmacx AC_FC_LIBRARY_LDFLAGS
7972 @acindex{F77_LIBRARY_LDFLAGS}
7973 @ovindex FLIBS
7974 @acindex{FC_LIBRARY_LDFLAGS}
7975 @ovindex FCLIBS
7976 @caindex prog_f77_v
7977 @caindex prog_fc_v
7978 @caindex f77_libs
7979 @caindex fc_libs
7980 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7981 @dfn{Fortran intrinsic and runtime libraries} that are required to
7982 successfully link a Fortran program or shared library.  The output
7983 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7984 should be included after @code{LIBS} when linking).
7986 This macro is intended to be used in those situations when it is
7987 necessary to mix, e.g., C++ and Fortran source code in a single
7988 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7989 automake, GNU Automake}).
7991 For example, if object files from a C++ and Fortran compiler must be
7992 linked together, then the C++ compiler/linker must be used for linking
7993 (since special C++-ish things need to happen at link time like calling
7994 global constructors, instantiating templates, enabling exception
7995 support, etc.).
7997 However, the Fortran intrinsic and runtime libraries must be linked in
7998 as well, but the C++ compiler/linker doesn't know by default how to add
7999 these Fortran 77 libraries.  Hence, this macro was created to determine
8000 these Fortran libraries.
8002 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8003 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8004 link C/C++ with Fortran; see below.  Further, it is highly recommended
8005 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8006 because the complex defines that the function wrapper macros create
8007 may not work with C/C++ compiler drivers.
8009 These macros internally compute the flag needed to verbose linking
8010 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8011 variables, respectively.  The computed linker flags are cached in
8012 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8013 @end defmac
8015 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
8016   AC_MSG_FAILURE})
8017 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
8018   AC_MSG_FAILURE})
8019 @acindex{F77_DUMMY_MAIN}
8020 @cvindex F77_DUMMY_MAIN
8021 @acindex{FC_DUMMY_MAIN}
8022 @cvindex FC_DUMMY_MAIN
8023 @caindex f77_dummy_main
8024 @caindex fc_dummy_main
8025 With many compilers, the Fortran libraries detected by
8026 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8027 their own @code{main} entry function that initializes things like
8028 Fortran I/O, and which then calls a user-provided entry function named
8029 (say) @code{MAIN__} to run the user's program.  The
8030 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8031 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8032 this interaction.
8034 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8035 one prefers to provide one's own @code{main} and skip the Fortran
8036 library initializations.  In this case, however, one may still need to
8037 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8038 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8039 detects whether any such routine is @emph{required} for linking, and
8040 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8041 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8042 was found, and @code{none} when no such dummy main is needed.
8044 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8045 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8046 @emph{if} it is required.  @var{action-if-not-found} defaults to
8047 exiting with an error.
8049 In order to link with Fortran routines, the user's C/C++ program should
8050 then include the following code to define the dummy main if it is
8051 needed:
8053 @example
8054 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8055 #ifdef F77_DUMMY_MAIN
8056 #  ifdef __cplusplus
8057      extern "C"
8058 #  endif
8059    int F77_DUMMY_MAIN () @{ return 1; @}
8060 #endif
8061 @end example
8063 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8065 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8066 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8067 explicitly unless one wants to change the default actions.
8069 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8070 @code{ac_cv_fc_dummy_main} variable, respectively.
8071 @end defmac
8073 @defmac AC_F77_MAIN
8074 @defmacx AC_FC_MAIN
8075 @acindex{F77_MAIN}
8076 @cvindex F77_MAIN
8077 @acindex{FC_MAIN}
8078 @cvindex FC_MAIN
8079 @caindex f77_main
8080 @caindex fc_main
8081 As discussed above, many Fortran libraries allow you to provide an entry
8082 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8083 is then called by a @code{main} function in the Fortran libraries that
8084 initializes things like Fortran I/O@.  The
8085 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8086 @emph{possible} to utilize such an alternate main function, and defines
8087 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8088 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8089 simply defined to @code{main}.)
8091 Thus, when calling Fortran routines from C that perform things like I/O,
8092 one should use this macro and declare the "main" function like so:
8094 @example
8095 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8096 #ifdef __cplusplus
8097   extern "C"
8098 #endif
8099 int F77_MAIN (int argc, char *argv[]);
8100 @end example
8102 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8104 The result of this macro is cached in the @code{ac_cv_f77_main} or
8105 @code{ac_cv_fc_main} variable, respectively.
8106 @end defmac
8108 @defmac AC_F77_WRAPPERS
8109 @defmacx AC_FC_WRAPPERS
8110 @acindex{F77_WRAPPERS}
8111 @cvindex F77_FUNC
8112 @cvindex F77_FUNC_
8113 @acindex{FC_WRAPPERS}
8114 @cvindex FC_FUNC
8115 @cvindex FC_FUNC_
8116 @caindex f77_mangling
8117 @caindex fc_mangling
8118 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8119 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8120 mangle the names of C/C++ identifiers, and identifiers with underscores,
8121 respectively, so that they match the name-mangling scheme used by the
8122 Fortran compiler.
8124 Fortran is case-insensitive, and in order to achieve this the Fortran
8125 compiler converts all identifiers into a canonical case and format.  To
8126 call a Fortran subroutine from C or to write a C function that is
8127 callable from Fortran, the C program must explicitly use identifiers in
8128 the format expected by the Fortran compiler.  In order to do this, one
8129 simply wraps all C identifiers in one of the macros provided by
8130 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8131 you have the following Fortran 77 subroutine:
8133 @example
8134 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8135       subroutine foobar (x, y)
8136       double precision x, y
8137       y = 3.14159 * x
8138       return
8139       end
8140 @end example
8142 You would then declare its prototype in C or C++ as:
8144 @example
8145 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8146 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8147 #ifdef __cplusplus
8148 extern "C"  /* prevent C++ name mangling */
8149 #endif
8150 void FOOBAR_F77 (double *x, double *y);
8151 @end example
8153 Note that we pass both the lowercase and uppercase versions of the
8154 function name to @code{F77_FUNC} so that it can select the right one.
8155 Note also that all parameters to Fortran 77 routines are passed as
8156 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8157 Automake}).
8159 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8161 Although Autoconf tries to be intelligent about detecting the
8162 name-mangling scheme of the Fortran compiler, there may be Fortran
8163 compilers that it doesn't support yet.  In this case, the above code
8164 generates a compile-time error, but some other behavior
8165 (e.g., disabling Fortran-related features) can be induced by checking
8166 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8168 Now, to call that routine from a C program, we would do something like:
8170 @example
8171 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8173     double x = 2.7183, y;
8174     FOOBAR_F77 (&x, &y);
8176 @end example
8178 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8179 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8180 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8181 because some Fortran compilers mangle names differently if they contain
8182 an underscore.
8184 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8185 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8186 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8187 @end defmac
8189 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8190 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8191 @acindex{F77_FUNC}
8192 @acindex{FC_FUNC}
8193 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8194 hold the mangled version @var{name} according to the rules of the
8195 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8196 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8197 supplied, the shell variable is simply @var{name}.  The purpose of
8198 this macro is to give the caller a way to access the name-mangling
8199 information other than through the C preprocessor as above, for example,
8200 to call Fortran routines from some language other than C/C++.
8201 @end defmac
8203 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8204   @dvar{action-if-failure, AC_MSG_FAILURE})
8205 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8206   @dvar{action-if-failure, AC_MSG_FAILURE})
8207 @acindex{FC_SRCEXT}
8208 @acindex{FC_PP_SRCEXT}
8209 @caindex fc_srcext_@var{ext}
8210 @caindex fc_pp_srcext_@var{ext}
8211 By default, the @code{FC} macros perform their tests using a @file{.f}
8212 extension for source-code files.  Some compilers, however, only enable
8213 newer language features for appropriately named files, e.g., Fortran 90
8214 features only for @file{.f90} files, or preprocessing only with
8215 @file{.F} files or maybe other upper-case extensions.  On the other
8216 hand, some other compilers expect all source files to end in @file{.f}
8217 and require special flags to support other file name extensions.  The
8218 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8219 issues.
8221 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8222 accept files ending with the extension @file{.@var{ext}} (i.e.,
8223 @var{ext} does @emph{not} contain the dot).  If any special compiler
8224 flags are needed for this, it stores them in the output variable
8225 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8226 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8227 @code{AC_FC_PP_SRCEXT} is called another time).
8229 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8230 @file{.f90} extension in future tests, and it would set the
8231 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8232 to compile such files.
8234 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8235 compiler to preprocess and compile files with the extension
8236 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8237 preprocessing are provided, the former is preferred, as the latter may
8238 treat continuation lines, @code{//} tokens, and white space differently
8239 from what some Fortran dialects expect.  Conversely, if you do not want
8240 files to be preprocessed, use only lower-case characters in the file
8241 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8242 are stored in the @code{FCFLAGS_@var{ext}} variable.
8244 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8245 into @code{FCFLAGS}, for two reasons based on the limitations of some
8246 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8247 time, so files with different extensions must be compiled separately.
8248 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8249 the source-code file name when compiling.  So, continuing the example
8250 above, you might compile a @file{foo.f90} file in your makefile with the
8251 command:
8253 @example
8254 foo.o: foo.f90
8255        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8256 @end example
8258 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8259 files with the @var{ext} extension, it calls @var{action-if-success}
8260 (defaults to nothing).  If it fails, and cannot find a way to make the
8261 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8262 (defaults to exiting with an error message).
8264 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8265 results in @code{ac_cv_fc_srcext_@var{ext}} and
8266 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8267 @end defmac
8269 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @dvar{action-if-failure, @
8270   AC_MSG_FAILURE})
8271 @acindex{FC_PP_DEFINE}
8272 @caindex fc_pp_define
8274 Find a flag to specify defines for preprocessed Fortran.  Not all
8275 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8276 the result and call @var{action-if-success} (defaults to nothing) if
8277 successful, and @var{action-if-failure} (defaults to failing with an
8278 error message) if not.
8280 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8281 to preprocess a @file{conftest.F} file, but restores a previously used
8282 Fortran source file extension afterwards again.
8284 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8285 variable.
8286 @end defmac
8288 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8289   AC_MSG_FAILURE})
8290 @acindex{FC_FREEFORM}
8291 @caindex fc_freeform
8293 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8294 source code (as opposed to the older fixed-format style from Fortran
8295 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8297 This macro is most important if you are using the default @file{.f}
8298 extension, since many compilers interpret this extension as indicating
8299 fixed-format source unless an additional flag is supplied.  If you
8300 specify a different extension with @code{AC_FC_SRCEXT}, such as
8301 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8302 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8303 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8304 the compiler assume Fortran 77 by default, however.
8306 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8307 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8308 calls @var{action-if-failure} (defaults to exiting with an error
8309 message).
8311 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8312 the @code{ac_cv_fc_freeform} variable.
8313 @end defmac
8315 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8316   AC_MSG_FAILURE})
8317 @acindex{FC_FIXEDFORM}
8318 @caindex fc_fixedform
8320 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8321 fixed-format source code (as opposed to free-format style).  If
8322 necessary, it may add some additional flags to @code{FCFLAGS}.
8324 This macro is needed for some compilers alias names like @command{xlf95}
8325 which assume free-form source code by default, and in case you want to
8326 use fixed-form source with an extension like @file{.f90} which many
8327 compilers interpret as free-form by default.  If you specify a different
8328 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8329 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8330 @code{FCFLAGS}.
8332 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8333 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8334 calls @var{action-if-failure} (defaults to exiting with an error
8335 message).
8337 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8338 the @code{ac_cv_fc_fixedform} variable.
8339 @end defmac
8341 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8342   @dvar{action-if-failure, AC_MSG_FAILURE})
8343 @acindex{FC_LINE_LENGTH}
8344 @caindex fc_line_length
8346 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8347 code lines.  The @var{length} argument may be given as 80, 132, or
8348 unlimited, and defaults to 132.  Note that line lengths above 254
8349 columns are not portable, and some compilers do not accept more than 132
8350 columns at least for fixed format source.  If necessary, it may add some
8351 additional flags to @code{FCFLAGS}.
8353 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8354 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8355 calls @var{action-if-failure} (defaults to exiting with an error
8356 message).
8358 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8359 the @code{ac_cv_fc_line_length} variable.
8360 @end defmac
8362 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8363   @dvar{action-if-failure, AC_MSG_FAILURE})
8364 @acindex{FC_CHECK_BOUNDS}
8365 @caindex fc_check_bounds
8367 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8368 in the Fortran compiler.  If successful, the @var{action-if-success}
8369 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8370 @var{action-if-failure} is called, which defaults to failing with an error
8371 message.  The macro currently requires Fortran 90 or a newer dialect.
8373 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8374 variable.
8375 @end defmac
8377 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8378   @dvar{action-if-failure, AC_MSG_FAILURE})
8379 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8380   @dvar{action-if-failure, AC_MSG_FAILURE})
8381 @acindex{F77_IMPLICIT_NONE}
8382 @acindex{FC_IMPLICIT_NONE}
8383 @caindex f77_implicit_none
8384 @caindex fc_implicit_none
8386 Try to disallow implicit declarations in the Fortran compiler.  If
8387 successful, @var{action-if-success} is called and any needed flags
8388 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8389 @var{action-if-failure} is called, which defaults to failing with an error
8390 message.
8392 The result of these macros are cached in the
8393 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8394 variables, respectively.
8395 @end defmac
8397 @defmac AC_FC_MODULE_EXTENSION
8398 @acindex{FC_MODULE_EXTENSION}
8399 @caindex fc_module_ext
8400 @ovindex FC_MODEXT
8402 Find the Fortran 90 module file name extension.  Most Fortran 90
8403 compilers store module information in files separate from the object
8404 files.  The module files are usually named after the name of the module
8405 rather than the source file name, with characters possibly turned to
8406 upper case, plus an extension, often @file{.mod}.
8408 Not all compilers use module files at all, or by default.  The Cray
8409 Fortran compiler requires @option{-e m} in order to store and search
8410 module information in @file{.mod} files rather than in object files.
8411 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8412 indicate how module information is stored.
8414 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8415 without the leading dot, and stores that in the @code{FC_MODEXT}
8416 variable.  If the compiler does not produce module files, or the
8417 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8418 the result of this macro may be used in cleanup @command{make} rules as
8419 follows:
8421 @example
8422 clean-modules:
8423         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8424 @end example
8426 The extension, or @samp{unknown}, is cached in the
8427 @code{ac_cv_fc_module_ext} variable.
8428 @end defmac
8430 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-sucess}, @
8431   @dvar{action-if-failure, AC_MSG_FAILURE})
8432 @acindex{FC_MODULE_FLAG}
8433 @caindex fc_module_flag
8434 @ovindex FC_MODINC
8435 @ovindex ac_empty
8437 Find the compiler flag to include Fortran 90 module information from
8438 another directory, and store that in the @code{FC_MODINC} variable.
8439 Call @var{action-if-success} (defaults to nothing) if successful, and
8440 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8441 to exiting with an error message) if not.
8443 Most Fortran 90 compilers provide a way to specify module directories.
8444 Some have separate flags for the directory to write module files to,
8445 and directories to search them in, whereas others only allow writing to
8446 the current directory or to the first directory specified in the include
8447 path.  Further, with some compilers, the module search path and the
8448 preprocessor search path can only be modified with the same flag.  Thus,
8449 for portability, write module files to the current directory only and
8450 list that as first directory in the search path.
8452 There may be no whitespace between @code{FC_MODINC} and the following
8453 directory name, but @code{FC_MODINC} may contain trailing white space.
8454 For example, if you use Automake and would like to search @file{../lib}
8455 for module files, you can use the following:
8457 @example
8458 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8459 @end example
8461 Inside @command{configure} tests, you can use:
8463 @example
8464 if test -n "$FC_MODINC"; then
8465   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8467 @end example
8469 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8470 The substituted value of @code{FC_MODINC} may refer to the
8471 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8472 the significant trailing whitespace in a @file{Makefile}.
8473 @end defmac
8475 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-sucess}, @
8476   @dvar{action-if-failure, AC_MSG_FAILURE})
8477 @acindex{FC_MODULE_OUTPUT_FLAG}
8478 @caindex fc_module_output_flag
8479 @ovindex FC_MODOUT
8481 Find the compiler flag to write Fortran 90 module information to
8482 another directory, and store that in the @code{FC_MODOUT} variable.
8483 Call @var{action-if-success} (defaults to nothing) if successful, and
8484 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8485 to exiting with an error message) if not.
8487 Not all Fortran 90 compilers write module files, and of those that do,
8488 not all allow writing to a directory other than the current one, nor
8489 do all have separate flags for writing and reading; see the description
8490 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8491 another directory, for maximum portability use @code{FC_MODOUT} before
8492 any @code{FC_MODINC} and include both the current directory and the one
8493 you write to in the search path:
8495 @example
8496 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8497 @end example
8499 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8500 The substituted value of @code{FC_MODOUT} may refer to the
8501 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8502 the significant trailing whitespace in a @file{Makefile}.
8503 @end defmac
8506 @node Go Compiler
8507 @subsection Go Compiler Characteristics
8508 @cindex Go
8510 Autoconf provides basic support for the Go programming language when
8511 using the @code{gccgo} compiler (there is currently no support for the
8512 @code{6g} and @code{8g} compilers).
8514 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8515 Find the Go compiler to use.  Check whether the environment variable
8516 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8517 value.
8519 Otherwise, if the macro is invoked without an argument, then search for
8520 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8521 resort set @code{GOC} to @code{gccgo}.
8523 This macro may be invoked with an optional first argument which, if
8524 specified, must be a blank-separated list of Go compilers to search for.
8526 If output variable @code{GOFLAGS} was not already set, set it to
8527 @option{-g -O2}.  If your package does not like this default,
8528 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8529 @end defmac
8532 @node System Services
8533 @section System Services
8535 The following macros check for operating system services or capabilities.
8537 @anchor{AC_PATH_X}
8538 @defmac AC_PATH_X
8539 @acindex{PATH_X}
8540 @evindex XMKMF
8541 @cindex X Window System
8542 Try to locate the X Window System include files and libraries.  If the
8543 user gave the command line options @option{--x-includes=@var{dir}} and
8544 @option{--x-libraries=@var{dir}}, use those directories.
8546 If either or both were not given, get the missing values by running
8547 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8548 environment variable) on a trivial @file{Imakefile} and examining the
8549 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8550 disables this method.
8552 If this method fails to find the X Window System, @command{configure}
8553 looks for the files in several directories where they often reside.
8554 If either method is successful, set the shell variables
8555 @code{x_includes} and @code{x_libraries} to their locations, unless they
8556 are in directories the compiler searches by default.
8558 If both methods fail, or the user gave the command line option
8559 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8560 otherwise set it to the empty string.
8561 @end defmac
8563 @anchor{AC_PATH_XTRA}
8564 @defmac AC_PATH_XTRA
8565 @acindex{PATH_XTRA}
8566 @ovindex X_CFLAGS
8567 @ovindex X_LIBS
8568 @ovindex X_EXTRA_LIBS
8569 @ovindex X_PRE_LIBS
8570 @cvindex X_DISPLAY_MISSING
8571 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8572 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8573 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8574 available.
8576 This macro also checks for special libraries that some systems need in
8577 order to compile X programs.  It adds any that the system needs to
8578 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8579 libraries that need to be linked with before @option{-lX11}, and adds
8580 any found to the output variable @code{X_PRE_LIBS}.
8582 @c This is an incomplete kludge.  Make a real way to do it.
8583 @c If you need to check for other X functions or libraries yourself, then
8584 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8585 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8586 @end defmac
8588 @anchor{AC_SYS_INTERPRETER}
8589 @defmac AC_SYS_INTERPRETER
8590 @acindex{SYS_INTERPRETER}
8591 Check whether the system supports starting scripts with a line of the
8592 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8593 After running this macro, shell code in @file{configure.ac} can check
8594 the shell variable @code{interpval}; it is set to @samp{yes}
8595 if the system supports @samp{#!}, @samp{no} if not.
8596 @end defmac
8598 @defmac AC_SYS_LARGEFILE
8599 @acindex{SYS_LARGEFILE}
8600 @cvindex _FILE_OFFSET_BITS
8601 @cvindex _LARGE_FILES
8602 @ovindex CC
8603 @cindex Large file support
8604 @cindex LFS
8605 Arrange for 64-bit file offsets, known as
8606 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8607 large-file support}.  On some hosts, one must use special compiler
8608 options to build programs that can access large files.  Append any such
8609 options to the output variable @code{CC}.  Define
8610 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8612 Large-file support can be disabled by configuring with the
8613 @option{--disable-largefile} option.
8615 If you use this macro, check that your program works even when
8616 @code{off_t} is wider than @code{long int}, since this is common when
8617 large-file support is enabled.  For example, it is not correct to print
8618 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8619 (long int) X)}.
8621 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8622 replace their C counterparts @code{fseek} and @code{ftell} that do not
8623 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8624 prototypes available when using them and large-file support is
8625 enabled.
8626 @end defmac
8628 @anchor{AC_SYS_LONG_FILE_NAMES}
8629 @defmac AC_SYS_LONG_FILE_NAMES
8630 @acindex{SYS_LONG_FILE_NAMES}
8631 @cvindex HAVE_LONG_FILE_NAMES
8632 If the system supports file names longer than 14 characters, define
8633 @code{HAVE_LONG_FILE_NAMES}.
8634 @end defmac
8636 @defmac AC_SYS_POSIX_TERMIOS
8637 @acindex{SYS_POSIX_TERMIOS}
8638 @cindex Posix termios headers
8639 @cindex termios Posix headers
8640 @caindex sys_posix_termios
8641 Check to see if the Posix termios headers and functions are available on the
8642 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8643 @samp{yes}.  If not, set the variable to @samp{no}.
8644 @end defmac
8646 @node Posix Variants
8647 @section Posix Variants
8649 The following macro makes it possible to use features of Posix that are
8650 extensions to C, as well as platform extensions not defined by Posix.
8652 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8653 @defmac AC_USE_SYSTEM_EXTENSIONS
8654 @acindex{USE_SYSTEM_EXTENSIONS}
8655 @cvindex _ALL_SOURCE
8656 @cvindex _GNU_SOURCE
8657 @cvindex _MINIX
8658 @cvindex _POSIX_1_SOURCE
8659 @cvindex _POSIX_PTHREAD_SEMANTICS
8660 @cvindex _POSIX_SOURCE
8661 @cvindex _TANDEM_SOURCE
8662 @cvindex __EXTENSIONS__
8663 This macro was introduced in Autoconf 2.60.  If possible, enable
8664 extensions to C or Posix on hosts that normally disable the extensions,
8665 typically due to standards-conformance namespace issues.  This should be
8666 called before any macros that run the C compiler.  The following
8667 preprocessor macros are defined where appropriate:
8669 @table @code
8670 @item _GNU_SOURCE
8671 Enable extensions on GNU/Linux.
8672 @item __EXTENSIONS__
8673 Enable general extensions on Solaris.
8674 @item _POSIX_PTHREAD_SEMANTICS
8675 Enable threading extensions on Solaris.
8676 @item _TANDEM_SOURCE
8677 Enable extensions for the HP NonStop platform.
8678 @item _ALL_SOURCE
8679 Enable extensions for AIX 3, and for Interix.
8680 @item _POSIX_SOURCE
8681 Enable Posix functions for Minix.
8682 @item _POSIX_1_SOURCE
8683 Enable additional Posix functions for Minix.
8684 @item _MINIX
8685 Identify Minix platform.  This particular preprocessor macro is
8686 obsolescent, and may be removed in a future release of Autoconf.
8687 @end table
8688 @end defmac
8691 @node Erlang Libraries
8692 @section Erlang Libraries
8693 @cindex Erlang, Library, checking
8695 The following macros check for an installation of Erlang/OTP, and for the
8696 presence of certain Erlang libraries.  All those macros require the
8697 configuration of an Erlang interpreter and an Erlang compiler
8698 (@pxref{Erlang Compiler and Interpreter}).
8700 @defmac AC_ERLANG_SUBST_ERTS_VER
8701 @acindex{ERLANG_SUBST_ERTS_VER}
8702 @ovindex ERLANG_ERTS_VER
8703 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8704 Erlang runtime system (as returned by Erlang's
8705 @code{erlang:system_info(version)} function).  The result of this test
8706 is cached if caching is enabled when running @command{configure}.  The
8707 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8708 for features of specific ERTS versions, but to be used for substituting
8709 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8710 files), as shown below.
8711 @end defmac
8713 @defmac AC_ERLANG_SUBST_ROOT_DIR
8714 @acindex{ERLANG_SUBST_ROOT_DIR}
8715 @ovindex ERLANG_ROOT_DIR
8716 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8717 directory in which Erlang/OTP is installed (as returned by Erlang's
8718 @code{code:root_dir/0} function).  The result of this test is cached if
8719 caching is enabled when running @command{configure}.
8720 @end defmac
8722 @defmac AC_ERLANG_SUBST_LIB_DIR
8723 @acindex{ERLANG_SUBST_LIB_DIR}
8724 @ovindex ERLANG_LIB_DIR
8725 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8726 directory of Erlang/OTP (as returned by Erlang's
8727 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8728 Erlang/OTP library.  The result of this test is cached if caching is enabled
8729 when running @command{configure}.
8730 @end defmac
8732 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8733   @ovar{action-if-not-found})
8734 @acindex{ERLANG_CHECK_LIB}
8735 @ovindex ERLANG_LIB_DIR_@var{library}
8736 @ovindex ERLANG_LIB_VER_@var{library}
8737 Test whether the Erlang/OTP library @var{library} is installed by
8738 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8739 test is cached if caching is enabled when running @command{configure}.
8740 @var{action-if-found} is a list of shell commands to run if the library
8741 is installed; @var{action-if-not-found} is a list of shell commands to
8742 run if it is not.  Additionally, if the library is installed, the output
8743 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8744 library installation directory, and the output variable
8745 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8746 part of the subdirectory name, if it is in the standard form
8747 (@code{@var{library}-@var{version}}).  If the directory name does not
8748 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8749 empty string.  If the library is not installed,
8750 @samp{ERLANG_LIB_DIR_@var{library}} and
8751 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8752 example, to check if library @code{stdlib} is installed:
8754 @example
8755 AC_ERLANG_CHECK_LIB([stdlib],
8756   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8757    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8758   [AC_MSG_ERROR([stdlib was not found!])])
8759 @end example
8761 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8762 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8763 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8764 testing for features of specific versions of libraries or of the Erlang
8765 runtime system.  Those variables are intended to be substituted in
8766 Erlang release resource files (@code{.rel} files).  For instance, to
8767 generate a @file{example.rel} file for an application depending on the
8768 @code{stdlib} library, @file{configure.ac} could contain:
8770 @example
8771 AC_ERLANG_SUBST_ERTS_VER
8772 AC_ERLANG_CHECK_LIB([stdlib],
8773   [],
8774   [AC_MSG_ERROR([stdlib was not found!])])
8775 AC_CONFIG_FILES([example.rel])
8776 @end example
8778 @noindent
8779 The @file{example.rel.in} file used to generate @file{example.rel}
8780 should contain:
8782 @example
8783 @{release,
8784     @{"@@PACKAGE@@", "@@VERSION@@"@},
8785     @{erts, "@@ERLANG_ERTS_VER@@"@},
8786     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8787      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8788 @end example
8789 @end defmac
8791 In addition to the above macros, which test installed Erlang libraries, the
8792 following macros determine the paths to the directories into which newly built
8793 Erlang libraries are to be installed:
8795 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8796 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8797 @ovindex ERLANG_INSTALL_LIB_DIR
8799 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8800 which every built Erlang library should be installed in a separate
8801 subdirectory.
8802 If this variable is not set in the environment when @command{configure} runs,
8803 its default value is @code{$@{libdir@}/erlang/lib}.
8804 @end defmac
8806 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8807 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8808 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8810 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8811 directory into which the built Erlang library @var{library} version
8812 @var{version} should be installed.  If this variable is not set in the
8813 environment when @command{configure} runs, its default value is
8814 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8815 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8816 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8817 @end defmac
8823 @c ========================================================= Writing Tests
8825 @node Writing Tests
8826 @chapter Writing Tests
8828 If the existing feature tests don't do something you need, you have to
8829 write new ones.  These macros are the building blocks.  They provide
8830 ways for other macros to check whether various kinds of features are
8831 available and report the results.
8833 This chapter contains some suggestions and some of the reasons why the
8834 existing tests are written the way they are.  You can also learn a lot
8835 about how to write Autoconf tests by looking at the existing ones.  If
8836 something goes wrong in one or more of the Autoconf tests, this
8837 information can help you understand the assumptions behind them, which
8838 might help you figure out how to best solve the problem.
8840 These macros check the output of the compiler system of the current
8841 language (@pxref{Language Choice}).  They do not cache the results of
8842 their tests for future use (@pxref{Caching Results}), because they don't
8843 know enough about the information they are checking for to generate a
8844 cache variable name.  They also do not print any messages, for the same
8845 reason.  The checks for particular kinds of features call these macros
8846 and do cache their results and print messages about what they're
8847 checking for.
8849 When you write a feature test that could be applicable to more than one
8850 software package, the best thing to do is encapsulate it in a new macro.
8851 @xref{Writing Autoconf Macros}, for how to do that.
8853 @menu
8854 * Language Choice::             Selecting which language to use for testing
8855 * Writing Test Programs::       Forging source files for compilers
8856 * Running the Preprocessor::    Detecting preprocessor symbols
8857 * Running the Compiler::        Detecting language or header features
8858 * Running the Linker::          Detecting library features
8859 * Runtime::                     Testing for runtime features
8860 * Systemology::                 A zoology of operating systems
8861 * Multiple Cases::              Tests for several possible values
8862 @end menu
8864 @node Language Choice
8865 @section Language Choice
8866 @cindex Language
8868 Autoconf-generated @command{configure} scripts check for the C compiler and
8869 its features by default.  Packages that use other programming languages
8870 (maybe more than one, e.g., C and C++) need to test features of the
8871 compilers for the respective languages.  The following macros determine
8872 which programming language is used in the subsequent tests in
8873 @file{configure.ac}.
8875 @anchor{AC_LANG}
8876 @defmac AC_LANG (@var{language})
8877 @acindex{LANG}
8878 Do compilation tests using the compiler, preprocessor, and file
8879 extensions for the specified @var{language}.
8881 Supported languages are:
8883 @table @samp
8884 @item C
8885 Do compilation tests using @code{CC} and @code{CPP} and use extension
8886 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8887 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8889 @item C++
8890 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8891 extension @file{.C} for test programs.  Use compilation flags:
8892 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8893 @code{CXXFLAGS} with @code{CXX}.
8895 @item Fortran 77
8896 Do compilation tests using @code{F77} and use extension @file{.f} for
8897 test programs.  Use compilation flags: @code{FFLAGS}.
8899 @item Fortran
8900 Do compilation tests using @code{FC} and use extension @file{.f} (or
8901 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8902 compilation flags: @code{FCFLAGS}.
8904 @item Erlang
8905 @ovindex ERLC
8906 @ovindex ERL
8907 @ovindex ERLCFLAGS
8908 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8909 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8911 @item Objective C
8912 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8913 extension @file{.m} for test programs.  Use compilation flags:
8914 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8915 @code{OBJCFLAGS} with @code{OBJC}.
8917 @item Objective C++
8918 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8919 extension @file{.mm} for test programs.  Use compilation flags:
8920 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8921 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8923 @item Go
8924 Do compilation tests using @code{GOC} and use extension @file{.go} for
8925 test programs.  Use compilation flags @code{GOFLAGS}.
8926 @end table
8927 @end defmac
8929 @anchor{AC_LANG_PUSH}
8930 @defmac AC_LANG_PUSH (@var{language})
8931 @acindex{LANG_PUSH}
8932 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8933 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8934 in macros that need to temporarily switch to a particular language.
8935 @end defmac
8937 @defmac AC_LANG_POP (@ovar{language})
8938 @acindex{LANG_POP}
8939 Select the language that is saved on the top of the stack, as set by
8940 @code{AC_LANG_PUSH}, and remove it from the stack.
8942 If given, @var{language} specifies the language we just @emph{quit}.  It
8943 is a good idea to specify it when it's known (which should be the
8944 case@dots{}), since Autoconf detects inconsistencies.
8946 @example
8947 AC_LANG_PUSH([Fortran 77])
8948 # Perform some tests on Fortran 77.
8949 # @dots{}
8950 AC_LANG_POP([Fortran 77])
8951 @end example
8952 @end defmac
8954 @defmac AC_LANG_ASSERT (@var{language})
8955 @acindex{LANG_ASSERT}
8956 Check statically that the current language is @var{language}.
8957 You should use this in your language specific macros
8958 to avoid that they be called with an inappropriate language.
8960 This macro runs only at @command{autoconf} time, and incurs no cost at
8961 @command{configure} time.  Sadly enough and because Autoconf is a two
8962 layer language @footnote{Because M4 is not aware of Sh code,
8963 especially conditionals, some optimizations that look nice statically
8964 may produce incorrect results at runtime.}, the macros
8965 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8966 therefore as much as possible you ought to avoid using them to wrap
8967 your code, rather, require from the user to run the macro with a
8968 correct current language, and check it with @code{AC_LANG_ASSERT}.
8969 And anyway, that may help the user understand she is running a Fortran
8970 macro while expecting a result about her Fortran 77 compiler@enddots{}
8971 @end defmac
8974 @defmac AC_REQUIRE_CPP
8975 @acindex{REQUIRE_CPP}
8976 Ensure that whichever preprocessor would currently be used for tests has
8977 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8978 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8979 depending on which language is current.
8980 @end defmac
8983 @node Writing Test Programs
8984 @section Writing Test Programs
8986 Autoconf tests follow a common scheme: feed some program with some
8987 input, and most of the time, feed a compiler with some source file.
8988 This section is dedicated to these source samples.
8990 @menu
8991 * Guidelines::                  General rules for writing test programs
8992 * Test Functions::              Avoiding pitfalls in test programs
8993 * Generating Sources::          Source program boilerplate
8994 @end menu
8996 @node Guidelines
8997 @subsection Guidelines for Test Programs
8999 The most important rule to follow when writing testing samples is:
9001 @center @emph{Look for realism.}
9003 This motto means that testing samples must be written with the same
9004 strictness as real programs are written.  In particular, you should
9005 avoid ``shortcuts'' and simplifications.
9007 Don't just play with the preprocessor if you want to prepare a
9008 compilation.  For instance, using @command{cpp} to check whether a header is
9009 functional might let your @command{configure} accept a header which
9010 causes some @emph{compiler} error.  Do not hesitate to check a header with
9011 other headers included before, especially required headers.
9013 Make sure the symbols you use are properly defined, i.e., refrain from
9014 simply declaring a function yourself instead of including the proper
9015 header.
9017 Test programs should not write to standard output.  They
9018 should exit with status 0 if the test succeeds, and with status 1
9019 otherwise, so that success
9020 can be distinguished easily from a core dump or other failure;
9021 segmentation violations and other failures produce a nonzero exit
9022 status.  Unless you arrange for @code{exit} to be declared, test
9023 programs should @code{return}, not @code{exit}, from @code{main},
9024 because on many systems @code{exit} is not declared by default.
9026 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9027 preprocessor macros defined by tests that have already run.  For
9028 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9029 @file{configure.ac} you can have a test program that includes
9030 @file{stdbool.h} conditionally:
9032 @example
9033 @group
9034 #ifdef HAVE_STDBOOL_H
9035 # include <stdbool.h>
9036 #endif
9037 @end group
9038 @end example
9040 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9041 work with any standard C compiler.  Some developers prefer @code{#if}
9042 because it is easier to read, while others prefer @code{#ifdef} because
9043 it avoids diagnostics with picky compilers like GCC with the
9044 @option{-Wundef} option.
9046 If a test program needs to use or create a data file, give it a name
9047 that starts with @file{conftest}, such as @file{conftest.data}.  The
9048 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9049 after running test programs and if the script is interrupted.
9051 @node Test Functions
9052 @subsection Test Functions
9054 These days it's safe to assume support for function prototypes
9055 (introduced in C89).
9057 Functions that test programs declare should also be conditionalized for
9058 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9059 include any header files containing clashing prototypes.
9061 @example
9062 #ifdef __cplusplus
9063 extern "C"
9064 #endif
9065 void *valloc (size_t);
9066 @end example
9068 If a test program calls a function with invalid parameters (just to see
9069 whether it exists), organize the program to ensure that it never invokes
9070 that function.  You can do this by calling it in another function that is
9071 never invoked.  You can't do it by putting it after a call to
9072 @code{exit}, because GCC version 2 knows that @code{exit}
9073 never returns
9074 and optimizes out any code that follows it in the same block.
9076 If you include any header files, be sure to call the functions
9077 relevant to them with the correct number of arguments, even if they are
9078 just 0, to avoid compilation errors due to prototypes.  GCC
9079 version 2
9080 has internal prototypes for several functions that it automatically
9081 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9082 them, either pass them the correct number of arguments or redeclare them
9083 with a different return type (such as @code{char}).
9086 @node Generating Sources
9087 @subsection Generating Sources
9089 Autoconf provides a set of macros that can be used to generate test
9090 source files.  They are written to be language generic, i.e., they
9091 actually depend on the current language (@pxref{Language Choice}) to
9092 ``format'' the output properly.
9095 @defmac AC_LANG_CONFTEST (@var{source})
9096 @acindex{LANG_CONFTEST}
9097 Save the @var{source} text in the current test source file:
9098 @file{conftest.@var{extension}} where the @var{extension} depends on the
9099 current language.  As of Autoconf 2.63b, the source file also contains
9100 the results of all of the @code{AC_DEFINE} performed so far.
9102 Note that the @var{source} is evaluated exactly once, like regular
9103 Autoconf macro arguments, and therefore (i) you may pass a macro
9104 invocation, (ii) if not, be sure to double quote if needed.
9106 This macro issues a warning during @command{autoconf} processing if
9107 @var{source} does not include an expansion of the macro
9108 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9109 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9111 This macro is seldom called directly, but is used under the hood by more
9112 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9113 @end defmac
9115 @defmac AC_LANG_DEFINES_PROVIDED
9116 @acindex{LANG_DEFINES_PROVIDED}
9117 This macro is called as a witness that the file
9118 @file{conftest.@var{extension}} appropriate for the current language is
9119 complete, including all previously determined results from
9120 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9121 you have a compelling reason to write a conftest file without using
9122 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9123 @code{AC_LANG_CONFTEST}.
9124 @end defmac
9126 @defmac AC_LANG_SOURCE (@var{source})
9127 @acindex{LANG_SOURCE}
9128 Expands into the @var{source}, with the definition of
9129 all the @code{AC_DEFINE} performed so far.  This macro includes an
9130 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9132 In many cases, you may find it more convenient to use the wrapper
9133 @code{AC_LANG_PROGRAM}.
9134 @end defmac
9136 For instance, executing (observe the double quotation!):
9138 @example
9139 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9140 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9141         [http://www.example.org/])
9142 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9143   [Greetings string.])
9144 AC_LANG([C])
9145 AC_LANG_CONFTEST(
9146    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9147 gcc -E -dD conftest.c
9148 @end example
9150 @noindent
9151 on a system with @command{gcc} installed, results in:
9153 @example
9154 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9155 @dots{}
9156 # 1 "conftest.c"
9158 #define PACKAGE_NAME "Hello"
9159 #define PACKAGE_TARNAME "hello"
9160 #define PACKAGE_VERSION "1.0"
9161 #define PACKAGE_STRING "Hello 1.0"
9162 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9163 #define PACKAGE_URL "http://www.example.org/"
9164 #define HELLO_WORLD "Hello, World\n"
9166 const char hw[] = "Hello, World\n";
9167 @end example
9169 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9170 definitions are not automatically translated into constants in the
9171 source code by this macro.
9173 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9174 @acindex{LANG_PROGRAM}
9175 Expands into a source file which consists of the @var{prologue}, and
9176 then @var{body} as body of the main function (e.g., @code{main} in
9177 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9178 available.
9179 @end defmac
9181 For instance:
9183 @example
9184 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9185 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9186         [http://www.example.org/])
9187 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9188   [Greetings string.])
9189 AC_LANG_CONFTEST(
9190 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9191                  [[fputs (hw, stdout);]])])
9192 gcc -E -dD conftest.c
9193 @end example
9195 @noindent
9196 on a system with @command{gcc} installed, results in:
9198 @example
9199 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9200 @dots{}
9201 # 1 "conftest.c"
9203 #define PACKAGE_NAME "Hello"
9204 #define PACKAGE_TARNAME "hello"
9205 #define PACKAGE_VERSION "1.0"
9206 #define PACKAGE_STRING "Hello 1.0"
9207 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9208 #define PACKAGE_URL "http://www.example.org/"
9209 #define HELLO_WORLD "Hello, World\n"
9211 const char hw[] = "Hello, World\n";
9213 main ()
9215 fputs (hw, stdout);
9216   ;
9217   return 0;
9219 @end example
9221 In Erlang tests, the created source file is that of an Erlang module called
9222 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9223 at least
9224 one @code{start/0} function, which is called to perform the test.  The
9225 @var{prologue} is optional code that is inserted between the module header and
9226 the @code{start/0} function definition.  @var{body} is the body of the
9227 @code{start/0} function without the final period (@pxref{Runtime}, about
9228 constraints on this function's behavior).
9230 For instance:
9232 @example
9233 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9234 AC_LANG(Erlang)
9235 AC_LANG_CONFTEST(
9236 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9237                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9238 cat conftest.erl
9239 @end example
9241 @noindent
9242 results in:
9244 @example
9245 -module(conftest).
9246 -export([start/0]).
9247 -define(HELLO_WORLD, "Hello, world!").
9248 start() ->
9249 io:format("~s~n", [?HELLO_WORLD])
9251 @end example
9253 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9254 @acindex{LANG_CALL}
9255 Expands into a source file which consists of the @var{prologue}, and
9256 then a call to the @var{function} as body of the main function (e.g.,
9257 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9258 of the latter are available.
9260 This function will probably be replaced in the future by a version
9261 which would enable specifying the arguments.  The use of this macro is
9262 not encouraged, as it violates strongly the typing system.
9264 This macro cannot be used for Erlang tests.
9265 @end defmac
9267 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9268 @acindex{LANG_FUNC_LINK_TRY}
9269 Expands into a source file which uses the @var{function} in the body of
9270 the main function (e.g., @code{main} in C).  Since it uses
9271 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9273 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9274 It is considered to be severely broken, and in the future will be
9275 removed in favor of actual function calls (with properly typed
9276 arguments).
9278 This macro cannot be used for Erlang tests.
9279 @end defmac
9281 @node Running the Preprocessor
9282 @section Running the Preprocessor
9284 Sometimes one might need to run the preprocessor on some source file.
9285 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9286 your project, not merely run the preprocessor on it; therefore you
9287 certainly want to run the compiler, not the preprocessor.  Resist the
9288 temptation of following the easiest path.
9290 Nevertheless, if you need to run the preprocessor, then use
9291 @code{AC_PREPROC_IFELSE}.
9293 The macros described in this section cannot be used for tests in Erlang,
9294 Fortran, or Go, since those languages require no preprocessor.
9296 @anchor{AC_PREPROC_IFELSE}
9297 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9298   @ovar{action-if-false})
9299 @acindex{PREPROC_IFELSE}
9300 Run the preprocessor of the current language (@pxref{Language Choice})
9301 on the @var{input}, run the shell commands @var{action-if-true} on
9302 success, @var{action-if-false} otherwise.  The @var{input} can be made
9303 by @code{AC_LANG_PROGRAM} and friends.
9305 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9306 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9307 preprocessors.
9309 It is customary to report unexpected failures with
9310 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9311 the preprocessed output in the file @file{conftest.i}.
9312 @end defmac
9314 For instance:
9316 @example
9317 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9318 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9319   [Greetings string.])
9320 AC_PREPROC_IFELSE(
9321    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9322                     [[fputs (hw, stdout);]])],
9323    [AC_MSG_RESULT([OK])],
9324    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9325 @end example
9327 @noindent
9328 results in:
9330 @example
9331 checking for gcc... gcc
9332 checking for C compiler default output file name... a.out
9333 checking whether the C compiler works... yes
9334 checking whether we are cross compiling... no
9335 checking for suffix of executables...
9336 checking for suffix of object files... o
9337 checking whether we are using the GNU C compiler... yes
9338 checking whether gcc accepts -g... yes
9339 checking for gcc option to accept ISO C89... none needed
9340 checking how to run the C preprocessor... gcc -E
9342 @end example
9344 @sp 1
9346 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9347 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9348 it impossible to use it to elaborate sources.  You are encouraged to
9349 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9350 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9351 to run the @emph{preprocessor} and not the compiler?
9353 @anchor{AC_EGREP_HEADER}
9354 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9355   @var{action-if-found}, @ovar{action-if-not-found})
9356 @acindex{EGREP_HEADER}
9357 If the output of running the preprocessor on the system header file
9358 @var{header-file} matches the extended regular expression
9359 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9360 execute @var{action-if-not-found}.
9361 @end defmac
9363 @anchor{AC_EGREP_CPP}
9364 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9365   @ovar{action-if-found}, @ovar{action-if-not-found})
9366 @acindex{EGREP_CPP}
9367 @var{program} is the text of a C or C++ program, on which shell
9368 variable, back quote, and backslash substitutions are performed.  If the
9369 output of running the preprocessor on @var{program} matches the
9370 extended regular expression @var{pattern}, execute shell commands
9371 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9372 @end defmac
9376 @node Running the Compiler
9377 @section Running the Compiler
9379 To check for a syntax feature of the current language's (@pxref{Language
9380 Choice}) compiler, such as whether it recognizes a certain keyword, or
9381 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9382 to compile a small program that uses that feature.
9384 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9385   @ovar{action-if-false})
9386 @acindex{COMPILE_IFELSE}
9387 Run the compiler and compilation flags of the current language
9388 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9389 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9390 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9392 It is customary to report unexpected failures with
9393 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9394 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9395 Linker}).  If needed, @var{action-if-true} can further access the
9396 just-compiled object file @file{conftest.$OBJEXT}.
9398 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9399 current language, which means that if the compiler has not yet been
9400 determined, the compiler determination will be made prior to the body of
9401 the outermust @code{AC_DEFUN} macro that triggered this macro to
9402 expand (@pxref{Expanded Before Required}).
9403 @end defmac
9405 @ovindex ERL
9406 For tests in Erlang, the @var{input} must be the source code of a module named
9407 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9408 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9409 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9410 to ensure that the Erlang module has the right name.
9412 @node Running the Linker
9413 @section Running the Linker
9415 To check for a library, a function, or a global variable, Autoconf
9416 @command{configure} scripts try to compile and link a small program that
9417 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9418 @code{ar} on the C library to try to figure out which functions are
9419 available.  Trying to link with the function is usually a more reliable
9420 approach because it avoids dealing with the variations in the options
9421 and output formats of @code{nm} and @code{ar} and in the location of the
9422 standard libraries.  It also allows configuring for cross-compilation or
9423 checking a function's runtime behavior if needed.  On the other hand,
9424 it can be slower than scanning the libraries once, but accuracy is more
9425 important than speed.
9427 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9428 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9429 to check for libraries (@pxref{Libraries}), by adding the library being
9430 checked for to @code{LIBS} temporarily and trying to link a small
9431 program.
9433 @anchor{AC_LINK_IFELSE}
9434 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9435   @ovar{action-if-false})
9436 @acindex{LINK_IFELSE}
9437 Run the compiler (and compilation flags) and the linker of the current
9438 language (@pxref{Language Choice}) on the @var{input}, run the shell
9439 commands @var{action-if-true} on success, @var{action-if-false}
9440 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9441 friends.  If needed, @var{action-if-true} can further access the
9442 just-linked program file @file{conftest$EXEEXT}.
9444 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9445 current compilation flags.
9447 It is customary to report unexpected failures with
9448 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9449 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9450 @end defmac
9452 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9453 programs are interpreted and do not require linking.
9457 @node Runtime
9458 @section Checking Runtime Behavior
9460 Sometimes you need to find out how a system performs at runtime, such
9461 as whether a given function has a certain capability or bug.  If you
9462 can, make such checks when your program runs instead of when it is
9463 configured.  You can check for things like the machine's endianness when
9464 your program initializes itself.
9466 If you really need to test for a runtime behavior while configuring,
9467 you can write a test program to determine the result, and compile and
9468 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9469 possible, because this prevents people from configuring your package for
9470 cross-compiling.
9472 @anchor{AC_RUN_IFELSE}
9473 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9474   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9475 @acindex{RUN_IFELSE}
9476 Run the compiler (and compilation flags) and the linker of the current
9477 language (@pxref{Language Choice}) on the @var{input}, then execute the
9478 resulting program.  If the program returns an exit
9479 status of 0 when executed, run shell commands @var{action-if-true}.
9480 Otherwise, run shell commands @var{action-if-false}.
9482 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9483 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9484 compilation flags of the current language (@pxref{Language Choice}).
9485 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9486 for further testing.
9488 In the @var{action-if-false} section, the failing exit status is
9489 available in the shell variable @samp{$?}.  This exit status might be
9490 that of a failed compilation, or it might be that of a failed program
9491 execution.
9493 If the compiler being used does not produce executables that run on the
9494 system where @command{configure} is being run, then the test program is
9495 not run.  If the optional shell commands @var{action-if-cross-compiling}
9496 are given, those commands are run instead; typically these commands
9497 provide pessimistic defaults that allow cross-compilation to work even
9498 if the guess was wrong.  If the fourth argument is empty or omitted, but
9499 cross-compilation is detected, then @command{configure} prints an error
9500 message and exits.  If you want your package to be useful in a
9501 cross-compilation scenario, you @emph{should} provide a non-empty
9502 @var{action-if-cross-compiling} clause, as well as wrap the
9503 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9504 (@pxref{Caching Results}) which allows the user to override the
9505 pessimistic default if needed.
9507 It is customary to report unexpected failures with
9508 @code{AC_MSG_FAILURE}.
9509 @end defmac
9511 @command{autoconf} prints a warning message when creating
9512 @command{configure} each time it encounters a call to
9513 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9514 given.  If you are not concerned about users configuring your package
9515 for cross-compilation, you may ignore the warning.  A few of the macros
9516 distributed with Autoconf produce this warning message; but if this is a
9517 problem for you, please report it as a bug, along with an appropriate
9518 pessimistic guess to use instead.
9520 To configure for cross-compiling you can also choose a value for those
9521 parameters based on the canonical system name (@pxref{Manual
9522 Configuration}).  Alternatively, set up a test results cache file with
9523 the correct values for the host system (@pxref{Caching Results}).
9525 @ovindex cross_compiling
9526 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9527 in other macros, including a few of the ones that come with Autoconf,
9528 you can test whether the shell variable @code{cross_compiling} is set to
9529 @samp{yes}, and then use an alternate method to get the results instead
9530 of calling the macros.
9532 It is also permissible to temporarily assign to @code{cross_compiling}
9533 in order to force tests to behave as though they are in a
9534 cross-compilation environment, particularly since this provides a way to
9535 test your @var{action-if-cross-compiling} even when you are not using a
9536 cross-compiler.
9538 @example
9539 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9540 # to use the slow link-only method
9541 save_cross_compiling=$cross_compiling
9542 cross_compiling=yes
9543 AC_COMPUTE_INT([@dots{}])
9544 cross_compiling=$save_cross_compiling
9545 @end example
9547 A C or C++ runtime test should be portable.
9548 @xref{Portable C and C++}.
9550 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9551 function: the given status code is used to determine the success of the test
9552 (status is @code{0}) or its failure (status is different than @code{0}), as
9553 explained above.  It must be noted that data output through the standard output
9554 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9555 Therefore, if a test must output configuration information, it is recommended
9556 to create and to output data into the temporary file named @file{conftest.out},
9557 using the functions of module @code{file}.  The @code{conftest.out} file is
9558 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9559 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9560 macro is:
9562 @example
9563 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9564 AC_ERLANG_NEED_ERL
9565 AC_LANG(Erlang)
9566 AC_RUN_IFELSE(
9567   [AC_LANG_PROGRAM([], [dnl
9568     file:write_file("conftest.out", code:lib_dir()),
9569     halt(0)])],
9570   [echo "code:lib_dir() returned: `cat conftest.out`"],
9571   [AC_MSG_FAILURE([test Erlang program execution failed])])
9572 @end example
9575 @node Systemology
9576 @section Systemology
9577 @cindex Systemology
9579 This section aims at presenting some systems and pointers to
9580 documentation.  It may help you addressing particular problems reported
9581 by users.
9583 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9584 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9585 operating system}.
9587 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9588 contains a table correlating the features of various Posix-conforming
9589 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9590 simplified diagram of how many Unix systems were derived from each
9591 other.
9593 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9594 provides some variants of traditional implementations of Unix utilities.
9596 @table @asis
9597 @item Darwin
9598 @cindex Darwin
9599 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9600 case-preserving, but case insensitive.  This can cause nasty problems,
9601 since for instance the installation attempt for a package having an
9602 @file{INSTALL} file can result in @samp{make install} report that
9603 nothing was to be done!
9605 That's all dependent on whether the file system is a UFS (case
9606 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9607 install the OS on HFS+.  Unfortunately, there are some pieces of
9608 software which really need to be built on UFS@.  We may want to rebuild
9609 Darwin to have both UFS and HFS+ available (and put the /local/build
9610 tree on the UFS).
9612 @item QNX 4.25
9613 @cindex QNX 4.25
9614 @c FIXME: Please, if you feel like writing something more precise,
9615 @c it'd be great.  In particular, I can't understand the difference with
9616 @c QNX Neutrino.
9617 QNX is a realtime operating system running on Intel architecture
9618 meant to be scalable from the small embedded systems to the hundred
9619 processor super-computer.  It claims to be Posix certified.  More
9620 information is available on the
9621 @uref{http://@/www.qnx.com/, QNX home page}.
9623 @item Tru64
9624 @cindex Tru64
9625 @uref{http://@/h30097.www3.hp.com/@/docs/,
9626 Documentation of several versions of Tru64} is available in different
9627 formats.
9629 @item Unix version 7
9630 @cindex Unix version 7
9631 @cindex V7
9632 Officially this was called the ``Seventh Edition'' of ``the UNIX
9633 time-sharing system'' but we use the more-common name ``Unix version 7''.
9634 Documentation is available in the
9635 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9636 Previous versions of Unix are called ``Unix version 6'', etc., but
9637 they were not as widely used.
9638 @end table
9641 @node Multiple Cases
9642 @section Multiple Cases
9644 Some operations are accomplished in several possible ways, depending on
9645 the OS variant.  Checking for them essentially requires a ``case
9646 statement''.  Autoconf does not directly provide one; however, it is
9647 easy to simulate by using a shell variable to keep track of whether a
9648 way to perform the operation has been found yet.
9650 Here is an example that uses the shell variable @code{fstype} to keep
9651 track of whether the remaining cases need to be checked.  Note that
9652 since the value of @code{fstype} is under our control, we don't have to
9653 use the longer @samp{test "x$fstype" = xno}.
9655 @example
9656 @group
9657 AC_MSG_CHECKING([how to get file system type])
9658 fstype=no
9659 # The order of these tests is important.
9660 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9661 #include <sys/fstyp.h>]])],
9662                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9663                      [Define if statvfs exists.])
9664                    fstype=SVR4])
9665 if test $fstype = no; then
9666   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9667 #include <sys/fstyp.h>]])],
9668                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9669                      [Define if USG statfs.])
9670                    fstype=SVR3])
9672 if test $fstype = no; then
9673   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9674 #include <sys/vmount.h>]])]),
9675                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9676                      [Define if AIX statfs.])
9677                    fstype=AIX])
9679 # (more cases omitted here)
9680 AC_MSG_RESULT([$fstype])
9681 @end group
9682 @end example
9684 @c ====================================================== Results of Tests.
9686 @node Results
9687 @chapter Results of Tests
9689 Once @command{configure} has determined whether a feature exists, what can
9690 it do to record that information?  There are four sorts of things it can
9691 do: define a C preprocessor symbol, set a variable in the output files,
9692 save the result in a cache file for future @command{configure} runs, and
9693 print a message letting the user know the result of the test.
9695 @menu
9696 * Defining Symbols::            Defining C preprocessor symbols
9697 * Setting Output Variables::    Replacing variables in output files
9698 * Special Chars in Variables::  Characters to beware of in variables
9699 * Caching Results::             Speeding up subsequent @command{configure} runs
9700 * Printing Messages::           Notifying @command{configure} users
9701 @end menu
9703 @node Defining Symbols
9704 @section Defining C Preprocessor Symbols
9706 A common action to take in response to a feature test is to define a C
9707 preprocessor symbol indicating the results of the test.  That is done by
9708 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9710 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9711 into the output variable @code{DEFS}, which contains an option
9712 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9713 Autoconf version 1, there is no variable @code{DEFS} defined while
9714 @command{configure} is running.  To check whether Autoconf macros have
9715 already defined a certain C preprocessor symbol, test the value of the
9716 appropriate cache variable, as in this example:
9718 @example
9719 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9720                           [Define if vprintf exists.])])
9721 if test "x$ac_cv_func_vprintf" != xyes; then
9722   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9723                             [Define if _doprnt exists.])])
9725 @end example
9727 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9728 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9729 correct values into @code{#define} statements in a template file.
9730 @xref{Configuration Headers}, for more information about this kind of
9731 output.
9733 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9734 @defmacx AC_DEFINE (@var{variable})
9735 @cvindex @var{variable}
9736 @acindex{DEFINE}
9737 Define @var{variable} to @var{value} (verbatim), by defining a C
9738 preprocessor macro for @var{variable}.  @var{variable} should be a C
9739 identifier, optionally suffixed by a parenthesized argument list to
9740 define a C preprocessor macro with arguments.  The macro argument list,
9741 if present, should be a comma-separated list of C identifiers, possibly
9742 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9743 @var{variable} should not contain comments, white space, trigraphs,
9744 backslash-newlines, universal character names, or non-ASCII
9745 characters.
9747 @var{value} may contain backslash-escaped newlines, which will be
9748 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9749 via @code{@@DEFS@@} (with no effect on the compilation, since the
9750 preprocessor sees only one line in the first place).  @var{value} should
9751 not contain raw newlines.  If you are not using
9752 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9753 characters, as @command{make} tends to eat them.  To use a shell
9754 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9756 @var{description} is only useful if you are using
9757 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9758 the generated @file{config.h.in} as the comment before the macro define.
9759 The following example defines the C preprocessor variable
9760 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9762 @example
9763 AC_DEFINE([EQUATION], ["$a > $b"],
9764   [Equation string.])
9765 @end example
9767 If neither @var{value} nor @var{description} are given, then
9768 @var{value} defaults to 1 instead of to the empty string.  This is for
9769 backwards compatibility with older versions of Autoconf, but this usage
9770 is obsolescent and may be withdrawn in future versions of Autoconf.
9772 If the @var{variable} is a literal string, it is passed to
9773 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9775 If multiple @code{AC_DEFINE} statements are executed for the same
9776 @var{variable} name (not counting any parenthesized argument list),
9777 the last one wins.
9778 @end defmac
9780 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9781 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9782 @acindex{DEFINE_UNQUOTED}
9783 @cvindex @var{variable}
9784 Like @code{AC_DEFINE}, but three shell expansions are
9785 performed---once---on @var{variable} and @var{value}: variable expansion
9786 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9787 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9788 characters in the value have no
9789 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9790 @var{variable} or @var{value} is a shell variable.  Examples:
9792 @example
9793 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9794   [Configuration machine file.])
9795 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9796   [getgroups return type.])
9797 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9798   [Translated header name.])
9799 @end example
9800 @end defmac
9802 Due to a syntactical bizarreness of the Bourne shell, do not use
9803 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9804 calls from other macro calls or shell code; that can cause syntax errors
9805 in the resulting @command{configure} script.  Use either blanks or
9806 newlines.  That is, do this:
9808 @example
9809 AC_CHECK_HEADER([elf.h],
9810   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9811 @end example
9813 @noindent
9814 or this:
9816 @example
9817 AC_CHECK_HEADER([elf.h],
9818   [AC_DEFINE([SVR4], [1], [System V Release 4])
9819    LIBS="-lelf $LIBS"])
9820 @end example
9822 @noindent
9823 instead of this:
9825 @example
9826 AC_CHECK_HEADER([elf.h],
9827   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9828 @end example
9830 @node Setting Output Variables
9831 @section Setting Output Variables
9832 @cindex Output variables
9834 Another way to record the results of tests is to set @dfn{output
9835 variables}, which are shell variables whose values are substituted into
9836 files that @command{configure} outputs.  The two macros below create new
9837 output variables.  @xref{Preset Output Variables}, for a list of output
9838 variables that are always available.
9840 @defmac AC_SUBST (@var{variable}, @ovar{value})
9841 @acindex{SUBST}
9842 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9843 substitute the variable @var{variable} into output files (typically one
9844 or more makefiles).  This means that @code{AC_OUTPUT}
9845 replaces instances of @samp{@@@var{variable}@@} in input files with the
9846 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9847 is called.  The value can contain any non-@code{NUL} character, including
9848 newline.  If you are using Automake 1.11 or newer, for newlines in values
9849 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9850 @command{automake} from adding a line @code{@var{variable} =
9851 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9852 Automake, automake, Other things Automake recognizes}).
9854 Variable occurrences should not overlap: e.g., an input file should
9855 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9856 are variable names.
9857 The substituted value is not rescanned for more output variables;
9858 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9859 literally into the output file.  (The algorithm uses the special marker
9860 @code{|#_!!_#|} internally, so neither the substituted value nor the
9861 output file may contain @code{|#_!!_#|}.)
9863 If @var{value} is given, in addition assign it to @var{variable}.
9865 The string @var{variable} is passed to @code{m4_pattern_allow}
9866 (@pxref{Forbidden Patterns}).
9867 @end defmac
9869 @defmac AC_SUBST_FILE (@var{variable})
9870 @acindex{SUBST_FILE}
9871 Another way to create an output variable from a shell variable.  Make
9872 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9873 named by shell variable @var{variable} into output files.  This means
9874 that @code{AC_OUTPUT} replaces instances of
9875 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9876 with the contents of the file that the shell variable @var{variable}
9877 names when @code{AC_OUTPUT} is called.  Set the variable to
9878 @file{/dev/null} for cases that do not have a file to insert.
9879 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9880 line by itself, optionally surrounded by spaces and tabs.  The
9881 substitution replaces the whole line, including the spaces, tabs, and
9882 the terminating newline.
9884 This macro is useful for inserting makefile fragments containing
9885 special dependencies or other @command{make} directives for particular host
9886 or target types into makefiles.  For example, @file{configure.ac}
9887 could contain:
9889 @example
9890 AC_SUBST_FILE([host_frag])
9891 host_frag=$srcdir/conf/sun4.mh
9892 @end example
9894 @noindent
9895 and then a @file{Makefile.in} could contain:
9897 @example
9898 @@host_frag@@
9899 @end example
9901 The string @var{variable} is passed to @code{m4_pattern_allow}
9902 (@pxref{Forbidden Patterns}).
9903 @end defmac
9905 @cindex Precious Variable
9906 @cindex Variable, Precious
9907 Running @command{configure} in varying environments can be extremely
9908 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9909 ./configure}, then the cache, @file{config.h}, and many other output
9910 files depend upon @command{bizarre-cc} being the C compiler.  If
9911 for some reason the user runs @command{./configure} again, or if it is
9912 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9913 and @pxref{config.status Invocation}), then the configuration can be
9914 inconsistent, composed of results depending upon two different
9915 compilers.
9917 Environment variables that affect this situation, such as @samp{CC}
9918 above, are called @dfn{precious variables}, and can be declared as such
9919 by @code{AC_ARG_VAR}.
9921 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9922 @acindex{ARG_VAR}
9923 Declare @var{variable} is a precious variable, and include its
9924 @var{description} in the variable section of @samp{./configure --help}.
9926 Being precious means that
9927 @itemize @minus
9928 @item
9929 @var{variable} is substituted via @code{AC_SUBST}.
9931 @item
9932 The value of @var{variable} when @command{configure} was launched is
9933 saved in the cache, including if it was not specified on the command
9934 line but via the environment.  Indeed, while @command{configure} can
9935 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9936 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9937 which, unfortunately, is what most users do.
9939 We emphasize that it is the @emph{initial} value of @var{variable} which
9940 is saved, not that found during the execution of @command{configure}.
9941 Indeed, specifying @samp{./configure FOO=foo} and letting
9942 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9943 different things.
9945 @item
9946 @var{variable} is checked for consistency between two
9947 @command{configure} runs.  For instance:
9949 @example
9950 $ @kbd{./configure --silent --config-cache}
9951 $ @kbd{CC=cc ./configure --silent --config-cache}
9952 configure: error: `CC' was not set in the previous run
9953 configure: error: changes in the environment can compromise \
9954 the build
9955 configure: error: run `make distclean' and/or \
9956 `rm config.cache' and start over
9957 @end example
9959 @noindent
9960 and similarly if the variable is unset, or if its content is changed.
9961 If the content has white space changes only, then the error is degraded
9962 to a warning only, but the old value is reused.
9964 @item
9965 @var{variable} is kept during automatic reconfiguration
9966 (@pxref{config.status Invocation}) as if it had been passed as a command
9967 line argument, including when no cache is used:
9969 @example
9970 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9971 $ @kbd{./config.status --recheck}
9972 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9973   CC=/usr/bin/cc  --no-create --no-recursion
9974 @end example
9975 @end itemize
9976 @end defmac
9978 @node Special Chars in Variables
9979 @section Special Characters in Output Variables
9980 @cindex Output variables, special characters in
9982 Many output variables are intended to be evaluated both by
9983 @command{make} and by the shell.  Some characters are expanded
9984 differently in these two contexts, so to avoid confusion these
9985 variables' values should not contain any of the following characters:
9987 @example
9988 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9989 @end example
9991 Also, these variables' values should neither contain newlines, nor start
9992 with @samp{~}, nor contain white space or @samp{:} immediately followed
9993 by @samp{~}.  The values can contain nonempty sequences of white space
9994 characters like tabs and spaces, but each such sequence might
9995 arbitrarily be replaced by a single space during substitution.
9997 These restrictions apply both to the values that @command{configure}
9998 computes, and to the values set directly by the user.  For example, the
9999 following invocations of @command{configure} are problematic, since they
10000 attempt to use special characters within @code{CPPFLAGS} and white space
10001 within @code{$(srcdir)}:
10003 @example
10004 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10006 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10007 @end example
10009 @node Caching Results
10010 @section Caching Results
10011 @cindex Cache
10013 To avoid checking for the same features repeatedly in various
10014 @command{configure} scripts (or in repeated runs of one script),
10015 @command{configure} can optionally save the results of many checks in a
10016 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10017 runs with caching enabled and finds a cache file, it reads the results
10018 of previous runs from the cache and avoids rerunning those checks.  As a
10019 result, @command{configure} can then run much faster than if it had to
10020 perform all of the checks every time.
10022 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10023 @acindex{CACHE_VAL}
10024 Ensure that the results of the check identified by @var{cache-id} are
10025 available.  If the results of the check were in the cache file that was
10026 read, and @command{configure} was not given the @option{--quiet} or
10027 @option{--silent} option, print a message saying that the result was
10028 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10029 the shell commands are run to determine the value, the value is
10030 saved in the cache file just before @command{configure} creates its output
10031 files.  @xref{Cache Variable Names}, for how to choose the name of the
10032 @var{cache-id} variable.
10034 The @var{commands-to-set-it} @emph{must have no side effects} except for
10035 setting the variable @var{cache-id}, see below.
10036 @end defmac
10038 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10039   @var{commands-to-set-it})
10040 @acindex{CACHE_CHECK}
10041 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10042 messages.  This macro provides a convenient shorthand for the most
10043 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10044 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10045 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10047 The @var{commands-to-set-it} @emph{must have no side effects} except for
10048 setting the variable @var{cache-id}, see below.
10049 @end defmac
10051 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10052 @code{AC_CACHE_CHECK}, because people are tempted to call
10053 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10054 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10055 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10056 instance, the following macro is broken:
10058 @example
10059 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10060 @group
10061 AC_DEFUN([AC_SHELL_TRUE],
10062 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10063                 [my_cv_shell_true_works=no
10064                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10065                  if test "x$my_cv_shell_true_works" = xyes; then
10066                    AC_DEFINE([TRUE_WORKS], [1],
10067                              [Define if `true(1)' works properly.])
10068                  fi])
10070 @end group
10071 @end example
10073 @noindent
10074 This fails if the cache is enabled: the second time this macro is run,
10075 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10078 @example
10079 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10080 @group
10081 AC_DEFUN([AC_SHELL_TRUE],
10082 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10083                 [my_cv_shell_true_works=no
10084                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10085  if test "x$my_cv_shell_true_works" = xyes; then
10086    AC_DEFINE([TRUE_WORKS], [1],
10087              [Define if `true(1)' works properly.])
10088  fi
10090 @end group
10091 @end example
10093 Also, @var{commands-to-set-it} should not print any messages, for
10094 example with @code{AC_MSG_CHECKING}; do that before calling
10095 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10096 the results of the check are retrieved from the cache or determined by
10097 running the shell commands.
10099 @menu
10100 * Cache Variable Names::        Shell variables used in caches
10101 * Cache Files::                 Files @command{configure} uses for caching
10102 * Cache Checkpointing::         Loading and saving the cache file
10103 @end menu
10105 @node Cache Variable Names
10106 @subsection Cache Variable Names
10107 @cindex Cache variable
10109 The names of cache variables should have the following format:
10111 @example
10112 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10113 @end example
10115 @noindent
10116 for example, @samp{ac_cv_header_stat_broken} or
10117 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10119 @table @asis
10120 @item @var{package-prefix}
10121 An abbreviation for your package or organization; the same prefix you
10122 begin local Autoconf macros with, except lowercase by convention.
10123 For cache values used by the distributed Autoconf macros, this value is
10124 @samp{ac}.
10126 @item @code{_cv_}
10127 Indicates that this shell variable is a cache value.  This string
10128 @emph{must} be present in the variable name, including the leading
10129 underscore.
10131 @item @var{value-type}
10132 A convention for classifying cache values, to produce a rational naming
10133 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10135 @item @var{specific-value}
10136 Which member of the class of cache values this test applies to.
10137 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10138 output variable (@samp{INSTALL}).
10140 @item @var{additional-options}
10141 Any particular behavior of the specific member that this test applies to.
10142 For example, @samp{broken} or @samp{set}.  This part of the name may
10143 be omitted if it does not apply.
10144 @end table
10146 The values assigned to cache variables may not contain newlines.
10147 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10148 names of files or functions; so this is not an important restriction.
10149 @ref{Cache Variable Index} for an index of cache variables with
10150 documented semantics.
10153 @node Cache Files
10154 @subsection Cache Files
10156 A cache file is a shell script that caches the results of configure
10157 tests run on one system so they can be shared between configure scripts
10158 and configure runs.  It is not useful on other systems.  If its contents
10159 are invalid for some reason, the user may delete or edit it, or override
10160 documented cache variables on the @command{configure} command line.
10162 By default, @command{configure} uses no cache file,
10163 to avoid problems caused by accidental
10164 use of stale cache files.
10166 To enable caching, @command{configure} accepts @option{--config-cache} (or
10167 @option{-C}) to cache results in the file @file{config.cache}.
10168 Alternatively, @option{--cache-file=@var{file}} specifies that
10169 @var{file} be the cache file.  The cache file is created if it does not
10170 exist already.  When @command{configure} calls @command{configure} scripts in
10171 subdirectories, it uses the @option{--cache-file} argument so that they
10172 share the same cache.  @xref{Subdirectories}, for information on
10173 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10175 @file{config.status} only pays attention to the cache file if it is
10176 given the @option{--recheck} option, which makes it rerun
10177 @command{configure}.
10179 It is wrong to try to distribute cache files for particular system types.
10180 There is too much room for error in doing that, and too much
10181 administrative overhead in maintaining them.  For any features that
10182 can't be guessed automatically, use the standard method of the canonical
10183 system type and linking files (@pxref{Manual Configuration}).
10185 The site initialization script can specify a site-wide cache file to
10186 use, instead of the usual per-program cache.  In this case, the cache
10187 file gradually accumulates information whenever someone runs a new
10188 @command{configure} script.  (Running @command{configure} merges the new cache
10189 results with the existing cache file.)  This may cause problems,
10190 however, if the system configuration (e.g., the installed libraries or
10191 compilers) changes and the stale cache file is not deleted.
10193 If @command{configure} is interrupted at the right time when it updates
10194 a cache file outside of the build directory where the @command{configure}
10195 script is run, it may leave behind a temporary file named after the
10196 cache file with digits following it.  You may safely delete such a file.
10199 @node Cache Checkpointing
10200 @subsection Cache Checkpointing
10202 If your configure script, or a macro called from @file{configure.ac}, happens
10203 to abort the configure process, it may be useful to checkpoint the cache
10204 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10205 reduces the amount of time it takes to rerun the configure script with
10206 (hopefully) the error that caused the previous abort corrected.
10208 @c FIXME: Do we really want to document this guy?
10209 @defmac AC_CACHE_LOAD
10210 @acindex{CACHE_LOAD}
10211 Loads values from existing cache file, or creates a new cache file if a
10212 cache file is not found.  Called automatically from @code{AC_INIT}.
10213 @end defmac
10215 @defmac AC_CACHE_SAVE
10216 @acindex{CACHE_SAVE}
10217 Flushes all cached values to the cache file.  Called automatically from
10218 @code{AC_OUTPUT}, but it can be quite useful to call
10219 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10220 @end defmac
10222 For instance:
10224 @example
10225 @r{ @dots{} AC_INIT, etc. @dots{}}
10226 @group
10227 # Checks for programs.
10228 AC_PROG_CC
10229 AC_PROG_AWK
10230 @r{ @dots{} more program checks @dots{}}
10231 AC_CACHE_SAVE
10232 @end group
10234 @group
10235 # Checks for libraries.
10236 AC_CHECK_LIB([nsl], [gethostbyname])
10237 AC_CHECK_LIB([socket], [connect])
10238 @r{ @dots{} more lib checks @dots{}}
10239 AC_CACHE_SAVE
10240 @end group
10242 @group
10243 # Might abort@dots{}
10244 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10245 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10246 @end group
10247 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10248 @end example
10250 @node Printing Messages
10251 @section Printing Messages
10252 @cindex Messages, from @command{configure}
10254 @command{configure} scripts need to give users running them several kinds
10255 of information.  The following macros print messages in ways appropriate
10256 for each kind.  The arguments to all of them get enclosed in shell
10257 double quotes, so the shell performs variable and back-quote
10258 substitution on them.
10260 These macros are all wrappers around the @command{echo} shell command.
10261 They direct output to the appropriate file descriptor (@pxref{File
10262 Descriptor Macros}).
10263 @command{configure} scripts should rarely need to run @command{echo} directly
10264 to print messages for the user.  Using these macros makes it easy to
10265 change how and when each kind of message is printed; such changes need
10266 only be made to the macro definitions and all the callers change
10267 automatically.
10269 To diagnose static issues, i.e., when @command{autoconf} is run, see
10270 @ref{Diagnostic Macros}.
10272 @defmac AC_MSG_CHECKING (@var{feature-description})
10273 @acindex{MSG_CHECKING}
10274 Notify the user that @command{configure} is checking for a particular
10275 feature.  This macro prints a message that starts with @samp{checking }
10276 and ends with @samp{...} and no newline.  It must be followed by a call
10277 to @code{AC_MSG_RESULT} to print the result of the check and the
10278 newline.  The @var{feature-description} should be something like
10279 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10280 c89}.
10282 This macro prints nothing if @command{configure} is run with the
10283 @option{--quiet} or @option{--silent} option.
10284 @end defmac
10286 @anchor{AC_MSG_RESULT}
10287 @defmac AC_MSG_RESULT (@var{result-description})
10288 @acindex{MSG_RESULT}
10289 Notify the user of the results of a check.  @var{result-description} is
10290 almost always the value of the cache variable for the check, typically
10291 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10292 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10293 the completion of the message printed by the call to
10294 @code{AC_MSG_CHECKING}.
10296 This macro prints nothing if @command{configure} is run with the
10297 @option{--quiet} or @option{--silent} option.
10298 @end defmac
10300 @anchor{AC_MSG_NOTICE}
10301 @defmac AC_MSG_NOTICE (@var{message})
10302 @acindex{MSG_NOTICE}
10303 Deliver the @var{message} to the user.  It is useful mainly to print a
10304 general description of the overall purpose of a group of feature checks,
10305 e.g.,
10307 @example
10308 AC_MSG_NOTICE([checking if stack overflow is detectable])
10309 @end example
10311 This macro prints nothing if @command{configure} is run with the
10312 @option{--quiet} or @option{--silent} option.
10313 @end defmac
10315 @anchor{AC_MSG_ERROR}
10316 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10317 @acindex{MSG_ERROR}
10318 Notify the user of an error that prevents @command{configure} from
10319 completing.  This macro prints an error message to the standard error
10320 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10321 by default, except that @samp{0} is converted to @samp{1}).
10322 @var{error-description} should be something like @samp{invalid value
10323 $HOME for \$HOME}.
10325 The @var{error-description} should start with a lower-case letter, and
10326 ``cannot'' is preferred to ``can't''.
10327 @end defmac
10329 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10330 @acindex{MSG_FAILURE}
10331 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10332 prevents @command{configure} from completing @emph{and} that additional
10333 details are provided in @file{config.log}.  This is typically used when
10334 abnormal results are found during a compilation.
10335 @end defmac
10337 @anchor{AC_MSG_WARN}
10338 @defmac AC_MSG_WARN (@var{problem-description})
10339 @acindex{MSG_WARN}
10340 Notify the @command{configure} user of a possible problem.  This macro
10341 prints the message to the standard error output; @command{configure}
10342 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10343 provide a default (back-up) behavior for the situations they warn about.
10344 @var{problem-description} should be something like @samp{ln -s seems to
10345 make hard links}.
10346 @end defmac
10350 @c ====================================================== Programming in M4.
10352 @node Programming in M4
10353 @chapter Programming in M4
10354 @cindex M4
10356 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10357 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10358 provides macros dedicated to shell script generation.
10360 As of this version of Autoconf, these two layers still contain
10361 experimental macros, whose interface might change in the future.  As a
10362 matter of fact, @emph{anything that is not documented must not be used}.
10364 @menu
10365 * M4 Quotation::                Protecting macros from unwanted expansion
10366 * Using autom4te::              The Autoconf executables backbone
10367 * Programming in M4sugar::      Convenient pure M4 macros
10368 * Debugging via autom4te::      Figuring out what M4 was doing
10369 @end menu
10371 @node M4 Quotation
10372 @section M4 Quotation
10373 @cindex M4 quotation
10374 @cindex quotation
10376 The most common problem with existing macros is an improper quotation.
10377 This section, which users of Autoconf can skip, but which macro writers
10378 @emph{must} read, first justifies the quotation scheme that was chosen
10379 for Autoconf and then ends with a rule of thumb.  Understanding the
10380 former helps one to follow the latter.
10382 @menu
10383 * Active Characters::           Characters that change the behavior of M4
10384 * One Macro Call::              Quotation and one macro call
10385 * Quoting and Parameters::      M4 vs. shell parameters
10386 * Quotation and Nested Macros::  Macros calling macros
10387 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10388 * Quadrigraphs::                Another way to escape special characters
10389 * Balancing Parentheses::       Dealing with unbalanced parentheses
10390 * Quotation Rule Of Thumb::     One parenthesis, one quote
10391 @end menu
10393 @node Active Characters
10394 @subsection Active Characters
10396 To fully understand where proper quotation is important, you first need
10397 to know what the special characters are in Autoconf: @samp{#} introduces
10398 a comment inside which no macro expansion is performed, @samp{,}
10399 separates arguments, @samp{[} and @samp{]} are the quotes
10400 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10401 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10402 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10403 @samp{$} inside a macro definition.
10405 In order to understand the delicate case of macro calls, we first have
10406 to present some obvious failures.  Below they are ``obvious-ified'',
10407 but when you find them in real life, they are usually in disguise.
10409 Comments, introduced by a hash and running up to the newline, are opaque
10410 tokens to the top level: active characters are turned off, and there is
10411 no macro expansion:
10413 @example
10414 # define([def], ine)
10415 @result{}# define([def], ine)
10416 @end example
10418 Each time there can be a macro expansion, there is a quotation
10419 expansion, i.e., one level of quotes is stripped:
10421 @example
10422 int tab[10];
10423 @result{}int tab10;
10424 [int tab[10];]
10425 @result{}int tab[10];
10426 @end example
10428 Without this in mind, the reader might try hopelessly to use her macro
10429 @code{array}:
10431 @example
10432 define([array], [int tab[10];])
10433 array
10434 @result{}int tab10;
10435 [array]
10436 @result{}array
10437 @end example
10439 @noindent
10440 How can you correctly output the intended results@footnote{Using
10441 @code{defn}.}?
10444 @node One Macro Call
10445 @subsection One Macro Call
10447 Let's proceed on the interaction between active characters and macros
10448 with this small macro, which just returns its first argument:
10450 @example
10451 define([car], [$1])
10452 @end example
10454 @noindent
10455 The two pairs of quotes above are not part of the arguments of
10456 @code{define}; rather, they are understood by the top level when it
10457 tries to find the arguments of @code{define}.  Therefore, assuming
10458 @code{car} is not already defined, it is equivalent to write:
10460 @example
10461 define(car, $1)
10462 @end example
10464 @noindent
10465 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10466 quotes, it is bad practice for Autoconf macros which must both be more
10467 robust and also advocate perfect style.
10469 At the top level, there are only two possibilities: either you
10470 quote or you don't:
10472 @example
10473 car(foo, bar, baz)
10474 @result{}foo
10475 [car(foo, bar, baz)]
10476 @result{}car(foo, bar, baz)
10477 @end example
10479 Let's pay attention to the special characters:
10481 @example
10482 car(#)
10483 @error{}EOF in argument list
10484 @end example
10486 The closing parenthesis is hidden in the comment; with a hypothetical
10487 quoting, the top level understood it this way:
10489 @example
10490 car([#)]
10491 @end example
10493 @noindent
10494 Proper quotation, of course, fixes the problem:
10496 @example
10497 car([#])
10498 @result{}#
10499 @end example
10501 Here are more examples:
10503 @example
10504 car(foo, bar)
10505 @result{}foo
10506 car([foo, bar])
10507 @result{}foo, bar
10508 car((foo, bar))
10509 @result{}(foo, bar)
10510 car([(foo], [bar)])
10511 @result{}(foo
10512 define([a], [b])
10513 @result{}
10514 car(a)
10515 @result{}b
10516 car([a])
10517 @result{}b
10518 car([[a]])
10519 @result{}a
10520 car([[[a]]])
10521 @result{}[a]
10522 @end example
10524 @node Quoting and Parameters
10525 @subsection Quoting and Parameters
10527 When M4 encounters @samp{$} within a macro definition, followed
10528 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10529 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10530 expansion.  This happens regardless of how many layers of quotes the
10531 parameter expansion is nested within, or even if it occurs in text that
10532 will be rescanned as a comment.
10534 @example
10535 define([none], [$1])
10536 @result{}
10537 define([one], [[$1]])
10538 @result{}
10539 define([two], [[[$1]]])
10540 @result{}
10541 define([comment], [# $1])
10542 @result{}
10543 define([active], [ACTIVE])
10544 @result{}
10545 none([active])
10546 @result{}ACTIVE
10547 one([active])
10548 @result{}active
10549 two([active])
10550 @result{}[active]
10551 comment([active])
10552 @result{}# active
10553 @end example
10555 On the other hand, since autoconf generates shell code, you often want
10556 to output shell variable expansion, rather than performing M4 parameter
10557 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10558 from the next character in the definition of your macro.  If the macro
10559 definition occurs in single-quoted text, then insert another level of
10560 quoting; if the usage is already inside a double-quoted string, then
10561 split it into concatenated strings.
10563 @example
10564 define([single], [a single-quoted $[]1 definition])
10565 @result{}
10566 define([double], [[a double-quoted $][1 definition]])
10567 @result{}
10568 single
10569 @result{}a single-quoted $1 definition
10570 double
10571 @result{}a double-quoted $1 definition
10572 @end example
10574 Posix states that M4 implementations are free to provide implementation
10575 extensions when @samp{$@{} is encountered in a macro definition.
10576 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10577 extensions that will be available in the future GNU M4 2.0,
10578 but guarantees that all other instances of @samp{$@{} will be output
10579 literally.  Therefore, this idiom can also be used to output shell code
10580 parameter references:
10582 @example
10583 define([first], [$@{1@}])first
10584 @result{}$@{1@}
10585 @end example
10587 Posix also states that @samp{$11} should expand to the first parameter
10588 concatenated with a literal @samp{1}, although some versions of
10589 GNU M4 expand the eleventh parameter instead.  For
10590 portability, you should only use single-digit M4 parameter expansion.
10592 With this in mind, we can explore the cases where macros invoke
10593 macros@enddots{}
10595 @node Quotation and Nested Macros
10596 @subsection Quotation and Nested Macros
10598 The examples below use the following macros:
10600 @example
10601 define([car], [$1])
10602 define([active], [ACT, IVE])
10603 define([array], [int tab[10]])
10604 @end example
10606 Each additional embedded macro call introduces other possible
10607 interesting quotations:
10609 @example
10610 car(active)
10611 @result{}ACT
10612 car([active])
10613 @result{}ACT, IVE
10614 car([[active]])
10615 @result{}active
10616 @end example
10618 In the first case, the top level looks for the arguments of @code{car},
10619 and finds @samp{active}.  Because M4 evaluates its arguments
10620 before applying the macro, @samp{active} is expanded, which results in:
10622 @example
10623 car(ACT, IVE)
10624 @result{}ACT
10625 @end example
10627 @noindent
10628 In the second case, the top level gives @samp{active} as first and only
10629 argument of @code{car}, which results in:
10631 @example
10632 active
10633 @result{}ACT, IVE
10634 @end example
10636 @noindent
10637 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10638 In the third case, @code{car} receives @samp{[active]}, which results in:
10640 @example
10641 [active]
10642 @result{}active
10643 @end example
10645 @noindent
10646 exactly as we already saw above.
10648 The example above, applied to a more realistic example, gives:
10650 @example
10651 car(int tab[10];)
10652 @result{}int tab10;
10653 car([int tab[10];])
10654 @result{}int tab10;
10655 car([[int tab[10];]])
10656 @result{}int tab[10];
10657 @end example
10659 @noindent
10660 Huh?  The first case is easily understood, but why is the second wrong,
10661 and the third right?  To understand that, you must know that after
10662 M4 expands a macro, the resulting text is immediately subjected
10663 to macro expansion and quote removal.  This means that the quote removal
10664 occurs twice---first before the argument is passed to the @code{car}
10665 macro, and second after the @code{car} macro expands to the first
10666 argument.
10668 As the author of the Autoconf macro @code{car}, you then consider it to
10669 be incorrect that your users have to double-quote the arguments of
10670 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10671 quoted car:
10673 @example
10674 define([qar], [[$1]])
10675 @end example
10677 @noindent
10678 and check that @code{qar} is properly fixed:
10680 @example
10681 qar([int tab[10];])
10682 @result{}int tab[10];
10683 @end example
10685 @noindent
10686 Ahhh!  That's much better.
10688 But note what you've done: now that the result of @code{qar} is always
10689 a literal string, the only time a user can use nested macros is if she
10690 relies on an @emph{unquoted} macro call:
10692 @example
10693 qar(active)
10694 @result{}ACT
10695 qar([active])
10696 @result{}active
10697 @end example
10699 @noindent
10700 leaving no way for her to reproduce what she used to do with @code{car}:
10702 @example
10703 car([active])
10704 @result{}ACT, IVE
10705 @end example
10707 @noindent
10708 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10709 macros:
10711 @example
10712 define([my_includes], [#include <stdio.h>])
10713 car([my_includes])
10714 @result{}#include <stdio.h>
10715 qar(my_includes)
10716 @error{}EOF in argument list
10717 @end example
10719 This macro, @code{qar}, because it double quotes its arguments, forces
10720 its users to leave their macro calls unquoted, which is dangerous.
10721 Commas and other active symbols are interpreted by M4 before
10722 they are given to the macro, often not in the way the users expect.
10723 Also, because @code{qar} behaves differently from the other macros,
10724 it's an exception that should be avoided in Autoconf.
10726 @node Changequote is Evil
10727 @subsection @code{changequote} is Evil
10728 @cindex @code{changequote}
10730 The temptation is often high to bypass proper quotation, in particular
10731 when it's late at night.  Then, many experienced Autoconf hackers
10732 finally surrender to the dark side of the force and use the ultimate
10733 weapon: @code{changequote}.
10735 The M4 builtin @code{changequote} belongs to a set of primitives that
10736 allow one to adjust the syntax of the language to adjust it to one's
10737 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10738 quotes, but in the context of shell programming (and actually of most
10739 programming languages), that's about the worst choice one can make:
10740 because of strings and back-quoted expressions in shell code (such as
10741 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10742 programming languages (as in @samp{'0'}), there are many unbalanced
10743 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10744 not impossible.  In order to make M4 useful in such a context, its
10745 designers have equipped it with @code{changequote}, which makes it
10746 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10747 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10748 because they are unlikely characters, but @emph{because they are
10749 characters unlikely to be unbalanced}.
10751 There are other magic primitives, such as @code{changecom} to specify
10752 what syntactic forms are comments (it is common to see
10753 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10754 @code{changeword} and @code{changesyntax} to change other syntactic
10755 details (such as the character to denote the @var{n}th argument, @samp{$} by
10756 default, the parentheses around arguments, etc.).
10758 These primitives are really meant to make M4 more useful for specific
10759 domains: they should be considered like command line options:
10760 @option{--quotes}, @option{--comments}, @option{--words}, and
10761 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10762 it makes M4 libraries self contained (no need for additional options).
10764 There lies the problem@enddots{}
10766 @sp 1
10768 The problem is that it is then tempting to use them in the middle of an
10769 M4 script, as opposed to its initialization.  This, if not carefully
10770 thought out, can lead to disastrous effects: @emph{you are changing the
10771 language in the middle of the execution}.  Changing and restoring the
10772 syntax is often not enough: if you happened to invoke macros in between,
10773 these macros are lost, as the current syntax is probably not
10774 the one they were implemented with.
10776 @c FIXME: I've been looking for a short, real case example, but I
10777 @c lost them all :(
10780 @node Quadrigraphs
10781 @subsection Quadrigraphs
10782 @cindex quadrigraphs
10783 @cindex @samp{@@S|@@}
10784 @cindex @samp{@@&t@@}
10785 @c Info cannot handle `:' in index entries.
10786 @ifnotinfo
10787 @cindex @samp{@@<:@@}
10788 @cindex @samp{@@:>@@}
10789 @cindex @samp{@@%:@@}
10790 @cindex @samp{@@@{:@@}
10791 @cindex @samp{@@:@}@@}
10792 @end ifnotinfo
10794 When writing an Autoconf macro you may occasionally need to generate
10795 special characters that are difficult to express with the standard
10796 Autoconf quoting rules.  For example, you may need to output the regular
10797 expression @samp{[^[]}, which matches any character other than @samp{[}.
10798 This expression contains unbalanced brackets so it cannot be put easily
10799 into an M4 macro.
10801 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10802 and @code{m4_expand}) which internally use special markers in addition
10803 to the regular quoting characters.  If the arguments to these macros
10804 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10805 might behave incorrectly.
10807 You can work around these problems by using one of the following
10808 @dfn{quadrigraphs}:
10810 @table @samp
10811 @item @@<:@@
10812 @samp{[}
10813 @item @@:>@@
10814 @samp{]}
10815 @item @@S|@@
10816 @samp{$}
10817 @item @@%:@@
10818 @samp{#}
10819 @item @@@{:@@
10820 @samp{(}
10821 @item @@:@}@@
10822 @samp{)}
10823 @item @@&t@@
10824 Expands to nothing.
10825 @end table
10827 Quadrigraphs are replaced at a late stage of the translation process,
10828 after @command{m4} is run, so they do not get in the way of M4 quoting.
10829 For example, the string @samp{^@@<:@@}, independently of its quotation,
10830 appears as @samp{^[} in the output.
10832 The empty quadrigraph can be used:
10834 @itemize @minus
10835 @item to mark trailing spaces explicitly
10837 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10839 @item to produce quadrigraphs and other strings reserved by m4sugar
10841 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10842 contrived example:
10844 @example
10845 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10846 m4_split([a )@}>=- b -=<@{( c])
10847 @result{}[a], [], [B], [], [c]
10848 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10849 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10850 @end example
10852 @item to escape @emph{occurrences} of forbidden patterns
10854 For instance you might want to mention @code{AC_FOO} in a comment, while
10855 still being sure that @command{autom4te} still catches unexpanded
10856 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10857 @end itemize
10859 The name @samp{@@&t@@} was suggested by Paul Eggert:
10861 @quotation
10862 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10863 own invention, but the @samp{t} came from the source code of the
10864 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10865 and which used @samp{mt} to denote the empty string.  In C, it would
10866 have looked like something like:
10868 @example
10869 char const mt[] = "";
10870 @end example
10872 @noindent
10873 but of course the source code was written in Algol 68.
10875 I don't know where he got @samp{mt} from: it could have been his own
10876 invention, and I suppose it could have been a common pun around the
10877 Cambridge University computer lab at the time.
10878 @end quotation
10881 @node Balancing Parentheses
10882 @subsection Dealing with unbalanced parentheses
10883 @cindex balancing parentheses
10884 @cindex parentheses, balancing
10885 @cindex unbalanced parentheses, managing
10887 One of the pitfalls of portable shell programming is that @command{case}
10888 statements require unbalanced parentheses (@pxref{case, , Limitations of
10889 Shell Builtins}).  With syntax highlighting
10890 editors, the presence of unbalanced @samp{)} can interfere with editors
10891 that perform syntax highlighting of macro contents based on finding the
10892 matching @samp{(}.  Another concern is how much editing must be done
10893 when transferring code snippets between shell scripts and macro
10894 definitions.  But most importantly, the presence of unbalanced
10895 parentheses can introduce expansion bugs.
10897 For an example, here is an underquoted attempt to use the macro
10898 @code{my_case}, which happens to expand to a portable @command{case}
10899 statement:
10901 @example
10902 AC_DEFUN([my_case],
10903 [case $file_name in
10904   *.c) echo "C source code";;
10905 esac])
10906 AS_IF(:, my_case)
10907 @end example
10909 @noindent
10910 In the above example, the @code{AS_IF} call underquotes its arguments.
10911 As a result, the unbalanced @samp{)} generated by the premature
10912 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10913 truncated parameter, and the expansion is syntactically invalid:
10915 @example
10916 if :; then
10917   case $file_name in
10918   *.c
10919 fi echo "C source code";;
10920 esac)
10921 @end example
10923 If nothing else, this should emphasize the importance of the quoting
10924 arguments to macro calls.  On the other hand, there are several
10925 variations for defining @code{my_case} to be more robust, even when used
10926 without proper quoting, each with some benefits and some drawbacks.
10928 @itemize @w{}
10929 @item Creative literal shell comment
10930 @example
10931 AC_DEFUN([my_case],
10932 [case $file_name in #(
10933   *.c) echo "C source code";;
10934 esac])
10935 @end example
10936 @noindent
10937 This version provides balanced parentheses to several editors, and can
10938 be copied and pasted into a terminal as is.  Unfortunately, it is still
10939 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10940 that masks the normal properties of @samp{(}.
10942 @item Quadrigraph shell comment
10943 @example
10944 AC_DEFUN([my_case],
10945 [case $file_name in @@%:@@(
10946   *.c) echo "C source code";;
10947 esac])
10948 @end example
10949 @noindent
10950 This version provides balanced parentheses to even more editors, and can
10951 be used as a balanced Autoconf argument.  Unfortunately, it requires
10952 some editing before it can be copied and pasted into a terminal, and the
10953 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10955 @item Quoting just the parenthesis
10956 @example
10957 AC_DEFUN([my_case],
10958 [case $file_name in
10959   *.c[)] echo "C source code";;
10960 esac])
10961 @end example
10962 @noindent
10963 This version quotes the @samp{)}, so that it can be used as a balanced
10964 Autoconf argument.  As written, this is not balanced to an editor, but
10965 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10966 still requires some edits before it can be copied and pasted into a
10967 terminal.
10969 @item Double-quoting the entire statement
10970 @example
10971 AC_DEFUN([my_case],
10972 [[case $file_name in #(
10973   *.c) echo "C source code";;
10974 esac]])
10975 @end example
10976 @noindent
10977 Since the entire macro is double-quoted, there is no problem with using
10978 this as an Autoconf argument; and since the double-quoting is over the
10979 entire statement, this code can be easily copied and pasted into a
10980 terminal.  However, the double quoting prevents the expansion of any
10981 macros inside the case statement, which may cause its own set of
10982 problems.
10984 @item Using @code{AS_CASE}
10985 @example
10986 AC_DEFUN([my_case],
10987 [AS_CASE([$file_name],
10988   [*.c], [echo "C source code"])])
10989 @end example
10990 @noindent
10991 This version avoids the balancing issue altogether, by relying on
10992 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10993 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10994 statement, rather than within a branch of the case statement that might
10995 not be taken.  However, the abstraction comes with a penalty that it is
10996 no longer a quick copy, paste, and edit to get back to shell code.
10997 @end itemize
11000 @node Quotation Rule Of Thumb
11001 @subsection Quotation Rule Of Thumb
11003 To conclude, the quotation rule of thumb is:
11005 @center @emph{One pair of quotes per pair of parentheses.}
11007 Never over-quote, never under-quote, in particular in the definition of
11008 macros.  In the few places where the macros need to use brackets
11009 (usually in C program text or regular expressions), properly quote
11010 @emph{the arguments}!
11012 It is common to read Autoconf programs with snippets like:
11014 @example
11015 AC_TRY_LINK(
11016 changequote(<<, >>)dnl
11017 <<#include <time.h>
11018 #ifndef tzname /* For SGI.  */
11019 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11020 #endif>>,
11021 changequote([, ])dnl
11022 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11023 @end example
11025 @noindent
11026 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11027 double quoting, so you just need:
11029 @example
11030 AC_TRY_LINK(
11031 [#include <time.h>
11032 #ifndef tzname /* For SGI.  */
11033 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11034 #endif],
11035             [atoi (*tzname);],
11036             [ac_cv_var_tzname=yes],
11037             [ac_cv_var_tzname=no])
11038 @end example
11040 @noindent
11041 The M4-fluent reader might note that these two examples are rigorously
11042 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11043 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11044 quotes are not part of the arguments!
11046 Simplified, the example above is just doing this:
11048 @example
11049 changequote(<<, >>)dnl
11050 <<[]>>
11051 changequote([, ])dnl
11052 @end example
11054 @noindent
11055 instead of simply:
11057 @example
11058 [[]]
11059 @end example
11061 With macros that do not double quote their arguments (which is the
11062 rule), double-quote the (risky) literals:
11064 @example
11065 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11066 [[#include <time.h>
11067 #ifndef tzname /* For SGI.  */
11068 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11069 #endif]],
11070                                 [atoi (*tzname);])],
11071                [ac_cv_var_tzname=yes],
11072                [ac_cv_var_tzname=no])
11073 @end example
11075 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11076 should be using @code{AC_LINK_IFELSE} instead.
11078 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11079 where quoting does not suffice.
11081 When you create a @command{configure} script using newly written macros,
11082 examine it carefully to check whether you need to add more quotes in
11083 your macros.  If one or more words have disappeared in the M4
11084 output, you need more quotes.  When in doubt, quote.
11086 However, it's also possible to put on too many layers of quotes.  If
11087 this happens, the resulting @command{configure} script may contain
11088 unexpanded macros.  The @command{autoconf} program checks for this problem
11089 by looking for the string @samp{AC_} in @file{configure}.  However, this
11090 heuristic does not work in general: for example, it does not catch
11091 overquoting in @code{AC_DEFINE} descriptions.
11094 @c ---------------------------------------- Using autom4te
11096 @node Using autom4te
11097 @section Using @command{autom4te}
11099 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11100 to Autoconf per se, heavily rely on M4.  All these different uses
11101 revealed common needs factored into a layer over M4:
11102 @command{autom4te}@footnote{
11104 Yet another great name from Lars J. Aas.
11108 @command{autom4te} is a preprocessor that is like @command{m4}.
11109 It supports M4 extensions designed for use in tools like Autoconf.
11111 @menu
11112 * autom4te Invocation::         A GNU M4 wrapper
11113 * Customizing autom4te::        Customizing the Autoconf package
11114 @end menu
11116 @node autom4te Invocation
11117 @subsection Invoking @command{autom4te}
11119 The command line arguments are modeled after M4's:
11121 @example
11122 autom4te @var{options} @var{files}
11123 @end example
11125 @noindent
11126 @evindex M4
11127 where the @var{files} are directly passed to @command{m4}.  By default,
11128 GNU M4 is found during configuration, but the environment
11129 variable
11130 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11131 to the regular expansion, it handles the replacement of the quadrigraphs
11132 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11133 output.  It supports an extended syntax for the @var{files}:
11135 @table @file
11136 @item @var{file}.m4f
11137 This file is an M4 frozen file.  Note that @emph{all the previous files
11138 are ignored}.  See the option @option{--melt} for the rationale.
11140 @item @var{file}?
11141 If found in the library path, the @var{file} is included for expansion,
11142 otherwise it is ignored instead of triggering a failure.
11143 @end table
11145 @sp 1
11147 Of course, it supports the Autoconf common subset of options:
11149 @table @option
11150 @item --help
11151 @itemx -h
11152 Print a summary of the command line options and exit.
11154 @item --version
11155 @itemx -V
11156 Print the version number of Autoconf and exit.
11158 @item --verbose
11159 @itemx -v
11160 Report processing steps.
11162 @item --debug
11163 @itemx -d
11164 Don't remove the temporary files and be even more verbose.
11166 @item --include=@var{dir}
11167 @itemx -I @var{dir}
11168 Also look for input files in @var{dir}.  Multiple invocations
11169 accumulate.
11171 @item --output=@var{file}
11172 @itemx -o @var{file}
11173 Save output (script or trace) to @var{file}.  The file @option{-} stands
11174 for the standard output.
11175 @end table
11177 @sp 1
11179 As an extension of @command{m4}, it includes the following options:
11181 @table @option
11182 @item --warnings=@var{category}
11183 @itemx -W @var{category}
11184 @evindex WARNINGS
11185 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11186 Report the warnings related to @var{category} (which can actually be a
11187 comma separated list).  @xref{Reporting Messages}, macro
11188 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11189 values include:
11191 @table @samp
11192 @item all
11193 report all the warnings
11195 @item none
11196 report none
11198 @item error
11199 treats warnings as errors
11201 @item no-@var{category}
11202 disable warnings falling into @var{category}
11203 @end table
11205 Warnings about @samp{syntax} are enabled by default, and the environment
11206 variable @env{WARNINGS}, a comma separated list of categories, is
11207 honored.  @samp{autom4te -W @var{category}} actually
11208 behaves as if you had run:
11210 @example
11211 autom4te --warnings=syntax,$WARNINGS,@var{category}
11212 @end example
11214 @noindent
11215 For example, if you want to disable defaults and @env{WARNINGS}
11216 of @command{autom4te}, but enable the warnings about obsolete
11217 constructs, you would use @option{-W none,obsolete}.
11219 @cindex Back trace
11220 @cindex Macro invocation stack
11221 @command{autom4te} displays a back trace for errors, but not for
11222 warnings; if you want them, just pass @option{-W error}.
11224 @item --melt
11225 @itemx -M
11226 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11227 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11228 are executed only when the files are frozen, typically
11229 @code{m4_define}.  For instance, running:
11231 @example
11232 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11233 @end example
11235 @noindent
11236 is roughly equivalent to running:
11238 @example
11239 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11240 @end example
11242 @noindent
11243 while
11245 @example
11246 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11247 @end example
11249 @noindent
11250 is equivalent to:
11252 @example
11253 m4 --reload-state=4.m4f input.m4
11254 @end example
11256 @item --freeze
11257 @itemx -F
11258 Produce a frozen state file.  @command{autom4te} freezing is stricter
11259 than M4's: it must produce no warnings, and no output other than empty
11260 lines (a line with white space is @emph{not} empty) and comments
11261 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11262 this option takes no argument:
11264 @example
11265 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11266 @end example
11268 @noindent
11269 corresponds to
11271 @example
11272 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11273 @end example
11275 @item --mode=@var{octal-mode}
11276 @itemx -m @var{octal-mode}
11277 Set the mode of the non-traces output to @var{octal-mode}; by default
11278 @samp{0666}.
11279 @end table
11281 @sp 1
11283 @cindex @file{autom4te.cache}
11284 As another additional feature over @command{m4}, @command{autom4te}
11285 caches its results.  GNU M4 is able to produce a regular
11286 output and traces at the same time.  Traces are heavily used in the
11287 GNU Build System: @command{autoheader} uses them to build
11288 @file{config.h.in}, @command{autoreconf} to determine what
11289 GNU Build System components are used, @command{automake} to
11290 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11291 traces are cached while performing regular expansion,
11292 and conversely.  This cache is (actually, the caches are) stored in
11293 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11294 at any moment (especially if for some reason @command{autom4te}
11295 considers it trashed).
11297 @table @option
11298 @item --cache=@var{directory}
11299 @itemx -C @var{directory}
11300 Specify the name of the directory where the result should be cached.
11301 Passing an empty value disables caching.  Be sure to pass a relative
11302 file name, as for the time being, global caches are not supported.
11304 @item --no-cache
11305 Don't cache the results.
11307 @item --force
11308 @itemx -f
11309 If a cache is used, consider it obsolete (but update it anyway).
11310 @end table
11312 @sp 1
11314 Because traces are so important to the GNU Build System,
11315 @command{autom4te} provides high level tracing features as compared to
11316 M4, and helps exploiting the cache:
11318 @table @option
11319 @item --trace=@var{macro}[:@var{format}]
11320 @itemx -t @var{macro}[:@var{format}]
11321 Trace the invocations of @var{macro} according to the @var{format}.
11322 Multiple @option{--trace} arguments can be used to list several macros.
11323 Multiple @option{--trace} arguments for a single macro are not
11324 cumulative; instead, you should just make @var{format} as long as
11325 needed.
11327 The @var{format} is a regular string, with newlines if desired, and
11328 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11329 use the following special escapes:
11331 @table @samp
11332 @item $$
11333 @c $$ restore font-lock
11334 The character @samp{$}.
11336 @item $f
11337 The file name from which @var{macro} is called.
11339 @item $l
11340 The line number from which @var{macro} is called.
11342 @item $d
11343 The depth of the @var{macro} call.  This is an M4 technical detail that
11344 you probably don't want to know about.
11346 @item $n
11347 The name of the @var{macro}.
11349 @item $@var{num}
11350 The @var{num}th argument of the call to @var{macro}.
11352 @item $@@
11353 @itemx $@var{sep}@@
11354 @itemx $@{@var{separator}@}@@
11355 All the arguments passed to @var{macro}, separated by the character
11356 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11357 argument is quoted, i.e., enclosed in a pair of square brackets.
11359 @item $*
11360 @itemx $@var{sep}*
11361 @itemx $@{@var{separator}@}*
11362 As above, but the arguments are not quoted.
11364 @item $%
11365 @itemx $@var{sep}%
11366 @itemx $@{@var{separator}@}%
11367 As above, but the arguments are not quoted, all new line characters in
11368 the arguments are smashed, and the default separator is @samp{:}.
11370 The escape @samp{$%} produces single-line trace outputs (unless you put
11371 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11372 not.
11373 @end table
11375 @xref{autoconf Invocation}, for examples of trace uses.
11377 @item --preselect=@var{macro}
11378 @itemx -p @var{macro}
11379 Cache the traces of @var{macro}, but do not enable traces.  This is
11380 especially important to save CPU cycles in the future.  For instance,
11381 when invoked, @command{autoconf} preselects all the macros that
11382 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11383 trace, so that running @command{m4} is not needed to trace them: the
11384 cache suffices.  This results in a huge speed-up.
11385 @end table
11387 @sp 1
11389 @cindex Autom4te Library
11390 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11391 libraries}.  They consists in a powerful yet extremely simple feature:
11392 sets of combined command line arguments:
11394 @table @option
11395 @item --language=@var{language}
11396 @itemx -l @var{language}
11397 Use the @var{language} Autom4te library.  Current languages include:
11399 @table @code
11400 @item M4sugar
11401 create M4sugar output.
11403 @item M4sh
11404 create M4sh executable shell scripts.
11406 @item Autotest
11407 create Autotest executable test suites.
11409 @item Autoconf-without-aclocal-m4
11410 create Autoconf executable configure scripts without
11411 reading @file{aclocal.m4}.
11413 @item Autoconf
11414 create Autoconf executable configure scripts.  This language inherits
11415 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11416 additionally reads @file{aclocal.m4}.
11417 @end table
11419 @item --prepend-include=@var{dir}
11420 @itemx -B @var{dir}
11421 Prepend directory @var{dir} to the search path.  This is used to include
11422 the language-specific files before any third-party macros.
11424 @end table
11426 @cindex @file{autom4te.cfg}
11427 As an example, if Autoconf is installed in its default location,
11428 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11429 strictly equivalent to the command:
11431 @example
11432 autom4te --prepend-include /usr/local/share/autoconf \
11433   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11434 @end example
11436 @noindent
11437 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11438 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11439 foo.m4}, i.e.:
11441 @example
11442 autom4te --prepend-include /usr/local/share/autoconf \
11443   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11444 @end example
11446 @noindent
11447 The definition of the languages is stored in @file{autom4te.cfg}.
11449 @node Customizing autom4te
11450 @subsection Customizing @command{autom4te}
11452 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11453 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11454 as found in the directory from which @command{autom4te} is run).  The
11455 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11456 then @file{./.autom4te.cfg}, and finally the command line arguments.
11458 In these text files, comments are introduced with @code{#}, and empty
11459 lines are ignored.  Customization is performed on a per-language basis,
11460 wrapped in between a @samp{begin-language: "@var{language}"},
11461 @samp{end-language: "@var{language}"} pair.
11463 Customizing a language stands for appending options (@pxref{autom4te
11464 Invocation}) to the current definition of the language.  Options, and
11465 more generally arguments, are introduced by @samp{args:
11466 @var{arguments}}.  You may use the traditional shell syntax to quote the
11467 @var{arguments}.
11469 As an example, to disable Autoconf caches (@file{autom4te.cache})
11470 globally, include the following lines in @file{~/.autom4te.cfg}:
11472 @verbatim
11473 ## ------------------ ##
11474 ## User Preferences.  ##
11475 ## ------------------ ##
11477 begin-language: "Autoconf-without-aclocal-m4"
11478 args: --no-cache
11479 end-language: "Autoconf-without-aclocal-m4"
11480 @end verbatim
11483 @node Programming in M4sugar
11484 @section Programming in M4sugar
11486 @cindex M4sugar
11487 M4 by itself provides only a small, but sufficient, set of all-purpose
11488 macros.  M4sugar introduces additional generic macros.  Its name was
11489 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11490 M4sugar''.
11492 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11493 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11494 define your own macros into these namespaces.
11496 @menu
11497 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11498 * Diagnostic Macros::           Diagnostic messages from M4sugar
11499 * Diversion support::           Diversions in M4sugar
11500 * Conditional constructs::      Conditions in M4
11501 * Looping constructs::          Iteration in M4
11502 * Evaluation Macros::           More quotation and evaluation control
11503 * Text processing Macros::      String manipulation in M4
11504 * Number processing Macros::    Arithmetic computation in M4
11505 * Set manipulation Macros::     Set manipulation in M4
11506 * Forbidden Patterns::          Catching unexpanded macros
11507 @end menu
11509 @node Redefined M4 Macros
11510 @subsection Redefined M4 Macros
11512 @msindex{builtin}
11513 @msindex{changecom}
11514 @msindex{changequote}
11515 @msindex{debugfile}
11516 @msindex{debugmode}
11517 @msindex{decr}
11518 @msindex{define}
11519 @msindex{divnum}
11520 @msindex{errprint}
11521 @msindex{esyscmd}
11522 @msindex{eval}
11523 @msindex{format}
11524 @msindex{ifdef}
11525 @msindex{incr}
11526 @msindex{index}
11527 @msindex{indir}
11528 @msindex{len}
11529 @msindex{pushdef}
11530 @msindex{shift}
11531 @msindex{substr}
11532 @msindex{syscmd}
11533 @msindex{sysval}
11534 @msindex{traceoff}
11535 @msindex{traceon}
11536 @msindex{translit}
11537 With a few exceptions, all the M4 native macros are moved in the
11538 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11539 @code{m4_define} etc.
11541 The list of macros unchanged from M4, except for their name, is:
11542 @itemize @minus
11543 @item m4_builtin
11544 @item m4_changecom
11545 @item m4_changequote
11546 @item m4_debugfile
11547 @item m4_debugmode
11548 @item m4_decr
11549 @item m4_define
11550 @item m4_divnum
11551 @item m4_errprint
11552 @item m4_esyscmd
11553 @item m4_eval
11554 @item m4_format
11555 @item m4_ifdef
11556 @item m4_incr
11557 @item m4_index
11558 @item m4_indir
11559 @item m4_len
11560 @item m4_pushdef
11561 @item m4_shift
11562 @item m4_substr
11563 @item m4_syscmd
11564 @item m4_sysval
11565 @item m4_traceoff
11566 @item m4_traceon
11567 @item m4_translit
11568 @end itemize
11570 Some M4 macros are redefined, and are slightly incompatible with their
11571 native equivalent.
11573 @defmac __file__
11574 @defmacx __line__
11575 @MSindex __file__
11576 @MSindex __line__
11577 All M4 macros starting with @samp{__} retain their original name: for
11578 example, no @code{m4__file__} is defined.
11579 @end defmac
11581 @defmac __oline__
11582 @MSindex __oline__
11583 This is not technically a macro, but a feature of Autom4te.  The
11584 sequence @code{__oline__} can be used similarly to the other m4sugar
11585 location macros, but rather than expanding to the location of the input
11586 file, it is translated to the line number where it appears in the output
11587 file after all other M4 expansions.
11588 @end defmac
11590 @defmac dnl
11591 @MSindex dnl
11592 This macro kept its original name: no @code{m4_dnl} is defined.
11593 @end defmac
11595 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11596 @msindex{bpatsubst}
11597 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11598 is kept for future versions of M4sugar, once GNU M4 2.0 is
11599 released and supports extended regular expression syntax.
11600 @end defmac
11602 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11603 @msindex{bregexp}
11604 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11605 is kept for future versions of M4sugar, once GNU M4 2.0 is
11606 released and supports extended regular expression syntax.
11607 @end defmac
11609 @defmac m4_copy (@var{source}, @var{dest})
11610 @defmacx m4_copy_force (@var{source}, @var{dest})
11611 @defmacx m4_rename (@var{source}, @var{dest})
11612 @defmacx m4_rename_force (@var{source}, @var{dest})
11613 @msindex{copy}
11614 @msindex{copy_force}
11615 @msindex{rename}
11616 @msindex{rename_force}
11617 These macros aren't directly builtins, but are closely related to
11618 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11619 @code{m4_rename} ensure that @var{dest} is undefined, while
11620 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11621 definition.  All four macros then proceed to copy the entire pushdef
11622 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11623 and @code{m4_copy_force} preserve the source (including in the special
11624 case where @var{source} is undefined), while @code{m4_rename} and
11625 @code{m4_rename_force} undefine the original macro name (making it an
11626 error to rename an undefined @var{source}).
11628 Note that attempting to invoke a renamed macro might not work, since the
11629 macro may have a dependence on helper macros accessed via composition of
11630 @samp{$0} but that were not also renamed; likewise, other macros may
11631 have a hard-coded dependence on @var{source} and could break if
11632 @var{source} has been deleted.  On the other hand, it is always safe to
11633 rename a macro to temporarily move it out of the way, then rename it
11634 back later to restore original semantics.
11635 @end defmac
11637 @defmac m4_defn (@var{macro}@dots{})
11638 @msindex{defn}
11639 This macro fails if @var{macro} is not defined, even when using older
11640 versions of M4 that did not warn.  See @code{m4_undefine}.
11641 Unfortunately, in order to support these older versions of M4, there are
11642 some situations involving unbalanced quotes where concatenating multiple
11643 macros together will work in newer M4 but not in m4sugar; use
11644 quadrigraphs to work around this.
11645 @end defmac
11647 @defmac m4_divert (@var{diversion})
11648 @msindex{divert}
11649 M4sugar relies heavily on diversions, so rather than behaving as a
11650 primitive, @code{m4_divert} behaves like:
11651 @example
11652 m4_divert_pop()m4_divert_push([@var{diversion}])
11653 @end example
11654 @noindent
11655 @xref{Diversion support}, for more details about the use of the
11656 diversion stack.  In particular, this implies that @var{diversion}
11657 should be a named diversion rather than a raw number.  But be aware that
11658 it is seldom necessary to explicitly change the diversion stack, and
11659 that when done incorrectly, it can lead to syntactically invalid
11660 scripts.
11661 @end defmac
11663 @defmac m4_dumpdef (@var{name}@dots{})
11664 @defmacx m4_dumpdefs (@var{name}@dots{})
11665 @msindex{dumpdef}
11666 @msindex{dumpdefs}
11667 @code{m4_dumpdef} is like the M4 builtin, except that this version
11668 requires at least one argument, output always goes to standard error
11669 rather than the current debug file, no sorting is done on multiple
11670 arguments, and an error is issued if any
11671 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11672 calls @code{m4_dumpdef} for all of the
11673 @code{m4_pushdef} stack of definitions, starting with the current, and
11674 silently does nothing if @var{name} is undefined.
11676 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11677 builtin is output as the empty string.  This behavior is rectified by
11678 using M4 1.6 or newer.  However, this behavior difference means that
11679 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11680 and never in the final published form of a macro.
11681 @end defmac
11683 @defmac m4_esyscmd_s (@var{command})
11684 @msindex{esyscmd_s}
11685 Like @code{m4_esyscmd}, this macro expands to the result of running
11686 @var{command} in a shell.  The difference is that any trailing newlines
11687 are removed, so that the output behaves more like shell command
11688 substitution.
11689 @end defmac
11691 @defmac m4_exit (@var{exit-status})
11692 @msindex{exit}
11693 This macro corresponds to @code{m4exit}.
11694 @end defmac
11696 @defmac m4_if (@var{comment})
11697 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11698 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11699   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11700 @msindex{if}
11701 This macro corresponds to @code{ifelse}.  @var{string-1} and
11702 @var{string-2} are compared literally, so usually one of the two
11703 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11704 conditional idioms.
11705 @end defmac
11707 @defmac m4_include (@var{file})
11708 @defmacx m4_sinclude (@var{file})
11709 @msindex{include}
11710 @msindex{sinclude}
11711 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11712 @end defmac
11714 @defmac m4_mkstemp (@var{template})
11715 @defmacx m4_maketemp (@var{template})
11716 @msindex{maketemp}
11717 @msindex{mkstemp}
11718 Posix requires @code{maketemp} to replace the trailing @samp{X}
11719 characters in @var{template} with the process id, without regards to the
11720 existence of a file by that name, but this a security hole.  When this
11721 was pointed out to the Posix folks, they agreed to invent a new macro
11722 @code{mkstemp} that always creates a uniquely named file, but not all
11723 versions of GNU M4 support the new macro.  In M4sugar,
11724 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11725 and both have the secure semantics regardless of which macro the
11726 underlying M4 provides.
11727 @end defmac
11729 @defmac m4_popdef (@var{macro}@dots{})
11730 @msindex{popdef}
11731 This macro fails if @var{macro} is not defined, even when using older
11732 versions of M4 that did not warn.  See @code{m4_undefine}.
11733 @end defmac
11735 @defmac m4_undefine (@var{macro}@dots{})
11736 @msindex{undefine}
11737 This macro fails if @var{macro} is not defined, even when using older
11738 versions of M4 that did not warn.  Use
11740 @example
11741 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11742 @end example
11744 @noindent
11745 if you are not sure whether @var{macro} is defined.
11746 @end defmac
11748 @defmac m4_undivert (@var{diversion}@dots{})
11749 @msindex{undivert}
11750 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11751 Also, since the M4sugar diversion stack prefers named
11752 diversions, the use of @code{m4_undivert} to include files is risky.
11753 @xref{Diversion support}, for more details about the use of the
11754 diversion stack.  But be aware that it is seldom necessary to explicitly
11755 change the diversion stack, and that when done incorrectly, it can lead
11756 to syntactically invalid scripts.
11757 @end defmac
11759 @defmac m4_wrap (@var{text})
11760 @defmacx m4_wrap_lifo (@var{text})
11761 @msindex{wrap}
11762 @msindex{wrap_lifo}
11763 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11764 multiple wrap calls to be reprocessed at EOF in the same order
11765 as the original calls (first-in, first-out).  GNU M4 versions
11766 through 1.4.10, however, reprocess them in reverse order (last-in,
11767 first-out).  Both orders are useful, therefore, you can rely on
11768 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11769 LIFO semantics, regardless of the underlying GNU M4 version.
11771 Unlike the GNU M4 builtin, these macros only recognize one
11772 argument, and avoid token pasting between consecutive invocations.  On
11773 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11774 work just as in the builtin.
11775 @end defmac
11778 @node Diagnostic Macros
11779 @subsection Diagnostic messages from M4sugar
11780 @cindex Messages, from @command{M4sugar}
11782 When macros statically diagnose abnormal situations, benign or fatal,
11783 they should report them using these macros.  For issuing dynamic issues,
11784 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11786 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11787 @msindex{assert}
11788 Assert that the arithmetic @var{expression} evaluates to non-zero.
11789 Otherwise, issue a fatal error, and exit @command{autom4te} with
11790 @var{exit-status}.
11791 @end defmac
11793 @defmac m4_errprintn (@var{message})
11794 @msindex{errprintn}
11795 Similar to the builtin @code{m4_errprint}, except that a newline is
11796 guaranteed after @var{message}.
11797 @end defmac
11799 @anchor{m4_fatal}
11800 @defmac m4_fatal (@var{message})
11801 @msindex{fatal}
11802 Report a severe error @var{message} prefixed with the current location,
11803 and have @command{autom4te} die.
11804 @end defmac
11806 @defmac m4_location
11807 @msindex{location}
11808 Useful as a prefix in a message line.  Short for:
11809 @example
11810 __file__:__line__
11811 @end example
11812 @end defmac
11814 @anchor{m4_warn}
11815 @defmac m4_warn (@var{category}, @var{message})
11816 @msindex{warn}
11817 Report @var{message} as a warning (or as an error if requested by the
11818 user) if warnings of the @var{category} are turned on.  If the message
11819 is emitted, it is prefixed with the current location, and followed by a
11820 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11821 current expansion.  You are encouraged to use standard categories, which
11822 currently include:
11824 @table @samp
11825 @item all
11826 messages that don't fall into one of the following categories.  Use of an
11827 empty @var{category} is equivalent.
11829 @item cross
11830 related to cross compilation issues.
11832 @item obsolete
11833 use of an obsolete construct.
11835 @item syntax
11836 dubious syntactic constructs, incorrectly ordered macro calls.
11837 @end table
11838 @end defmac
11841 @node Diversion support
11842 @subsection Diversion support
11844 M4sugar makes heavy use of diversions under the hood, because it is
11845 often the case that
11846 text that must appear early in the output is not discovered until late
11847 in the input.  Additionally, some of the topological sorting algorithms
11848 used in resolving macro dependencies use diversions.  However, most
11849 macros should not need to change diversions directly, but rather rely on
11850 higher-level M4sugar macros to manage diversions transparently.  If you
11851 change diversions improperly, you risk generating a syntactically
11852 invalid script, because an incorrect diversion will violate assumptions
11853 made by many macros about whether prerequisite text has been previously
11854 output.  In short, if you manually change the diversion, you should not
11855 expect any macros provided by the Autoconf package to work until you
11856 have restored the diversion stack back to its original state.
11858 In the rare case that it is necessary to write a macro that explicitly
11859 outputs text to a different diversion, it is important to be aware of an
11860 M4 limitation regarding diversions: text only goes to a diversion if it
11861 is not part of argument collection.  Therefore, any macro that changes
11862 the current diversion cannot be used as an unquoted argument to another
11863 macro, but must be expanded at the top level.  The macro
11864 @code{m4_expand} will diagnose any attempt to change diversions, since
11865 it is generally useful only as an argument to another macro.  The
11866 following example shows what happens when diversion manipulation is
11867 attempted within macro arguments:
11869 @example
11870 m4_do([normal text]
11871 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11872 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11873 @result{}normal text
11874 @result{}unwanted
11875 @end example
11877 @noindent
11878 Notice that the unquoted text @code{unwanted} is output, even though it
11879 was processed while the current diversion was @code{KILL}, because it
11880 was collected as part of the argument to @code{m4_do}.  However, the
11881 text @code{discarded} disappeared as desired, because the diversion
11882 changes were single-quoted, and were not expanded until the top-level
11883 rescan of the output of @code{m4_do}.
11885 To make diversion management easier, M4sugar uses the concept of named
11886 diversions.  Rather than using diversion numbers directly, it is nicer
11887 to associate a name with each diversion.  The diversion number associated
11888 with a particular diversion name is an implementation detail, and a
11889 syntax warning is issued if a diversion number is used instead of a
11890 name.  In general, you should not output text
11891 to a named diversion until after calling the appropriate initialization
11892 routine for your language (@code{m4_init}, @code{AS_INIT},
11893 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11894 below.
11896 M4sugar defines two named diversions.
11897 @table @code
11898 @item KILL
11899 Text written to this diversion is discarded.  This is the default
11900 diversion once M4sugar is initialized.
11901 @item GROW
11902 This diversion is used behind the scenes by topological sorting macros,
11903 such as @code{AC_REQUIRE}.
11904 @end table
11906 M4sh adds several more named diversions.
11907 @table @code
11908 @item BINSH
11909 This diversion is reserved for the @samp{#!} interpreter line.
11910 @item HEADER-REVISION
11911 This diversion holds text from @code{AC_REVISION}.
11912 @item HEADER-COMMENT
11913 This diversion holds comments about the purpose of a file.
11914 @item HEADER-COPYRIGHT
11915 This diversion is managed by @code{AC_COPYRIGHT}.
11916 @item M4SH-SANITIZE
11917 This diversion contains M4sh sanitization code, used to ensure M4sh is
11918 executing in a reasonable shell environment.
11919 @item M4SH-INIT
11920 This diversion contains M4sh initialization code, initializing variables
11921 that are required by other M4sh macros.
11922 @item BODY
11923 This diversion contains the body of the shell code, and is the default
11924 diversion once M4sh is initialized.
11925 @end table
11927 Autotest inherits diversions from M4sh, and changes the default
11928 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11929 more named diversions, with the following subset designed for developer
11930 use.
11931 @table @code
11932 @item PREPARE_TESTS
11933 This diversion contains initialization sequences which are executed
11934 after @file{atconfig} and @file{atlocal}, and after all command line
11935 arguments have been parsed, but prior to running any tests.  It can be
11936 used to set up state that is required across all tests.  This diversion
11937 will work even before @code{AT_INIT}.
11938 @end table
11940 Autoconf inherits diversions from M4sh, and adds the following named
11941 diversions which developers can utilize.
11942 @table @code
11943 @item DEFAULTS
11944 This diversion contains shell variable assignments to set defaults that
11945 must be in place before arguments are parsed.  This diversion is placed
11946 early enough in @file{configure} that it is unsafe to expand any
11947 autoconf macros into this diversion.
11948 @item HELP_ENABLE
11949 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11950 diversion will be included as part of a quoted here-doc providing all of
11951 the @option{--help} output of @file{configure} related to options
11952 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11953 @item INIT_PREPARE
11954 This diversion occurs after all command line options have been parsed,
11955 but prior to the main body of the @file{configure} script.  This
11956 diversion is the last chance to insert shell code such as variable
11957 assignments or shell function declarations that will used by the
11958 expansion of other macros.
11959 @end table
11961 For now, the remaining named diversions of Autoconf, Autoheader, and
11962 Autotest are not documented.  In other words,
11963 intentionally outputting text into an undocumented diversion is subject
11964 to breakage in a future release of Autoconf.
11966 @defmac m4_cleardivert (@var{diversion}@dots{})
11967 @msindex{cleardivert}
11968 Permanently discard any text that has been diverted into
11969 @var{diversion}.
11970 @end defmac
11972 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11973 @msindex{divert_once}
11974 Similar to @code{m4_divert_text}, except that @var{content} is only
11975 output to @var{diversion} if this is the first time that
11976 @code{m4_divert_once} has been called with its particular arguments.
11977 @end defmac
11979 @defmac m4_divert_pop (@ovar{diversion})
11980 @msindex{divert_pop}
11981 If provided, check that the current diversion is indeed @var{diversion}.
11982 Then change to the diversion located earlier on the stack, giving an
11983 error if an attempt is made to pop beyond the initial m4sugar diversion
11984 of @code{KILL}.
11985 @end defmac
11987 @defmac m4_divert_push (@var{diversion})
11988 @msindex{divert_push}
11989 Remember the former diversion on the diversion stack, and output
11990 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11991 stack, and issues an error if there is not a matching pop for every
11992 push.
11993 @end defmac
11995 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11996 @msindex{divert_text}
11997 Output @var{content} and a newline into @var{diversion}, without
11998 affecting the current diversion.  Shorthand for:
11999 @example
12000 m4_divert_push([@var{diversion}])@var{content}
12001 m4_divert_pop([@var{diversion}])dnl
12002 @end example
12004 One use of @code{m4_divert_text} is to develop two related macros, where
12005 macro @samp{MY_A} does the work, but adjusts what work is performed
12006 based on whether the optional macro @samp{MY_B} has also been expanded.
12007 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12008 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12009 imposes an ordering restriction on the user; it would be nicer if macros
12010 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12011 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12012 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12013 expanded.
12015 @example
12016 AC_DEFUN([MY_A],
12017 [# various actions
12018 if test -n "$b_was_used"; then
12019   # extra action
12020 fi])
12021 AC_DEFUN([MY_B],
12022 [AC_REQUIRE([MY_A])dnl
12023 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12024 @end example
12026 @end defmac
12028 @defmac m4_init
12029 @msindex{init}
12030 Initialize the M4sugar environment, setting up the default named
12031 diversion to be @code{KILL}.
12032 @end defmac
12034 @node Conditional constructs
12035 @subsection Conditional constructs
12037 The following macros provide additional conditional constructs as
12038 convenience wrappers around @code{m4_if}.
12040 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12041   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12042 @msindex{bmatch}
12043 The string @var{string} is repeatedly compared against a series of
12044 @var{regex} arguments; if a match is found, the expansion is the
12045 corresponding @var{value}, otherwise, the macro moves on to the next
12046 @var{regex}.  If no @var{regex} match, then the result is the optional
12047 @var{default}, or nothing.
12048 @end defmac
12050 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12051   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12052 @msindex{bpatsubsts}
12053 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12054 as if by:
12055 @example
12056 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12057 @end example
12059 @noindent
12060 The result of the substitution is then passed through the next set of
12061 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12062 deletion of any matched portions in the current string.  Note that this
12063 macro over-quotes @var{string}; this behavior is intentional, so that
12064 the result of each step of the recursion remains as a quoted string.
12065 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12066 will line up with the extra quotations, and not the characters of the
12067 original string.  The overquoting is removed after the final
12068 substitution.
12069 @end defmac
12071 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12072   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12073 @msindex{case}
12074 Test @var{string} against multiple @var{value} possibilities, resulting
12075 in the first @var{if-value} for a match, or in the optional
12076 @var{default}.  This is shorthand for:
12077 @example
12078 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12079       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12080       [@var{default}])
12081 @end example
12082 @end defmac
12084 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12085   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12086 @msindex{cond}
12087 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12088 except that each @var{test} is expanded only when it is encountered.
12089 This is useful for short-circuiting expensive tests; while @code{m4_if}
12090 requires all its strings to be expanded up front before doing
12091 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12092 tests have failed.
12094 For an example, these two sequences give the same result, but in the
12095 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12096 version only expands @code{m4_index} once, instead of five times, for
12097 faster computation if this is a common case for @samp{$1}.  Notice that
12098 every third argument is unquoted for @code{m4_if}, and quoted for
12099 @code{m4_cond}:
12101 @example
12102 m4_if(m4_index([$1], [\]), [-1], [$2],
12103       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12104       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12105       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12106       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12107       [$2])
12108 m4_cond([m4_index([$1], [\])], [-1], [$2],
12109         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12110         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12111         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12112         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12113         [$2])
12114 @end example
12115 @end defmac
12117 @defmac m4_default (@var{expr-1}, @var{expr-2})
12118 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12119 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12120 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12121 @msindex{default}
12122 @msindex{default_quoted}
12123 @msindex{default_nblank}
12124 @msindex{default_nblank_quoted}
12125 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12126 @code{m4_default} expands the result, while @code{m4_default_quoted}
12127 does not.  Useful for providing a fixed default if the expression that
12128 results in @var{expr-1} would otherwise be empty.  The difference
12129 between @code{m4_default} and @code{m4_default_nblank} is whether an
12130 argument consisting of just blanks (space, tab, newline) is
12131 significant.  When using the expanding versions, note that an argument
12132 may contain text but still expand to an empty string.
12134 @example
12135 m4_define([active], [ACTIVE])dnl
12136 m4_define([empty], [])dnl
12137 m4_define([demo1], [m4_default([$1], [$2])])dnl
12138 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12139 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12140 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12141 demo1([active], [default])
12142 @result{}ACTIVE
12143 demo1([], [active])
12144 @result{}ACTIVE
12145 demo1([empty], [text])
12146 @result{}
12147 -demo1([ ], [active])-
12148 @result{}- -
12149 demo2([active], [default])
12150 @result{}active
12151 demo2([], [active])
12152 @result{}active
12153 demo2([empty], [text])
12154 @result{}empty
12155 -demo2([ ], [active])-
12156 @result{}- -
12157 demo3([active], [default])
12158 @result{}ACTIVE
12159 demo3([], [active])
12160 @result{}ACTIVE
12161 demo3([empty], [text])
12162 @result{}
12163 -demo3([ ], [active])-
12164 @result{}-ACTIVE-
12165 demo4([active], [default])
12166 @result{}active
12167 demo4([], [active])
12168 @result{}active
12169 demo4([empty], [text])
12170 @result{}empty
12171 -demo4([ ], [active])-
12172 @result{}-active-
12173 @end example
12174 @end defmac
12176 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12177 @msindex{define_default}
12178 If @var{macro} does not already have a definition, then define it to
12179 @var{default-definition}.
12180 @end defmac
12182 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12183 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12184 @msindex{ifblank}
12185 @msindex{ifnblank}
12186 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12187 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12188 variants exist, in order to make it easier to select the correct logical
12189 sense when using only two parameters.  Note that this is more efficient
12190 than the equivalent behavior of:
12191 @example
12192 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12193 @end example
12194 @end defmac
12196 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12197 @msindex{ifndef}
12198 This is shorthand for:
12199 @example
12200 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12201 @end example
12202 @end defmac
12204 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12205 @msindex{ifset}
12206 If @var{macro} is undefined, or is defined as the empty string, expand
12207 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12208 @example
12209 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12210 @end example
12211 @noindent
12212 except that it is not an error if @var{macro} is undefined.
12213 @end defmac
12215 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12216 @msindex{ifval}
12217 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12218 @var{if-false}.  This is shorthand for:
12219 @example
12220 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12221 @end example
12222 @end defmac
12224 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12225 @msindex{ifvaln}
12226 Similar to @code{m4_ifval}, except guarantee that a newline is present
12227 after any non-empty expansion.  Often followed by @code{dnl}.
12228 @end defmac
12230 @defmac m4_n (@var{text})
12231 @msindex{n}
12232 Expand to @var{text}, and add a newline if @var{text} is not empty.
12233 Often followed by @code{dnl}.
12234 @end defmac
12237 @node Looping constructs
12238 @subsection Looping constructs
12240 The following macros are useful in implementing recursive algorithms in
12241 M4, including loop operations.  An M4 list is formed by quoting a list
12242 of quoted elements; generally the lists are comma-separated, although
12243 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12244 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12245 It is common to see lists with unquoted elements when those elements are
12246 not likely to be macro names, as in @samp{[fputc_unlocked,
12247 fgetc_unlocked]}.
12249 Although not generally recommended, it is possible for quoted lists to
12250 have side effects; all side effects are expanded only once, and prior to
12251 visiting any list element.  On the other hand, the fact that unquoted
12252 macros are expanded exactly once means that macros without side effects
12253 can be used to generate lists.  For example,
12255 @example
12256 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12257 @error{}hi
12258 @result{}123
12259 m4_define([list], [[1], [2], [3]])
12260 @result{}
12261 m4_foreach([i], [list], [i])
12262 @result{}123
12263 @end example
12265 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12266 @msindex{argn}
12267 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12268 If there are too few arguments, the empty string is used.  For any
12269 @var{n} besides 1, this is more efficient than the similar
12270 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12271 @end defmac
12273 @defmac m4_car (@var{arg}@dots{})
12274 @msindex{car}
12275 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12276 to recursively iterate
12277 through a list.  Generally, when using quoted lists of quoted elements,
12278 @code{m4_car} should be called without any extra quotes.
12279 @end defmac
12281 @defmac m4_cdr (@var{arg}@dots{})
12282 @msindex{cdr}
12283 Expands to a quoted list of all but the first @var{arg}, or the empty
12284 string if there was only one argument.  Generally, when using quoted
12285 lists of quoted elements, @code{m4_cdr} should be called without any
12286 extra quotes.
12288 For example, this is a simple implementation of @code{m4_map}; note how
12289 each iteration checks for the end of recursion, then merely applies the
12290 first argument to the first element of the list, then repeats with the
12291 rest of the list.  (The actual implementation in M4sugar is a bit more
12292 involved, to gain some speed and share code with @code{m4_map_sep}, and
12293 also to avoid expanding side effects in @samp{$2} twice).
12294 @example
12295 m4_define([m4_map], [m4_ifval([$2],
12296   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12297 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12298 @result{} 1 2 a
12299 @end example
12300 @end defmac
12302 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12303   @var{expression})
12304 @msindex{for}
12305 Loop over the numeric values between @var{first} and @var{last}
12306 including bounds by increments of @var{step}.  For each iteration,
12307 expand @var{expression} with the numeric value assigned to @var{var}.
12308 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12309 on the order of the limits.  If given, @var{step} has to match this
12310 order.  The number of iterations is determined independently from
12311 definition of @var{var}; iteration cannot be short-circuited or
12312 lengthened by modifying @var{var} from within @var{expression}.
12313 @end defmac
12315 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12316 @msindex{foreach}
12317 Loop over the comma-separated M4 list @var{list}, assigning each value
12318 to @var{var}, and expand @var{expression}.  The following example
12319 outputs two lines:
12321 @example
12322 m4_foreach([myvar], [[foo], [bar, baz]],
12323            [echo myvar
12324 ])dnl
12325 @result{}echo foo
12326 @result{}echo bar, baz
12327 @end example
12329 Note that for some forms of @var{expression}, it may be faster to use
12330 @code{m4_map_args}.
12331 @end defmac
12333 @anchor{m4_foreach_w}
12334 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12335 @msindex{foreach_w}
12336 Loop over the white-space-separated list @var{list}, assigning each value
12337 to @var{var}, and expand @var{expression}.  If @var{var} is only
12338 referenced once in @var{expression}, it is more efficient to use
12339 @code{m4_map_args_w}.
12341 The deprecated macro @code{AC_FOREACH} is an alias of
12342 @code{m4_foreach_w}.
12343 @end defmac
12345 @defmac m4_map (@var{macro}, @var{list})
12346 @defmacx m4_mapall (@var{macro}, @var{list})
12347 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12348 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12349 @msindex{map}
12350 @msindex{mapall}
12351 @msindex{map_sep}
12352 @msindex{mapall_sep}
12353 Loop over the comma separated quoted list of argument descriptions in
12354 @var{list}, and invoke @var{macro} with the arguments.  An argument
12355 description is in turn a comma-separated quoted list of quoted elements,
12356 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12357 @code{m4_map_sep} ignore empty argument descriptions, while
12358 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12359 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12360 additionally expand @var{separator} between invocations of @var{macro}.
12362 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12363 separating output with commas, this means that the map result can be
12364 used as a series of arguments, by using a single-quoted comma as
12365 @var{separator}, or as a single string, by using a double-quoted comma.
12367 @example
12368 m4_map([m4_count], [])
12369 @result{}
12370 m4_map([ m4_count], [[],
12371                      [[1]],
12372                      [[1], [2]]])
12373 @result{} 1 2
12374 m4_mapall([ m4_count], [[],
12375                         [[1]],
12376                         [[1], [2]]])
12377 @result{} 0 1 2
12378 m4_map_sep([m4_eval], [,], [[[1+2]],
12379                             [[10], [16]]])
12380 @result{}3,a
12381 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12382 @result{}a,b
12383 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12384 @result{}2
12385 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12386 @result{}a,b
12387 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12388 @result{}1
12389 @end example
12390 @end defmac
12392 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12393 @msindex{map_args}
12394 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12395 argument.  In the following example, three solutions are presented with
12396 the same expansion; the solution using @code{m4_map_args} is the most
12397 efficient.
12398 @example
12399 m4_define([active], [ACTIVE])dnl
12400 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12401 @result{} plain active
12402 m4_map([ m4_echo], [[[plain]], [[active]]])
12403 @result{} plain active
12404 m4_map_args([ m4_echo], [plain], [active])
12405 @result{} plain active
12406 @end example
12408 In cases where it is useful to operate on additional parameters besides
12409 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12410 to supply the argument currying necessary to generate the desired
12411 argument list.  In the following example, @code{list_add_n} is more
12412 efficient than @code{list_add_x}.  On the other hand, using
12413 @code{m4_map_args_sep} can be even more efficient.
12415 @example
12416 m4_define([list], [[1], [2], [3]])dnl
12417 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12418 dnl list_add_n(N, ARG...)
12419 dnl Output a list consisting of each ARG added to N
12420 m4_define([list_add_n],
12421 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12422 list_add_n([1], list)
12423 @result{}2,3,4
12424 list_add_n([2], list)
12425 @result{}3,4,5
12426 m4_define([list_add_x],
12427 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12428   [,add([$1],m4_defn([var]))]))])dnl
12429 list_add_x([1], list)
12430 @result{}2,3,4
12431 @end example
12432 @end defmac
12434 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
12435   @var{arg}@dots{})
12436 @msindex{map_args_pair}
12437 For every pair of arguments @var{arg}, invoke @var{macro} with two
12438 arguments.  If there is an odd number of arguments, invoke
12439 @var{macro-end}, which defaults to @var{macro}, with the remaining
12440 argument.
12442 @example
12443 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12444 @result{}, 2, 1, 3
12445 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12446 @result{}, 2, 1, [3]
12447 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12448 @result{}, 2, 1, 4, 3
12449 @end example
12450 @end defmac
12452 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12453 @msindex{map_args_sep}
12454 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12455 argument, additionally expanding @var{sep} between arguments.  One
12456 common use of this macro is constructing a macro call, where the opening
12457 and closing parentheses are split between @var{pre} and @var{post}; in
12458 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12459 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12460 macro provides the most efficient means for iterating over an arbitrary
12461 list of arguments, particularly when repeatedly constructing a macro
12462 call with more arguments than @var{arg}.
12463 @end defmac
12465 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12466 @msindex{map_args_w}
12467 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12468 the whitespace-separated @var{string}, additionally expanding @var{sep}
12469 between words.  This macro provides the most efficient means for
12470 iterating over a whitespace-separated string.  In particular,
12471 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12472 efficient than @code{m4_foreach_w([var], [@var{string}],
12473 [@var{action}(m4_defn([var]))])}.
12474 @end defmac
12476 @defmac m4_shiftn (@var{count}, @dots{})
12477 @defmacx m4_shift2 (@dots{})
12478 @defmacx m4_shift3 (@dots{})
12479 @msindex{shift2}
12480 @msindex{shift3}
12481 @msindex{shiftn}
12482 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12483 along with validation that enough arguments were passed in to match the
12484 shift count, and that the count is positive.  @code{m4_shift2} and
12485 @code{m4_shift3} are specializations
12486 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12487 for two and three shifts, respectively.
12488 @end defmac
12490 @defmac m4_stack_foreach (@var{macro}, @var{action})
12491 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12492 @msindex{stack_foreach}
12493 @msindex{stack_foreach_lifo}
12494 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12495 @var{action} with the single argument of a definition of @var{macro}.
12496 @code{m4_stack_foreach} starts with the oldest definition, while
12497 @code{m4_stack_foreach_lifo} starts with the current definition.
12498 @var{action} should not push or pop definitions of @var{macro}, nor is
12499 there any guarantee that the current definition of @var{macro} matches
12500 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12501 can be used if @var{action} needs more than one argument, although in
12502 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12504 Due to technical limitations, there are a few low-level m4sugar
12505 functions, such as @code{m4_pushdef}, that cannot be used as the
12506 @var{macro} argument.
12508 @example
12509 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12510 m4_stack_foreach([a], [ m4_incr])
12511 @result{} 2 3
12512 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12513 @result{} cd bcd
12514 @end example
12515 @end defmac
12517 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12518 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12519   @ovar{sep})
12520 @msindex{stack_foreach_sep}
12521 @msindex{stack_foreach_sep_lifo}
12522 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12523 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12524 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12525 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12526 the current definition first.  This macro provides the most efficient
12527 means for iterating over a pushdef stack.  In particular,
12528 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12529 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12530 @end defmac
12532 @node Evaluation Macros
12533 @subsection Evaluation Macros
12535 The following macros give some control over the order of the evaluation
12536 by adding or removing levels of quotes.
12538 @defmac m4_apply (@var{macro}, @var{list})
12539 @msindex{apply}
12540 Apply the elements of the quoted, comma-separated @var{list} as the
12541 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12542 without arguments.  Note the difference between @code{m4_indir}, which
12543 expects its first argument to be a macro name but can use names that are
12544 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12545 other text, but must end in a valid macro name.
12546 @example
12547 m4_apply([m4_count], [])
12548 @result{}0
12549 m4_apply([m4_count], [[]])
12550 @result{}1
12551 m4_apply([m4_count], [[1], [2]])
12552 @result{}2
12553 m4_apply([m4_join], [[|], [1], [2]])
12554 @result{}1|2
12555 @end example
12556 @end defmac
12558 @defmac m4_count (@var{arg}, @dots{})
12559 @msindex{count}
12560 This macro returns the decimal count of the number of arguments it was
12561 passed.
12562 @end defmac
12564 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12565 @msindex{curry}
12566 This macro performs argument currying.  The expansion of this macro is
12567 another macro name that expects exactly one argument; that argument is
12568 then appended to the @var{arg} list, and then @var{macro} is expanded
12569 with the resulting argument list.
12571 @example
12572 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12573 @result{}3, 2, 1
12574 @end example
12576 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12577 pass the definition of a builtin macro as the argument to the output of
12578 @code{m4_curry}; the empty string is used instead of the builtin token.
12579 This behavior is rectified by using M4 1.6 or newer.
12580 @end defmac
12582 @defmac m4_do (@var{arg}, @dots{})
12583 @msindex{do}
12584 This macro loops over its arguments and expands each @var{arg} in
12585 sequence.  Its main use is for readability; it allows the use of
12586 indentation and fewer @code{dnl} to result in the same expansion.  This
12587 macro guarantees that no expansion will be concatenated with subsequent
12588 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12589 @var{arg@dots{}}))}.
12591 @example
12592 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12593 m4_do([a],[b])c
12594 @result{}abc
12595 m4_unquote(m4_join([],[a],[b]))c
12596 @result{}3
12597 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12598 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12599 m4_do([a],[b])c
12600 @result{}ABC
12601 m4_unquote(m4_join([],[a],[b]))c
12602 @result{}3
12603 @end example
12604 @end defmac
12606 @defmac m4_dquote (@var{arg}, @dots{})
12607 @msindex{dquote}
12608 Return the arguments as a quoted list of quoted arguments.
12609 Conveniently, if there is just one @var{arg}, this effectively adds a
12610 level of quoting.
12611 @end defmac
12613 @defmac m4_dquote_elt (@var{arg}, @dots{})
12614 @msindex{dquote_elt}
12615 Return the arguments as a series of double-quoted arguments.  Whereas
12616 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12617 as many arguments as it was passed.
12618 @end defmac
12620 @defmac m4_echo (@var{arg}, @dots{})
12621 @msindex{echo}
12622 Return the arguments, with the same level of quoting.  Other than
12623 discarding whitespace after unquoted commas, this macro is a no-op.
12624 @end defmac
12626 @defmac m4_expand (@var{arg})
12627 @msindex{expand}
12628 Return the expansion of @var{arg} as a quoted string.  Whereas
12629 @code{m4_quote} is designed to collect expanded text into a single
12630 argument, @code{m4_expand} is designed to perform one level of expansion
12631 on quoted text.  One distinction is in the treatment of whitespace
12632 following a comma in the original @var{arg}.  Any time multiple
12633 arguments are collected into one with @code{m4_quote}, the M4 argument
12634 collection rules discard the whitespace.  However, with @code{m4_expand},
12635 whitespace is preserved, even after the expansion of macros contained in
12636 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12637 would involve an unterminated comment, whereas expanding that same text
12638 as the argument to @code{m4_quote} runs into difficulty in finding the
12639 end of the argument.  Since manipulating diversions during argument
12640 collection is inherently unsafe, @code{m4_expand} issues an error if
12641 @var{arg} attempts to change the current diversion (@pxref{Diversion
12642 support}).
12644 @example
12645 m4_define([active], [ACT, IVE])dnl
12646 m4_define([active2], [[ACT, IVE]])dnl
12647 m4_quote(active, active)
12648 @result{}ACT,IVE,ACT,IVE
12649 m4_expand([active, active])
12650 @result{}ACT, IVE, ACT, IVE
12651 m4_quote(active2, active2)
12652 @result{}ACT, IVE,ACT, IVE
12653 m4_expand([active2, active2])
12654 @result{}ACT, IVE, ACT, IVE
12655 m4_expand([# m4_echo])
12656 @result{}# m4_echo
12657 m4_quote(# m4_echo)
12659 @result{}# m4_echo)
12660 @result{}
12661 @end example
12663 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12664 literal unbalanced quotes, but that quadrigraphs can be used when
12665 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12666 be supplied with double quoting or a quadrigraph.
12668 @example
12669 m4_define([pattern], [[!@@<:@@]])dnl
12670 m4_define([bar], [BAR])dnl
12671 m4_expand([case $foo in
12672   m4_defn([pattern])@@:@}@@ bar ;;
12673   *[)] blah ;;
12674 esac])
12675 @result{}case $foo in
12676 @result{}  [![]) BAR ;;
12677 @result{}  *) blah ;;
12678 @result{}esac
12679 @end example
12680 @end defmac
12682 @defmac m4_ignore (@dots{})
12683 @msindex{ignore}
12684 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12685 ignoring all of its arguments.  By itself, this isn't very useful.
12686 However, it can be used to conditionally ignore an arbitrary number of
12687 arguments, by deciding which macro name to apply to a list of arguments.
12688 @example
12689 dnl foo outputs a message only if [debug] is defined.
12690 m4_define([foo],
12691 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12692 @end example
12694 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12695 serve the same purpose, although it is less readable.
12696 @end defmac
12698 @defmac m4_make_list (@var{arg}, @dots{})
12699 @msindex{make_list}
12700 This macro exists to aid debugging of M4sugar algorithms.  Its net
12701 effect is similar to @code{m4_dquote}---it produces a quoted list of
12702 quoted arguments, for each @var{arg}.  The difference is that this
12703 version uses a comma-newline separator instead of just comma, to improve
12704 readability of the list; with the result that it is less efficient than
12705 @code{m4_dquote}.
12706 @example
12707 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12708 m4_dquote(zero, [one], [[two]])
12709 @result{}[0],[one],[[two]]
12710 m4_make_list(zero, [one], [[two]])
12711 @result{}[0],
12712 @result{}[one],
12713 @result{}[[two]]
12714 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12715 @result{} 0 1 two
12716 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12717 @result{} 0 1 two
12718 @end example
12719 @end defmac
12721 @c m4_noquote is too dangerous to document - it invokes macros that
12722 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12723 @c user should generally prefer m4_unquote instead.
12725 @defmac m4_quote (@var{arg}, @dots{})
12726 @msindex{quote}
12727 Return the arguments as a single entity, i.e., wrap them into a pair of
12728 quotes.  This effectively collapses multiple arguments into one,
12729 although it loses whitespace after unquoted commas in the process.
12730 @end defmac
12732 @defmac m4_reverse (@var{arg}, @dots{})
12733 @msindex{reverse}
12734 Outputs each argument with the same level of quoting, but in reverse
12735 order, and with space following each comma for readability.
12737 @example
12738 m4_define([active], [ACT,IVE])
12739 @result{}
12740 m4_reverse(active, [active])
12741 @result{}active, IVE, ACT
12742 @end example
12743 @end defmac
12745 @defmac m4_unquote (@var{arg}, @dots{})
12746 @msindex{unquote}
12747 This macro was introduced in Autoconf 2.62.  Expand each argument,
12748 separated by commas.  For a single @var{arg}, this effectively removes a
12749 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12750 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12751 this results in an unquoted list of expansions.  This is commonly used
12752 with @code{m4_split}, in order to convert a single quoted list into a
12753 series of quoted elements.
12754 @end defmac
12756 The following example aims at emphasizing the difference between several
12757 scenarios: not using these macros, using @code{m4_defn}, using
12758 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12760 @example
12761 $ @kbd{cat example.m4}
12762 dnl Overquote, so that quotes are visible.
12763 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12764 m4_define([a], [A])
12765 m4_define([mkargs], [1, 2[,] 3])
12766 m4_define([arg1], [[$1]])
12767 m4_divert([0])dnl
12768 show(a, b)
12769 show([a, b])
12770 show(m4_quote(a, b))
12771 show(m4_dquote(a, b))
12772 show(m4_expand([a, b]))
12774 arg1(mkargs)
12775 arg1([mkargs])
12776 arg1(m4_defn([mkargs]))
12777 arg1(m4_quote(mkargs))
12778 arg1(m4_dquote(mkargs))
12779 arg1(m4_expand([mkargs]))
12780 $ @kbd{autom4te -l m4sugar example.m4}
12781 $1 = A, $@@ = [A],[b]
12782 $1 = a, b, $@@ = [a, b]
12783 $1 = A,b, $@@ = [A,b]
12784 $1 = [A],[b], $@@ = [[A],[b]]
12785 $1 = A, b, $@@ = [A, b]
12788 mkargs
12789 1, 2[,] 3
12790 1,2, 3
12791 [1],[2, 3]
12792 1, 2, 3
12793 @end example
12796 @node Text processing Macros
12797 @subsection String manipulation in M4
12799 The following macros may be used to manipulate strings in M4.  Many of
12800 the macros in this section intentionally result in quoted strings as
12801 output, rather than subjecting the arguments to further expansions.  As
12802 a result, if you are manipulating text that contains active M4
12803 characters, the arguments are passed with single quoting rather than
12804 double.
12806 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12807 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12808   @ovar{if-uniq}, @ovar{if-duplicate})
12809 @msindex{append}
12810 @msindex{append_uniq}
12811 Redefine @var{macro-name} to its former contents with @var{separator}
12812 and @var{string} added at the end.  If @var{macro-name} was undefined
12813 before (but not if it was defined but empty), then no @var{separator} is
12814 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12815 are expanded during this macro; instead, they are expanded when
12816 @var{macro-name} is invoked.
12818 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12819 to grow strings without duplicating substrings.  Additionally,
12820 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12821 @var{if-uniq} is expanded if @var{string} was appended, and
12822 @var{if-duplicate} is expanded if @var{string} was already present.
12823 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12824 occurs within @var{string}, since that can lead to duplicates.
12826 Note that @code{m4_append} can scale linearly in the length of the final
12827 string, depending on the quality of the underlying M4 implementation,
12828 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12829 If an algorithm can tolerate duplicates in the final string, use the
12830 former for speed.  If duplicates must be avoided, consider using
12831 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12833 @example
12834 m4_define([active], [ACTIVE])dnl
12835 m4_append([sentence], [This is an])dnl
12836 m4_append([sentence], [ active ])dnl
12837 m4_append([sentence], [symbol.])dnl
12838 sentence
12839 @result{}This is an ACTIVE symbol.
12840 m4_undefine([active])dnl
12841 @result{}This is an active symbol.
12842 m4_append_uniq([list], [one], [, ], [new], [existing])
12843 @result{}new
12844 m4_append_uniq([list], [one], [, ], [new], [existing])
12845 @result{}existing
12846 m4_append_uniq([list], [two], [, ], [new], [existing])
12847 @result{}new
12848 m4_append_uniq([list], [three], [, ], [new], [existing])
12849 @result{}new
12850 m4_append_uniq([list], [two], [, ], [new], [existing])
12851 @result{}existing
12852 list
12853 @result{}one, two, three
12854 m4_dquote(list)
12855 @result{}[one],[two],[three]
12856 m4_append([list2], [one], [[, ]])dnl
12857 m4_append_uniq([list2], [two], [[, ]])dnl
12858 m4_append([list2], [three], [[, ]])dnl
12859 list2
12860 @result{}one, two, three
12861 m4_dquote(list2)
12862 @result{}[one, two, three]
12863 @end example
12864 @end defmac
12866 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12867 @msindex{append_uniq_w}
12868 This macro was introduced in Autoconf 2.62.  It is similar to
12869 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12870 separated list of words to append, and only appends unique words.
12871 @var{macro-name} is updated with a single space between new words.
12872 @example
12873 m4_append_uniq_w([numbers], [1 1 2])dnl
12874 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12875 numbers
12876 @result{}1 2 3
12877 @end example
12878 @end defmac
12880 @defmac m4_chomp (@var{string})
12881 @defmacx m4_chomp_all (@var{string})
12882 @msindex{chomp}
12883 @msindex{chomp_all}
12884 Output @var{string} in quotes, but without a trailing newline.  The
12885 macro @code{m4_chomp} is slightly faster, and removes at most one
12886 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12887 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12888 and backslash does not influence the result.
12889 @end defmac
12891 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12892   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12893 @msindex{combine}
12894 This macro produces a quoted string containing the pairwise combination
12895 of every element of the quoted, comma-separated @var{prefix-list}, and
12896 every element from the @var{suffix} arguments.  Each pairwise
12897 combination is joined with @var{infix} in the middle, and successive
12898 pairs are joined by @var{separator}.  No expansion occurs on any of the
12899 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12900 list is empty, but the lists can contain empty elements.
12901 @example
12902 m4_define([a], [oops])dnl
12903 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12904 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12905 m4_combine([, ], [[a], [b]], [-])
12906 @result{}
12907 m4_combine([, ], [[a], [b]], [-], [])
12908 @result{}a-, b-
12909 m4_combine([, ], [], [-], [1], [2])
12910 @result{}
12911 m4_combine([, ], [[]], [-], [1], [2])
12912 @result{}-1, -2
12913 @end example
12914 @end defmac
12916 @defmac m4_escape (@var{string})
12917 @msindex{escape}
12918 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12919 within @var{string} into their respective quadrigraphs.  The result is
12920 still a quoted string.
12921 @end defmac
12923 @defmac m4_flatten (@var{string})
12924 @msindex{flatten}
12925 Flatten @var{string} into a single line.  Delete all backslash-newline
12926 pairs, and replace all remaining newlines with a space.  The result is
12927 still a quoted string.
12928 @end defmac
12930 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12931 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12932 @msindex{join}
12933 @msindex{joinall}
12934 Concatenate each @var{arg}, separated by @var{separator}.
12935 @code{joinall} uses every argument, while @code{join} omits empty
12936 arguments so that there are no back-to-back separators in the output.
12937 The result is a quoted string.
12938 @example
12939 m4_define([active], [ACTIVE])dnl
12940 m4_join([|], [one], [], [active], [two])
12941 @result{}one|active|two
12942 m4_joinall([|], [one], [], [active], [two])
12943 @result{}one||active|two
12944 @end example
12946 Note that if all you intend to do is join @var{args} with commas between
12947 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12948 efficient to use @code{m4_dquote}.
12949 @end defmac
12951 @defmac m4_newline (@ovar{text})
12952 @msindex{newline}
12953 This macro was introduced in Autoconf 2.62, and expands to a newline,
12954 followed by any @var{text}.
12955 It is primarily useful for maintaining macro formatting, and ensuring
12956 that M4 does not discard leading whitespace during argument collection.
12957 @end defmac
12959 @defmac m4_normalize (@var{string})
12960 @msindex{normalize}
12961 Remove leading and trailing spaces and tabs, sequences of
12962 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12963 with a single space.  This is a combination of @code{m4_flatten} and
12964 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12965 that would be removed by @code{m4_normalize}, you can use
12966 @code{m4_ifblank}.
12967 @end defmac
12969 @defmac m4_re_escape (@var{string})
12970 @msindex{re_escape}
12971 Backslash-escape all characters in @var{string} that are active in
12972 regexps.
12973 @end defmac
12975 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12976 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12977 @msindex{split}
12978 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12979 @samp{]}, while keeping white space at the beginning and at the end.
12980 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12981 If @var{string} is empty, the result is an empty list.
12982 @end defmac
12984 @defmac m4_strip (@var{string})
12985 @msindex{strip}
12986 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12987 reduced to a single space, then leading and trailing spaces are removed.
12988 The result is still a quoted string.  Note that this does not interfere
12989 with newlines; if you want newlines stripped as well, consider
12990 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12991 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12992 @end defmac
12994 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12995 @msindex{text_box}
12996 Add a text box around @var{message}, using @var{frame} as the border
12997 character above and below the message.  The @var{frame} argument must be
12998 a single byte, and does not support quadrigraphs.
12999 The frame correctly accounts for
13000 the subsequent expansion of @var{message}.  For example:
13001 @example
13002 m4_define([macro], [abc])dnl
13003 m4_text_box([macro])
13004 @result{}## --- ##
13005 @result{}## abc ##
13006 @result{}## --- ##
13007 @end example
13009 The @var{message} must contain balanced quotes and parentheses, although
13010 quadrigraphs can be used to work around this.
13011 @end defmac
13013 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13014   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
13015 @msindex{text_wrap}
13016 Break @var{string} into a series of whitespace-separated words, then
13017 output those words separated by spaces, and wrapping lines any time the
13018 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13019 the first line, and @var{prefix} begins all wrapped lines.  If
13020 @var{prefix1} is longer than @var{prefix}, then the first line consists
13021 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13022 padding is inserted so that the first word of @var{string} begins at the
13023 same indentation as all wrapped lines.  Note that using literal tab
13024 characters in any of the arguments will interfere with the calculation
13025 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13026 words of @var{string}, although quadrigraphs are recognized.
13028 For some examples:
13029 @example
13030 m4_text_wrap([Short string */], [   ], [/* ], [20])
13031 @result{}/* Short string */
13032 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13033 @result{}/* Much longer
13034 @result{}   string */
13035 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13036 @result{}  --short Short doc.
13037 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13038 @result{}  --too-wide
13039 @result{}          Short doc.
13040 m4_text_wrap([Super long documentation.], [     ],
13041              [  --too-wide ], 30)
13042 @result{}  --too-wide
13043 @result{}     Super long
13044 @result{}     documentation.
13045 @end example
13046 @end defmac
13048 @defmac m4_tolower (@var{string})
13049 @defmacx m4_toupper (@var{string})
13050 @msindex{tolower}
13051 @msindex{toupper}
13052 Return @var{string} with letters converted to upper or lower case,
13053 respectively.
13054 @end defmac
13056 @node Number processing Macros
13057 @subsection Arithmetic computation in M4
13059 The following macros facilitate integer arithmetic operations.
13060 Where a parameter is documented as taking an arithmetic expression, you
13061 can use anything that can be parsed by @code{m4_eval}.
13063 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13064 @msindex{cmp}
13065 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13066 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13067 equal, and @samp{1} if @var{expr-1} is larger.
13068 @end defmac
13070 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13071 @msindex{list_cmp}
13072 Compare the two M4 lists consisting of comma-separated arithmetic
13073 expressions, left to right.  Expand to @samp{-1} for the first element
13074 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13075 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13076 same values.  If one list is shorter than the other, the remaining
13077 elements of the longer list are compared against zero.
13078 @example
13079 m4_list_cmp([1, 0],       [1])
13080 @result{}0
13081 m4_list_cmp([1, [1 * 0]], [1, 0])
13082 @result{}0
13083 m4_list_cmp([1, 2],       [1, 0])
13084 @result{}1
13085 m4_list_cmp([1, [1+1], 3],[1, 2])
13086 @result{}1
13087 m4_list_cmp([1, 2, -3],   [1, 2])
13088 @result{}-1
13089 m4_list_cmp([1, 0],       [1, 2])
13090 @result{}-1
13091 m4_list_cmp([1],          [1, 2])
13092 @result{}-1
13093 @end example
13094 @end defmac
13096 @defmac m4_max (@var{arg}, @dots{})
13097 @msindex{max}
13098 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13099 of the maximum arithmetic expression among all the arguments.
13100 @end defmac
13102 @defmac m4_min (@var{arg}, @dots{})
13103 @msindex{min}
13104 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13105 of the minimum arithmetic expression among all the arguments.
13106 @end defmac
13108 @defmac m4_sign (@var{expr})
13109 @msindex{sign}
13110 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13111 @samp{1} if it is positive, and @samp{0} if it is zero.
13112 @end defmac
13114 @anchor{m4_version_compare}
13115 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13116 @msindex{version_compare}
13117 This macro was introduced in Autoconf 2.53, but had a number of
13118 usability limitations that were not lifted until Autoconf 2.62.  Compare
13119 the version strings @var{version-1} and @var{version-2}, and expand to
13120 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13121 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13122 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13123 element is a number along with optional case-insensitive letters
13124 designating beta releases.  The comparison stops at the leftmost element
13125 that contains a difference, although a 0 element compares equal to a
13126 missing element.
13128 It is permissible to include commit identifiers in @var{version}, such
13129 as an abbreviated SHA1 of the commit, provided there is still a
13130 monotonically increasing prefix to allow for accurate version-based
13131 comparisons.  For example, this paragraph was written when the
13132 development snapshot of autoconf claimed to be at version
13133 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13134 abbreviated commit identification of @samp{dc51}.
13136 @example
13137 m4_version_compare([1.1], [2.0])
13138 @result{}-1
13139 m4_version_compare([2.0b], [2.0a])
13140 @result{}1
13141 m4_version_compare([1.1.1], [1.1.1a])
13142 @result{}-1
13143 m4_version_compare([1.2], [1.1.1a])
13144 @result{}1
13145 m4_version_compare([1.0], [1])
13146 @result{}0
13147 m4_version_compare([1.1pre], [1.1PRE])
13148 @result{}0
13149 m4_version_compare([1.1a], [1,10])
13150 @result{}-1
13151 m4_version_compare([2.61a], [2.61a-248-dc51])
13152 @result{}-1
13153 m4_version_compare([2.61b], [2.61a-248-dc51])
13154 @result{}1
13155 @end example
13156 @end defmac
13158 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13159   @dvar{if-old, m4_fatal})
13160 @msindex{version_prereq}
13161 Compares @var{version} against the version of Autoconf currently
13162 running.  If the running version is at @var{version} or newer, expand
13163 @var{if-new-enough}, but if @var{version} is larger than the version
13164 currently executing, expand @var{if-old}, which defaults to printing an
13165 error message and exiting m4sugar with status 63.  When given only one
13166 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13167 Remember that the autoconf philosophy favors feature checks over version
13168 checks.
13169 @end defmac
13171 @node Set manipulation Macros
13172 @subsection Set manipulation in M4
13173 @cindex Set manipulation
13174 @cindex Data structure, set
13175 @cindex Unordered set manipulation
13177 Sometimes, it is necessary to track a set of data, where the order does
13178 not matter and where there are no duplicates in the set.  The following
13179 macros facilitate set manipulations.  Each set is an opaque object,
13180 which can only be accessed via these basic operations.  The underlying
13181 implementation guarantees linear scaling for set creation, which is more
13182 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13183 names and values can be arbitrary strings, except for unbalanced quotes.
13184 This implementation ties up memory for removed elements until the next
13185 operation that must traverse all the elements of a set; and although
13186 that may slow down some operations until the memory for removed elements
13187 is pruned, it still guarantees linear performance.
13189 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13190 @msindex{set_add}
13191 Adds the string @var{value} as a member of set @var{set}.  Expand
13192 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13193 previously in the set.  Operates in amortized constant time, so that set
13194 creation scales linearly.
13195 @end defmac
13197 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13198 @msindex{set_add_all}
13199 Adds each @var{value} to the set @var{set}.  This is slightly more
13200 efficient than repeatedly invoking @code{m4_set_add}.
13201 @end defmac
13203 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13204  @ovar{if-absent})
13205 @msindex{set_contains}
13206 Expands @var{if-present} if the string @var{value} is a member of
13207 @var{set}, otherwise @var{if-absent}.
13209 @example
13210 m4_set_contains([a], [1], [yes], [no])
13211 @result{}no
13212 m4_set_add([a], [1], [added], [dup])
13213 @result{}added
13214 m4_set_add([a], [1], [added], [dup])
13215 @result{}dup
13216 m4_set_contains([a], [1], [yes], [no])
13217 @result{}yes
13218 m4_set_remove([a], [1], [removed], [missing])
13219 @result{}removed
13220 m4_set_contains([a], [1], [yes], [no])
13221 @result{}no
13222 m4_set_remove([a], [1], [removed], [missing])
13223 @result{}missing
13224 @end example
13225 @end defmac
13227 @defmac m4_set_contents (@var{set}, @ovar{sep})
13228 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13229 @msindex{set_contents}
13230 @msindex{set_dump}
13231 Expands to a single string consisting of all the members of the set
13232 @var{set}, each separated by @var{sep}, which is not expanded.
13233 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13234 memory occupied by removed elements, while @code{m4_set_dump} is a
13235 faster one-shot action that also deletes the set.  No provision is made
13236 for disambiguating members that contain a non-empty @var{sep} as a
13237 substring; use @code{m4_set_empty} to distinguish between an empty set
13238 and the set containing only the empty string.  The order of the output
13239 is unspecified; in the current implementation, part of the speed of
13240 @code{m4_set_dump} results from using a different output order than
13241 @code{m4_set_contents}.  These macros scale linearly in the size of the
13242 set before memory pruning, and @code{m4_set_contents([@var{set}],
13243 [@var{sep}])} is faster than
13244 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13246 @example
13247 m4_set_add_all([a], [1], [2], [3])
13248 @result{}
13249 m4_set_contents([a], [-])
13250 @result{}1-2-3
13251 m4_joinall([-]m4_set_listc([a]))
13252 @result{}1-2-3
13253 m4_set_dump([a], [-])
13254 @result{}3-2-1
13255 m4_set_contents([a])
13256 @result{}
13257 m4_set_add([a], [])
13258 @result{}
13259 m4_set_contents([a], [-])
13260 @result{}
13261 @end example
13262 @end defmac
13264 @defmac m4_set_delete (@var{set})
13265 @msindex{set_delete}
13266 Delete all elements and memory associated with @var{set}.  This is
13267 linear in the set size, and faster than removing one element at a time.
13268 @end defmac
13270 @defmac m4_set_difference (@var{seta}, @var{setb})
13271 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13272 @defmacx m4_set_union (@var{seta}, @var{setb})
13273 @msindex{set_difference}
13274 @msindex{set_intersection}
13275 @msindex{set_union}
13276 Compute the relation between @var{seta} and @var{setb}, and output the
13277 result as a list of quoted arguments without duplicates and with a
13278 leading comma.  Set difference selects the elements in @var{seta} but
13279 not @var{setb}, intersection selects only elements in both sets, and
13280 union selects elements in either set.  These actions are linear in the
13281 sum of the set sizes.  The leading comma is necessary to distinguish
13282 between no elements and the empty string as the only element.
13284 @example
13285 m4_set_add_all([a], [1], [2], [3])
13286 @result{}
13287 m4_set_add_all([b], [3], [], [4])
13288 @result{}
13289 m4_set_difference([a], [b])
13290 @result{},1,2
13291 m4_set_difference([b], [a])
13292 @result{},,4
13293 m4_set_intersection([a], [b])
13294 @result{},3
13295 m4_set_union([a], [b])
13296 @result{},1,2,3,,4
13297 @end example
13298 @end defmac
13300 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13301 @msindex{set_empty}
13302 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13303 expand @var{if-elements}.  This macro operates in constant time.  Using
13304 this macro can help disambiguate output from @code{m4_set_contents} or
13305 @code{m4_set_list}.
13306 @end defmac
13308 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13309 @msindex{set_foreach}
13310 For each element in the set @var{set}, expand @var{action} with the
13311 macro @var{variable} defined as the set element.  Behavior is
13312 unspecified if @var{action} recursively lists the contents of @var{set}
13313 (although listing other sets is acceptable), or if it modifies the set
13314 in any way other than removing the element currently contained in
13315 @var{variable}.  This macro is faster than the corresponding
13316 @code{m4_foreach([@var{variable}],
13317 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13318 although @code{m4_set_map} might be faster still.
13320 @example
13321 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13322 @result{}
13323 m4_set_contents([a])
13324 @result{}12345
13325 m4_set_foreach([a], [i],
13326   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13327 @result{}24
13328 m4_set_contents([a])
13329 @result{}135
13330 @end example
13331 @end defmac
13333 @defmac m4_set_list (@var{set})
13334 @defmacx m4_set_listc (@var{set})
13335 @msindex{set_list}
13336 @msindex{set_listc}
13337 Produce a list of arguments, where each argument is a quoted element
13338 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13339 by adding a leading comma if there are any set elements, whereas the
13340 variant @code{m4_set_list} cannot distinguish between an empty set and a
13341 set containing only the empty string.  These can be directly used in
13342 macros that take multiple arguments, such as @code{m4_join} or
13343 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13344 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13345 memory occupied by removed elements is reclaimed during these macros.
13347 @example
13348 m4_set_add_all([a], [1], [2], [3])
13349 @result{}
13350 m4_set_list([a])
13351 @result{}1,2,3
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{}0
13360 m4_set_add([b], [])
13361 @result{}
13362 m4_set_list([b])
13363 @result{}
13364 m4_set_listc([b])
13365 @result{},
13366 m4_count(m4_set_list([b]))
13367 @result{}1
13368 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13369 @result{}1
13370 @end example
13371 @end defmac
13373 @defmac m4_set_map (@var{set}, @var{action})
13374 @msindex{set_map}
13375 For each element in the set @var{set}, expand @var{action} with a single
13376 argument of the set element.  Behavior is unspecified if @var{action}
13377 recursively lists the contents of @var{set} (although listing other sets
13378 is acceptable), or if it modifies the set in any way other than removing
13379 the element passed as an argument.  This macro is faster than either
13380 corresponding counterpart of
13381 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13382 @code{m4_set_foreach([@var{set}], [var],
13383 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13384 if more than one argument is needed for @var{action}, although it is
13385 more efficient to use @code{m4_set_map_sep} in that case.
13386 @end defmac
13388 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13389 @msindex{set_map_sep}
13390 For each element in the set @var{set}, expand
13391 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13392 between elements.  Behavior is unspecified if the expansion recursively
13393 lists the contents of @var{set} (although listing other sets
13394 is acceptable), or if it modifies the set in any way other than removing
13395 the element visited by the expansion.  This macro provides the most
13396 efficient means for non-destructively visiting the elements of a set; in
13397 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13398 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13399 @end defmac
13401 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13402  @ovar{if-absent})
13403 @msindex{set_remove}
13404 If @var{value} is an element in the set @var{set}, then remove it and
13405 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13406 operates in constant time so that multiple removals will scale linearly
13407 rather than quadratically; but when used outside of
13408 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13409 until the set is later
13410 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13411 other set operations are then less efficient between the time of element
13412 removal and subsequent memory compaction, but still maintain their
13413 guaranteed scaling performance.
13414 @end defmac
13416 @defmac m4_set_size (@var{set})
13417 @msindex{set_size}
13418 Expand to the size of the set @var{set}.  This implementation operates
13419 in constant time, and is thus more efficient than
13420 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13421 @end defmac
13424 @node Forbidden Patterns
13425 @subsection Forbidden Patterns
13426 @cindex Forbidden patterns
13427 @cindex Patterns, forbidden
13429 M4sugar provides a means to define suspicious patterns, patterns
13430 describing tokens which should not be found in the output.  For
13431 instance, if an Autoconf @file{configure} script includes tokens such as
13432 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13433 wrong (typically a macro was not evaluated because of overquotation).
13435 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13436 Additional layers, such as M4sh and Autoconf, add additional forbidden
13437 patterns to the list.
13439 @defmac m4_pattern_forbid (@var{pattern})
13440 @msindex{pattern_forbid}
13441 Declare that no token matching @var{pattern} must be found in the output.
13442 Comments are not checked; this can be a problem if, for instance, you
13443 have some macro left unexpanded after an @samp{#include}.  No consensus
13444 is currently found in the Autoconf community, as some people consider it
13445 should be valid to name macros in comments (which doesn't make sense to
13446 the authors of this documentation: input, such as macros, should be
13447 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13448 document the output).
13449 @end defmac
13451 Of course, you might encounter exceptions to these generic rules, for
13452 instance you might have to refer to @samp{$m4_flags}.
13454 @defmac m4_pattern_allow (@var{pattern})
13455 @msindex{pattern_allow}
13456 Any token matching @var{pattern} is allowed, including if it matches an
13457 @code{m4_pattern_forbid} pattern.
13458 @end defmac
13460 @node Debugging via autom4te
13461 @section Debugging via autom4te
13462 @cindex debugging tips
13463 @cindex autom4te debugging tips
13464 @cindex m4sugar debugging tips
13465 At times, it is desirable to see what was happening inside m4, to see
13466 why output was not matching expectations.  However, post-processing done
13467 by @command{autom4te} means that directly using the m4 builtin
13468 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13469 diversion changes and the concept of forbidden tokens make it difficult
13470 to use @code{m4_defn} to generate inline comments in the final output.
13472 There are a couple of tools to help with this.  One is the use of the
13473 @option{--trace} option provided by @command{autom4te} (as well as each
13474 of the programs that wrap @command{autom4te}, such as
13475 @command{autoconf}), in order to inspect when a macro is called and with
13476 which arguments.  For example, when this paragraph was written, the
13477 autoconf version could be found by:
13479 @example
13480 $ @kbd{autoconf --trace=AC_INIT}
13481 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13482 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13483 version is 2.63b.95-3963
13484 @end example
13486 Another trick is to print out the expansion of various m4 expressions to
13487 standard error or to an independent file, with no further m4 expansion,
13488 and without interfering with diversion changes or the post-processing
13489 done to standard output.  @code{m4_errprintn} shows a given expression
13490 on standard error.  For example, if you want to see the expansion of an
13491 autoconf primitive or of one of your autoconf macros, you can do it like
13492 this:
13494 @example
13495 $ @kbd{cat <<\EOF > configure.ac}
13496 AC_INIT
13497 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13498 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13499 AC_OUTPUT
13501 $ @kbd{autoconf}
13502 @error{}The definition of AC_DEFINE_UNQUOTED:
13503 @error{}_AC_DEFINE_Q([], $@@)
13504 @end example
13506 @node Programming in M4sh
13507 @chapter Programming in M4sh
13509 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13510 scripts.  This name was coined by Lars J. Aas, who notes that,
13511 according to the Webster's Revised Unabridged Dictionary (1913):
13513 @quotation
13514 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13515 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13517 @enumerate 1
13518 @item
13519 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13520 pressure@enddots{}
13522 @item
13523 A mixture of meal or bran and water fed to animals.
13525 @item
13526 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13527 @end enumerate
13528 @end quotation
13530 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13531 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13532 and environment variable namespace @samp{^as_}, and the here-document
13533 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13534 define your own macros or output shell code that conflicts with these
13535 namespaces.
13537 @menu
13538 * Common Shell Constructs::     Portability layer for common shell constructs
13539 * Polymorphic Variables::       Support for indirect variable names
13540 * Initialization Macros::       Macros to establish a sane shell environment
13541 * File Descriptor Macros::      File descriptor macros for input and output
13542 @end menu
13544 @node Common Shell Constructs
13545 @section Common Shell Constructs
13547 M4sh provides portable alternatives for some common shell constructs
13548 that unfortunately are not portable in practice.
13550 @c Deprecated, to be replaced by a better API
13551 @ignore
13552 @defmac AS_BASENAME (@var{file-name})
13553 @asindex{BASENAME}
13554 Output the non-directory portion of @var{file-name}.  For example,
13555 if @code{$file} is @samp{/one/two/three}, the command
13556 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13557 @end defmac
13558 @end ignore
13560 @defmac AS_BOX (@var{text}, @dvar{char, -})
13561 @asindex{BOX}
13562 Expand into shell code that will output @var{text} surrounded by a box
13563 with @var{char} in the top and bottom border.  @var{text} should not
13564 contain a newline, but may contain shell expansions valid for unquoted
13565 here-documents.  @var{char} defaults to @samp{-}, but can be any
13566 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13567 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13568 log files to separate distinct phases of script operation.
13569 @end defmac
13571 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13572   @dots{}, @ovar{default})
13573 @asindex{CASE}
13574 Expand into a shell @samp{case} statement, where @var{word} is matched
13575 against one or more patterns.  @var{if-matched} is run if the
13576 corresponding pattern matched @var{word}, else @var{default} is run.
13577 Avoids several portability issues (@pxref{case, , Limitations of Shell
13578 Builtins}).
13579 @end defmac
13581 @c Deprecated, to be replaced by a better API
13582 @defmac AS_DIRNAME (@var{file-name})
13583 @asindex{DIRNAME}
13584 Output the directory portion of @var{file-name}.  For example,
13585 if @code{$file} is @samp{/one/two/three}, the command
13586 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13588 This interface may be improved in the future to avoid forks and losing
13589 trailing newlines.
13590 @end defmac
13592 @defmac AS_ECHO (@var{word})
13593 @asindex{ECHO}
13594 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13595 must be a single shell word (typically a quoted string).  The bytes of
13596 @var{word} are output as-is, even if it starts with "-" or contains "\".
13597 Redirections can be placed outside the macro invocation.  This is much
13598 more portable than using @command{echo} (@pxref{echo, , Limitations of
13599 Shell Builtins}).
13600 @end defmac
13602 @defmac AS_ECHO_N (@var{word})
13603 @asindex{ECHO_N}
13604 Emits @var{word} to the standard output, without a following newline.
13605 @var{word} must be a single shell word (typically a quoted string) and,
13606 for portability, should not include more than one newline.  The bytes of
13607 @var{word} are output as-is, even if it starts with "-" or contains "\".
13608 Redirections can be placed outside the macro invocation.
13609 @end defmac
13611 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13612 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13613 @asindex{ESCAPE}
13614 Expands to @var{string}, with any characters in @var{chars} escaped with
13615 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13616 and only contain characters from the set @samp{`\"$}; however,
13617 characters may be safely listed more than once in @var{chars} for the
13618 sake of syntax highlighting editors.  The current implementation expands
13619 @var{string} after adding escapes; if @var{string} contains macro calls
13620 that in turn expand to text needing shell quoting, you can use
13621 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13623 The default for @var{chars} (@samp{\"$`}) is the set of characters
13624 needing escapes when @var{string} will be used literally within double
13625 quotes.  One common variant is the set of characters to protect when
13626 @var{string} will be used literally within back-ticks or an unquoted
13627 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13628 be used to form a double-quoted string containing the same expansions
13629 that would have occurred if @var{string} were expanded in an unquoted
13630 here-document; however, when using this variant, care must be taken that
13631 @var{string} does not use double quotes within complex variable
13632 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13633 with improper escapes.
13635 This macro is often used with @code{AS_ECHO}.  For an example, observe
13636 the output generated by the shell code generated from this snippet:
13638 @example
13639 foo=bar
13640 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13641 @result{}"$foo" = "bar"
13642 m4_define([macro], [a, [\b]])
13643 AS_ECHO(["AS_ESCAPE([[macro]])"])
13644 @result{}macro
13645 AS_ECHO(["AS_ESCAPE([macro])"])
13646 @result{}a, b
13647 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13648 @result{}a, \b
13649 @end example
13651 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13652 @comment the case of @var{string} that does not contain '.
13653 To escape a string that will be placed within single quotes, use:
13655 @example
13656 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13657 @end example
13658 @end defmac
13660 @defmac AS_EXIT (@dvar{status, $?})
13661 @asindex{EXIT}
13662 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13663 This macro
13664 works around shells that see the exit status of the command prior to
13665 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13666 of Shell Builtins}).
13667 @end defmac
13669 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13670 @asindex{IF}
13671 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13672 run shell code @var{run-if-true1}, else examine further tests.  If no test
13673 exits with a zero status, run shell code @var{run-if-false}, with
13674 simplifications if either @var{run-if-true1} or @var{run-if-false}
13675 is empty.  For example,
13677 @example
13678 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13679       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13680       [echo foo not specified])
13681 @end example
13683 @noindent
13684 ensures any required macros of @code{HANDLE_FOO}
13685 are expanded before the first test.
13686 @end defmac
13688 @defmac AS_MKDIR_P (@var{file-name})
13689 @asindex{MKDIR_P}
13690 Make the directory @var{file-name}, including intervening directories
13691 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13692 except that it is portable to older versions of @command{mkdir} that
13693 lack support for the @option{-p} option or for the @option{--}
13694 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13695 @code{AS_MKDIR_P}
13696 succeeds if @var{file-name} is a symbolic link to an existing directory,
13697 even though Posix is unclear whether @samp{mkdir -p} should
13698 succeed in that case.  If creation of @var{file-name} fails, exit the
13699 script.
13701 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13702 @end defmac
13704 @defmac AS_SET_STATUS (@var{status})
13705 @asindex{SET_STATUS}
13706 Emit shell code to set the value of @samp{$?} to @var{status}, as
13707 efficiently as possible.  However, this is not guaranteed to abort a
13708 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13709 Builtins}).  This should also be used at the end of a complex shell
13710 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13711 a DJGPP shell bug.
13712 @end defmac
13714 @defmac AS_TR_CPP (@var{expression})
13715 @asindex{TR_CPP}
13716 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13717 For example:
13719 @example
13720 # This outputs "#define HAVE_CHAR_P 1".
13721 # Notice the m4 quoting around #, to prevent an m4 comment
13722 type="char *"
13723 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13724 @end example
13725 @end defmac
13727 @defmac AS_TR_SH (@var{expression})
13728 @asindex{TR_SH}
13729 Transform @var{expression} into shell code that generates a valid shell
13730 variable name.  The result is literal when possible at m4 time, but must
13731 be used with @code{eval} if @var{expression} causes shell indirections.
13732 For example:
13734 @example
13735 # This outputs "Have it!".
13736 header="sys/some file.h"
13737 eval AS_TR_SH([HAVE_$header])=yes
13738 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13739 @end example
13740 @end defmac
13742 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13743 @asindex{SET_CATFILE}
13744 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13745 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13746 @var{file} is absolute, etc.).
13747 @end defmac
13749 @defmac AS_UNSET (@var{var})
13750 @asindex{UNSET}
13751 Unsets the shell variable @var{var}, working around bugs in older
13752 shells (@pxref{unset, , Limitations of Shell
13753 Builtins}).  @var{var} can be a literal or indirect variable name.
13754 @end defmac
13756 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13757   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13758 @asindex{VERSION_COMPARE}
13759 Compare two strings @var{version-1} and @var{version-2}, possibly
13760 containing shell variables, as version strings, and expand
13761 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13762 depending upon the result.
13763 The algorithm to compare is similar to the one used by strverscmp in
13764 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13765 The GNU C Library}).
13766 @end defmac
13768 @node Polymorphic Variables
13769 @section Support for indirect variable names
13770 @cindex variable name indirection
13771 @cindex polymorphic variable name
13772 @cindex indirection, variable name
13774 Often, it is convenient to write a macro that will emit shell code
13775 operating on a shell variable.  The simplest case is when the variable
13776 name is known.  But a more powerful idiom is writing shell code that can
13777 work through an indirection, where another variable or command
13778 substitution produces the name of the variable to actually manipulate.
13779 M4sh supports the notion of polymorphic shell variables, making it easy
13780 to write a macro that can deal with either literal or indirect variable
13781 names and output shell code appropriate for both use cases.  Behavior is
13782 undefined if expansion of an indirect variable does not result in a
13783 literal variable name.
13785 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13786   @dvar{if-simple-ref, @var{if-not}})
13787 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13788   @ovar{if-not}, @dvar{if-simple-ref, @var{if-not}})
13789 @asindex{LITERAL_IF}
13790 @asindex{LITERAL_WORD_IF}
13791 If the expansion of @var{expression} is definitely a shell literal,
13792 expand @var{if-literal}.  If the expansion of @var{expression} looks
13793 like it might contain shell indirections (such as @code{$var} or
13794 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13795 possible to output optimized code if @var{expression} consists only of
13796 shell variable expansions (such as @code{$@{var@}}), in which case
13797 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13798 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13799 @var{if-literal} if @var{expression} looks like a single shell word,
13800 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13801 in @var{expression}.
13803 In order to reduce the time spent recognizing whether an
13804 @var{expression} qualifies as a literal or a simple indirection, the
13805 implementation is somewhat conservative: @var{expression} must be a
13806 single shell word (possibly after stripping whitespace), consisting only
13807 of bytes that would have the same meaning whether unquoted or enclosed
13808 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13809 even though it is not a valid shell variable name; while both @samp{'a'}
13810 and @samp{[$]} result in @var{if-not}, because they behave differently
13811 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13812 for recognizing portable file names (such as in the implementation of
13813 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13814 valid variable names (such as in the implementation of @code{AS_TR_SH},
13815 which uses an additional @code{m4_translit} to convert @samp{.} to
13816 @samp{_}).
13818 This example shows how to read the contents of the shell variable
13819 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13820 results in a script that will output the line @samp{hello} three times.
13822 @example
13823 AC_DEFUN([MY_ACTION],
13824 [AS_LITERAL_IF([$1],
13825   [echo "$$1"],
13826 @c $$
13827   [AS_VAR_COPY([var], [$1])
13828    echo "$var"],
13829   [eval 'echo "$'"$1"\"])])
13830 foo=bar bar=hello
13831 MY_ACTION([bar])
13832 MY_ACTION([`echo bar`])
13833 MY_ACTION([$foo])
13834 @end example
13835 @end defmac
13837 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13838 @asindex{VAR_APPEND}
13839 Emit shell code to append the shell expansion of @var{text} to the end
13840 of the current contents of the polymorphic shell variable @var{var},
13841 taking advantage of shells that provide the @samp{+=} extension for more
13842 efficient scaling.
13844 For situations where the final contents of @var{var} are relatively
13845 short (less than 256 bytes), it is more efficient to use the simpler
13846 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13847 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13848 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13849 when the script will be repeatedly appending text into @code{var},
13850 issues of scaling start to become apparent.  A naive implementation
13851 requires execution time linear to the length of the current contents of
13852 @var{var} as well as the length of @var{text} for a single append, for
13853 an overall quadratic scaling with multiple appends.  This macro takes
13854 advantage of shells which provide the extension
13855 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13856 for a single append, for an overall linear scaling with multiple
13857 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13858 @var{text} be quoted properly to avoid field splitting and file name
13859 expansion.
13860 @end defmac
13862 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13863 @asindex{VAR_ARITH}
13864 Emit shell code to compute the arithmetic expansion of @var{expression},
13865 assigning the result as the contents of the polymorphic shell variable
13866 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13867 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13868 syntax for a valid @var{expression} is rather limited: all operators
13869 must occur as separate shell arguments and with proper quoting, there is
13870 no portable equality operator, all variables containing numeric values
13871 must be expanded prior to the computation, all numeric values must be
13872 provided in decimal without leading zeroes, and the first shell argument
13873 should not be a negative number.  In the following example, this snippet
13874 will print @samp{(2+3)*4 == 20}.
13876 @example
13877 bar=3
13878 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13879 echo "(2+$bar)*4 == $foo"
13880 @end example
13881 @end defmac
13883 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13884 @asindex{VAR_COPY}
13885 Emit shell code to assign the contents of the polymorphic shell variable
13886 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13887 executing this M4sh snippet will output @samp{bar hi}:
13889 @example
13890 foo=bar bar=hi
13891 AS_VAR_COPY([a], [foo])
13892 AS_VAR_COPY([b], [$foo])
13893 echo "$a $b"
13894 @end example
13896 When it is necessary to access the contents of an indirect variable
13897 inside a shell double-quoted context, the recommended idiom is to first
13898 copy the contents into a temporary literal shell variable.
13900 @smallexample
13901 for header in stdint_h inttypes_h ; do
13902   AS_VAR_COPY([var], [ac_cv_header_$header])
13903   echo "$header detected: $var"
13904 done
13905 @end smallexample
13906 @end defmac
13908 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13909 @comment trailing newlines uniformly, and forks too much.
13911 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13912   @ovar{if-not-equal})
13913 @asindex{VAR_IF}
13914 Output a shell conditional statement.  If the contents of the
13915 polymorphic shell variable @var{var} match the string @var{word},
13916 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13917 must be a single shell word (typically a quoted string).  Avoids
13918 shell bugs if an interrupt signal arrives while a command substitution
13919 in @var{var} is being expanded.
13920 @end defmac
13922 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13923 @defmacx AS_VAR_POPDEF (@var{m4-name})
13924 @asindex{VAR_PUSHDEF}
13925 @asindex{VAR_POPDEF}
13926 @cindex composing variable names
13927 @cindex variable names, composing
13928 A common M4sh idiom involves composing shell variable names from an m4
13929 argument (for example, writing a macro that uses a cache variable).
13930 @var{value} can be an arbitrary string, which will be transliterated
13931 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13932 composed variable name based on @var{value}, it is easier to declare a
13933 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13934 that macro as the argument to subsequent @code{AS_VAR} macros as a
13935 polymorphic variable name, and finally free the temporary macro with
13936 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13937 to avoid excess newlines in the output.
13939 Here is an involved example, that shows the power of writing macros that
13940 can handle composed shell variable names:
13942 @example
13943 m4_define([MY_CHECK_HEADER],
13944 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13945 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13946 AS_VAR_POPDEF([my_Header])dnl
13948 MY_CHECK_HEADER([stdint.h])
13949 for header in inttypes.h stdlib.h ; do
13950   MY_CHECK_HEADER([$header])
13951 done
13952 @end example
13954 @noindent
13955 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13956 variable names.  In the first invocation, the m4 argument is
13957 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13958 As a result, the temporary macro @code{my_Header} expands to the literal
13959 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13960 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13961 temporary macro @code{my_Header} expands to the indirect shell name
13962 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13963 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13964 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13965 platform where all three headers have been previously detected, the
13966 output of the script will include:
13968 @smallexample
13969 header stdint.h detected
13970 header inttypes.h detected
13971 header stdlib.h detected
13972 @end smallexample
13973 @end defmac
13975 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13976 @asindex{VAR_SET}
13977 Emit shell code to assign the contents of the polymorphic shell variable
13978 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13979 subject to field splitting or file name expansion, so if command
13980 substitution is used, it may be done with @samp{`""`} rather than using
13981 an intermediate variable (@pxref{Shell Substitutions}).  However,
13982 @var{value} does undergo rescanning for additional macro names; behavior
13983 is unspecified if late expansion results in any shell meta-characters.
13984 @end defmac
13986 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13987 @asindex{VAR_SET_IF}
13988 Emit a shell conditional statement, which executes @var{if-set} if the
13989 polymorphic shell variable @code{var} is set to any value, and
13990 @var{if-undef} otherwise.
13991 @end defmac
13993 @defmac AS_VAR_TEST_SET (@var{var})
13994 @asindex{VAR_TEST_SET}
13995 Emit a shell statement that results in a successful exit status only if
13996 the polymorphic shell variable @code{var} is set.
13997 @end defmac
13999 @node Initialization Macros
14000 @section Initialization Macros
14002 @defmac AS_BOURNE_COMPATIBLE
14003 @asindex{BOURNE_COMPATIBLE}
14004 Set up the shell to be more compatible with the Bourne shell as
14005 standardized by Posix, if possible.  This may involve setting
14006 environment variables, or setting options, or similar
14007 implementation-specific actions.  This macro is deprecated, since
14008 @code{AS_INIT} already invokes it.
14009 @end defmac
14011 @defmac AS_INIT
14012 @asindex{INIT}
14013 @evindex LC_ALL
14014 @evindex SHELL
14015 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14016 outputs the @code{#! /bin/sh} line, a notice about where the output was
14017 generated from, and code to sanitize the environment for the rest of the
14018 script.  Among other initializations, this sets @env{SHELL} to the shell
14019 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14020 ensure the C locale.  Finally, it changes the current diversion to
14021 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14022 and @code{AT_INIT}, so shell code in @file{configure},
14023 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14024 shell environment.
14025 @end defmac
14027 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14028 @asindex{INIT_GENERATED}
14029 Emit shell code to start the creation of a subsidiary shell script in
14030 @var{file}, including changing @var{file} to be executable.  This macro
14031 populates the child script with information learned from the parent
14032 (thus, the emitted code is equivalent in effect, but more efficient,
14033 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14034 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14035 beginning of the child, prior to the shell initialization code, and is
14036 subject to parameter expansion, command substitution, and backslash
14037 quote removal.  The
14038 parent script should check the exit status after this macro, in case
14039 @var{file} could not be properly created (for example, if the disk was
14040 full).  If successfully created, the parent script can then proceed to
14041 append additional M4sh constructs into the child script.
14043 Note that the child script starts life without a log file open, so if
14044 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14045 must temporarily disable any attempts to use the log file until after
14046 emitting code to open a log within the child.  On the other hand, if the
14047 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14048 @samp{1}, then the child script already has code that copies stdout to
14049 that descriptor.  Currently, the suggested
14050 idiom for writing a M4sh shell script from within another script is:
14052 @example
14053 AS_INIT_GENERATED([@var{file}], [[# My child script.
14054 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14055 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14056 cat >> "@var{file}" <<\__EOF__
14057 # Code to initialize AS_MESSAGE_LOG_FD
14058 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14059 # Additional code
14060 __EOF__
14061 @end example
14063 This, however, may change in the future as the M4sh interface is
14064 stabilized further.
14066 Also, be aware that use of @env{LINENO} within the child script may
14067 report line numbers relative to their location in the parent script,
14068 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14069 unable to locate a shell with working @env{LINENO} support.
14070 @end defmac
14072 @defmac AS_LINENO_PREPARE
14073 @asindex{LINENO_PREPARE}
14074 @evindex LINENO
14075 Find a shell that supports the special variable @env{LINENO}, which
14076 contains the number of the currently executing line.  This macro is
14077 automatically invoked by @code{AC_INIT} in configure scripts.
14078 @end defmac
14080 @defmac AS_ME_PREPARE
14081 @asindex{ME_PREPARE}
14082 Set up variable @env{as_me} to be the basename of the currently executing
14083 script.  This macro is automatically invoked by @code{AC_INIT} in
14084 configure scripts.
14085 @end defmac
14087 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14088 @asindex{TMPDIR}
14089 @evindex TMPDIR
14090 @ovindex tmp
14091 Create, as safely as possible, a temporary sub-directory within
14092 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14093 be 2-4 characters, to make it slightly easier to identify the owner of
14094 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14095 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14096 newly created directory is stored in the shell variable @code{tmp}.  On
14097 error, the script is aborted.
14099 Typically, this macro is coupled with some exit traps to delete the created
14100 directory and its contents on exit or interrupt.  However, there is a
14101 slight window between when the directory is created and when the name is
14102 actually known to the shell, so an interrupt at the right moment might
14103 leave the temporary directory behind.  Hence it is important to use a
14104 @var{prefix} that makes it easier to determine if a leftover temporary
14105 directory from an interrupted script is safe to delete.
14107 The use of the output variable @samp{$tmp} rather than something in the
14108 @samp{as_} namespace is historical; it has the unfortunate consequence
14109 that reusing this otherwise common name for any other purpose inside
14110 your script has the potential to break any cleanup traps designed to
14111 remove the temporary directory.
14112 @end defmac
14114 @defmac AS_SHELL_SANITIZE
14115 @asindex{SHELL_SANITIZE}
14116 Initialize the shell suitably for @command{configure} scripts.  This has
14117 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14118 environment variables for predictable results from configuration tests.
14119 For example, it sets @env{LC_ALL} to change to the default C locale.
14120 @xref{Special Shell Variables}.  This macro is deprecated, since
14121 @code{AS_INIT} already invokes it.
14122 @end defmac
14125 @node File Descriptor Macros
14126 @section File Descriptor Macros
14127 @cindex input
14128 @cindex standard input
14129 @cindex file descriptors
14130 @cindex descriptors
14131 @cindex low-level output
14132 @cindex output, low-level
14134 The following macros define file descriptors used to output messages
14135 (or input values) from @file{configure} scripts.
14136 For example:
14138 @example
14139 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14140 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14141 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14142 @end example
14144 @noindent
14145 However doing so is seldom needed, because Autoconf provides higher
14146 level macros as described below.
14148 @defmac AS_MESSAGE_FD
14149 @asindex{MESSAGE_FD}
14150 The file descriptor for @samp{checking for...}  messages and results.
14151 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14152 clients.  However, @code{AC_INIT} shuffles things around to another file
14153 descriptor, in order to allow the @option{-q} option of
14154 @command{configure} to choose whether messages should go to the script's
14155 standard output or be discarded.
14157 If you want to display some messages, consider using one of the printing
14158 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14159 via these macros are also recorded in @file{config.log}.
14160 @end defmac
14162 @anchor{AS_MESSAGE_LOG_FD}
14163 @defmac AS_MESSAGE_LOG_FD
14164 @asindex{MESSAGE_LOG_FD}
14165 This must either be empty, or expand to a file descriptor for log
14166 messages.  By default, @code{AS_INIT} sets this macro to the empty
14167 string for standalone M4sh clients, thus disabling logging.  However,
14168 @code{AC_INIT} shuffles things around so that both @command{configure}
14169 and @command{config.status} use @file{config.log} for log messages.
14170 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14171 Compiler}), redirect all output to this descriptor.  You may want to do
14172 so if you develop such a low-level macro.
14173 @end defmac
14175 @defmac AS_ORIGINAL_STDIN_FD
14176 @asindex{ORIGINAL_STDIN_FD}
14177 This must expand to a file descriptor for the original standard input.
14178 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14179 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14180 safety.
14182 When @command{configure} runs, it may accidentally execute an
14183 interactive command that has the same name as the non-interactive meant
14184 to be used or checked.  If the standard input was the terminal, such
14185 interactive programs would cause @command{configure} to stop, pending
14186 some user input.  Therefore @command{configure} redirects its standard
14187 input from @file{/dev/null} during its initialization.  This is not
14188 normally a problem, since @command{configure} normally does not need
14189 user input.
14191 In the extreme case where your @file{configure} script really needs to
14192 obtain some values from the original standard input, you can read them
14193 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14194 @end defmac
14197 @c =================================================== Writing Autoconf Macros.
14199 @node Writing Autoconf Macros
14200 @chapter Writing Autoconf Macros
14202 When you write a feature test that could be applicable to more than one
14203 software package, the best thing to do is encapsulate it in a new macro.
14204 Here are some instructions and guidelines for writing Autoconf macros.
14206 @menu
14207 * Macro Definitions::           Basic format of an Autoconf macro
14208 * Macro Names::                 What to call your new macros
14209 * Reporting Messages::          Notifying @command{autoconf} users
14210 * Dependencies Between Macros::  What to do when macros depend on other macros
14211 * Obsoleting Macros::           Warning about old ways of doing things
14212 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14213 @end menu
14215 @node Macro Definitions
14216 @section Macro Definitions
14218 @defmac AC_DEFUN (@var{name}, @ovar{body})
14219 @acindex{DEFUN}
14220 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14221 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14222 named @var{name} and with @var{body} as its expansion.  In addition to
14223 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14224 constrain the order in which macros are called, while avoiding redundant
14225 output (@pxref{Prerequisite Macros}).
14226 @end defmac
14228 An Autoconf macro definition looks like this:
14230 @example
14231 AC_DEFUN(@var{macro-name}, @var{macro-body})
14232 @end example
14234 You can refer to any arguments passed to the macro as @samp{$1},
14235 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
14236 GNU M4}, for more complete information on writing M4 macros.
14238 Most macros fall in one of two general categories.  The first category
14239 includes macros which take arguments, in order to generate output
14240 parameterized by those arguments.  Macros in this category are designed
14241 to be directly expanded, often multiple times, and should not be used as
14242 the argument to @code{AC_REQUIRE}.  The other category includes macros
14243 which are shorthand for a fixed block of text, and therefore do not take
14244 arguments.  For this category of macros, directly expanding the macro
14245 multiple times results in redundant output, so it is more common to use
14246 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14247 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14249 Be sure to properly quote both the @var{macro-body} @emph{and} the
14250 @var{macro-name} to avoid any problems if the macro happens to have
14251 been previously defined.
14253 Each macro should have a header comment that gives its prototype, and a
14254 brief description.  When arguments have default values, display them in
14255 the prototype.  For example:
14257 @example
14258 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14259 # --------------------------------------
14260 m4_define([AC_MSG_ERROR],
14261   [@{ AS_MESSAGE([error: $1], [2])
14262      exit m4_default([$2], [1]); @}])
14263 @end example
14265 Comments about the macro should be left in the header comment.  Most
14266 other comments make their way into @file{configure}, so just keep
14267 using @samp{#} to introduce comments.
14269 @cindex @code{dnl}
14270 If you have some special comments about pure M4 code, comments
14271 that make no sense in @file{configure} and in the header comment, then
14272 use the builtin @code{dnl}: it causes M4 to discard the text
14273 through the next newline.
14275 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14276 @code{dnl} is more useful to get rid of the newlines following macros
14277 that produce no output, such as @code{AC_REQUIRE}.
14279 Public third-party macros need to use @code{AC_DEFUN}, and not
14280 @code{m4_define}, in order to be found by @command{aclocal}
14281 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14282 Additionally, if it is ever determined that a macro should be made
14283 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14284 in order to have @command{autoupdate} assist the user in choosing a
14285 better alternative, but there is no corresponding way to make
14286 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14288 There is another subtle, but important, difference between using
14289 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14290 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14291 block of text with a @code{m4_define} macro that will expand to the same
14292 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14293 the same content does not necessarily give the same results, because it
14294 changes the location where any embedded but unsatisfied
14295 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14296 example of this, see @ref{Expanded Before Required}.
14298 @node Macro Names
14299 @section Macro Names
14301 All of the public Autoconf macros have all-uppercase names in the
14302 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14303 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14304 internal macros.  All shell variables that they use for internal
14305 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14306 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14307 @command{configure}, files produced by Autoconf make heavy use of the
14308 file system namespace @samp{^conf}.
14310 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14311 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14312 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14313 @file{configure.ac} is also designed to be scanned by Autoheader,
14314 Autoscan, Autoupdate, and Automake, you should be aware of the
14315 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14316 the namespace of a package that does not own the macro or shell code you
14317 are writing.
14319 To ensure that your macros don't conflict with present or future
14320 Autoconf macros, you should prefix your own macro names and any shell
14321 variables they use with some other sequence.  Possibilities include your
14322 initials, or an abbreviation for the name of your organization or
14323 software package.  Historically, people have not always followed the
14324 rule of using a namespace appropriate for their package, and this has
14325 made it difficult for determining the origin of a macro (and where to
14326 report bugs about that macro), as well as difficult for the true
14327 namespace owner to add new macros without interference from pre-existing
14328 uses of third-party macros.  Perhaps the best example of this confusion
14329 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14330 to Gettext.
14332 Most of the Autoconf macros' names follow a structured naming convention
14333 that indicates the kind of feature check by the name.  The macro names
14334 consist of several words, separated by underscores, going from most
14335 general to most specific.  The names of their cache variables use the
14336 same convention (@pxref{Cache Variable Names}, for more information on
14337 them).
14339 The first word of the name after the namespace initials (such as
14340 @samp{AC_}) usually tells the category
14341 of the feature being tested.  Here are the categories used in Autoconf for
14342 specific test macros, the kind of macro that you are more likely to
14343 write.  They are also used for cache variables, in all-lowercase.  Use
14344 them where applicable; where they're not, invent your own categories.
14346 @table @code
14347 @item C
14348 C language builtin features.
14349 @item DECL
14350 Declarations of C variables in header files.
14351 @item FUNC
14352 Functions in libraries.
14353 @item GROUP
14354 Posix group owners of files.
14355 @item HEADER
14356 Header files.
14357 @item LIB
14358 C libraries.
14359 @item PROG
14360 The base names of programs.
14361 @item MEMBER
14362 Members of aggregates.
14363 @item SYS
14364 Operating system features.
14365 @item TYPE
14366 C builtin or declared types.
14367 @item VAR
14368 C variables in libraries.
14369 @end table
14371 After the category comes the name of the particular feature being
14372 tested.  Any further words in the macro name indicate particular aspects
14373 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
14374 C compiler supports ISO Standard C.
14376 An internal macro should have a name that starts with an underscore;
14377 Autoconf internals should therefore start with @samp{_AC_}.
14378 Additionally, a macro that is an internal subroutine of another macro
14379 should have a name that starts with an underscore and the name of that
14380 other macro, followed by one or more words saying what the internal
14381 macro does.  For example, @code{AC_PATH_X} has internal macros
14382 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14384 @node Reporting Messages
14385 @section Reporting Messages
14386 @cindex Messages, from @command{autoconf}
14388 When macros statically diagnose abnormal situations, benign or fatal, it
14389 is possible to make @command{autoconf} detect the problem, and refuse to
14390 create @file{configure} in the case of an error.  The macros in this
14391 section are considered obsolescent, and new code should use M4sugar
14392 macros for this purpose, see @ref{Diagnostic Macros}.
14394 On the other hand, it is possible to want to detect errors when
14395 @command{configure} is run, which are dependent on the environment of
14396 the user rather than the maintainer.  For dynamic diagnostics, see
14397 @ref{Printing Messages}.
14399 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14400 @acindex{DIAGNOSE}
14401 Report @var{message} as a warning (or as an error if requested by the
14402 user) if warnings of the @var{category} are turned on.  This macro is
14403 obsolescent; you are encouraged to use:
14404 @example
14405 m4_warn([@var{category}], [@var{message}])
14406 @end example
14407 @noindent
14408 instead.  @xref{m4_warn}, for more details, including valid
14409 @var{category} names.
14410 @end defmac
14412 @defmac AC_WARNING (@var{message})
14413 @acindex{WARNING}
14414 Report @var{message} as a syntax warning.  This macro is obsolescent;
14415 you are encouraged to use:
14416 @example
14417 m4_warn([syntax], [@var{message}])
14418 @end example
14419 @noindent
14420 instead.  @xref{m4_warn}, for more details, as well as better
14421 finer-grained categories of warnings (not all problems have to do with
14422 syntax).
14423 @end defmac
14425 @defmac AC_FATAL (@var{message})
14426 @acindex{FATAL}
14427 Report a severe error @var{message}, and have @command{autoconf} die.
14428 This macro is obsolescent; you are encouraged to use:
14429 @example
14430 m4_fatal([@var{message}])
14431 @end example
14432 @noindent
14433 instead.  @xref{m4_fatal}, for more details.
14434 @end defmac
14436 When the user runs @samp{autoconf -W error}, warnings from
14437 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14438 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14440 @node Dependencies Between Macros
14441 @section Dependencies Between Macros
14442 @cindex Dependencies between macros
14444 Some Autoconf macros depend on other macros having been called first in
14445 order to work correctly.  Autoconf provides a way to ensure that certain
14446 macros are called if needed and a way to warn the user if macros are
14447 called in an order that might cause incorrect operation.
14449 @menu
14450 * Prerequisite Macros::         Ensuring required information
14451 * Suggested Ordering::          Warning about possible ordering problems
14452 * One-Shot Macros::             Ensuring a macro is called only once
14453 @end menu
14455 @node Prerequisite Macros
14456 @subsection Prerequisite Macros
14457 @cindex Prerequisite macros
14458 @cindex Macros, prerequisites
14460 A macro that you write might need to use values that have previously
14461 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14462 examines the output of @code{flex} or @code{lex}, so it depends on
14463 @code{AC_PROG_LEX} having been called first to set the shell variable
14464 @code{LEX}.
14466 Rather than forcing the user of the macros to keep track of the
14467 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14468 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14469 called if it is needed, and only called once.
14471 @defmac AC_REQUIRE (@var{macro-name})
14472 @acindex{REQUIRE}
14473 If the M4 macro @var{macro-name} has not already been called, call it
14474 (without any arguments).  Make sure to quote @var{macro-name} with
14475 square brackets.  @var{macro-name} must have been defined using
14476 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14477 that it has been called.
14479 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14480 must not be called from the top level.  Also, it does not make sense to
14481 require a macro that takes parameters.
14482 @end defmac
14484 @code{AC_REQUIRE} is often misunderstood.  It really implements
14485 dependencies between macros in the sense that if one macro depends upon
14486 another, the latter is expanded @emph{before} the body of the
14487 former.  To be more precise, the required macro is expanded before
14488 the outermost defined macro in the current expansion stack.
14489 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14490 @code{FOO}.  For instance, this definition of macros:
14492 @example
14493 @group
14494 AC_DEFUN([TRAVOLTA],
14495 [test "$body_temperature_in_celsius" -gt "38" &&
14496   dance_floor=occupied])
14497 AC_DEFUN([NEWTON_JOHN],
14498 [test "x$hair_style" = xcurly &&
14499   dance_floor=occupied])
14500 @end group
14502 @group
14503 AC_DEFUN([RESERVE_DANCE_FLOOR],
14504 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14505   AC_REQUIRE([TRAVOLTA])
14506   AC_REQUIRE([NEWTON_JOHN])
14507 fi])
14508 @end group
14509 @end example
14511 @noindent
14512 with this @file{configure.ac}
14514 @example
14515 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14516 RESERVE_DANCE_FLOOR
14517 if test "x$dance_floor" = xoccupied; then
14518   AC_MSG_ERROR([cannot pick up here, let's move])
14520 @end example
14522 @noindent
14523 does not leave you with a better chance to meet a kindred soul at
14524 other times than Saturday night since it expands into:
14526 @example
14527 @group
14528 test "$body_temperature_in_Celsius" -gt "38" &&
14529   dance_floor=occupied
14530 test "x$hair_style" = xcurly &&
14531   dance_floor=occupied
14533 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14537 @end group
14538 @end example
14540 This behavior was chosen on purpose: (i) it prevents messages in
14541 required macros from interrupting the messages in the requiring macros;
14542 (ii) it avoids bad surprises when shell conditionals are used, as in:
14544 @example
14545 @group
14546 if @dots{}; then
14547   AC_REQUIRE([SOME_CHECK])
14549 @dots{}
14550 SOME_CHECK
14551 @end group
14552 @end example
14554 However, this implementation can lead to another class of problems.
14555 Consider the case where an outer macro first expands, then indirectly
14556 requires, an inner macro:
14558 @example
14559 AC_DEFUN([TESTA], [[echo in A
14560 if test -n "$SEEN_A" ; then echo duplicate ; fi
14561 SEEN_A=:]])
14562 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14563 if test -z "$SEEN_A" ; then echo bug ; fi]])
14564 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14565 AC_DEFUN([OUTER], [[echo in OUTER]
14566 TESTA
14567 TESTC])
14568 OUTER
14569 @end example
14571 @noindent
14572 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14573 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14574 of @code{OUTER}, but because @code{TESTA} had already been directly
14575 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14576 @code{TESTB} occurs prior to its prerequisites, leading to the following
14577 output:
14579 @example
14580 in B
14582 in OUTER
14583 in A
14584 in C
14585 @end example
14587 @noindent
14588 Newer Autoconf is smart enough to recognize this situation, and hoists
14589 @code{TESTA} even though it has already been expanded, but issues a
14590 syntax warning in the process.  This is because the hoisted expansion of
14591 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14592 redundant code, and causes its own set of problems if the hoisted macro
14593 is not idempotent:
14595 @example
14596 in A
14597 in B
14598 in OUTER
14599 in A
14600 duplicate
14601 in C
14602 @end example
14604 The bug is not in Autoconf, but in the macro definitions.  If you ever
14605 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14606 that the macro only needs to be expanded once.  But to enforce this,
14607 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14608 this only helps in Autoconf 2.64 or newer), or all
14609 uses of that macro should be through @code{AC_REQUIRE}; directly
14610 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14611 eliminate redundant expansion.  In the example, this rule of thumb was
14612 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14613 directly expands it.  One way of fixing the bug is to factor
14614 @code{TESTA} into two macros, the portion designed for direct and
14615 repeated use (here, named @code{TESTA}), and the portion designed for
14616 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14617 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14618 calling convention according to their needs:
14620 @example
14621 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14622 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14623 if test -n "$SEEN_A" ; then echo duplicate ; fi
14624 SEEN_A=:]])
14625 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14626 if test -z "$SEEN_A" ; then echo bug ; fi]])
14627 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14628 AC_DEFUN([OUTER], [[echo in OUTER]
14629 TESTA
14630 TESTC])
14631 OUTER
14632 @end example
14634 @noindent
14635 the resulting output will then obey all dependency rules and avoid any
14636 syntax warnings, whether the script is built with old or new Autoconf
14637 versions:
14639 @example
14640 in A_PREREQ
14641 in B
14642 in OUTER
14643 in A
14644 in C
14645 @end example
14647 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14648 enforce expansion of required macros outside of shell conditional
14649 constructs.  You are furthermore encouraged, although not required, to
14650 put all @code{AC_REQUIRE} calls
14651 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14652 lines they leave.
14654 @node Suggested Ordering
14655 @subsection Suggested Ordering
14656 @cindex Macros, ordering
14657 @cindex Ordering macros
14659 Some macros should be run before another macro if both are called, but
14660 neither @emph{requires} that the other be called.  For example, a macro
14661 that changes the behavior of the C compiler should be called before any
14662 macros that run the C compiler.  Many of these dependencies are noted in
14663 the documentation.
14665 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14666 with this kind of dependency appear out of order in a
14667 @file{configure.ac} file.  The warning occurs when creating
14668 @command{configure} from @file{configure.ac}, not when running
14669 @command{configure}.
14671 For example, @code{AC_PROG_CPP} checks whether the C compiler
14672 can run the C preprocessor when given the @option{-E} option.  It should
14673 therefore be called after any macros that change which C compiler is
14674 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14676 @example
14677 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14678 @end example
14680 @noindent
14681 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14682 when @code{AC_PROG_CC} is called.
14684 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14685 @acindex{BEFORE}
14686 Make M4 print a warning message to the standard error output if
14687 @var{called-macro-name} has already been called.  @var{this-macro-name}
14688 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14689 macro @var{called-macro-name} must have been defined using
14690 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14691 that it has been called.
14692 @end defmac
14694 @node One-Shot Macros
14695 @subsection One-Shot Macros
14696 @cindex One-shot macros
14697 @cindex Macros, called once
14699 Some macros should be called only once, either because calling them
14700 multiple time is unsafe, or because it is bad style.  For instance
14701 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14702 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14703 sense to run these expensive checks more than once.  Such one-shot
14704 macros can be defined using @code{AC_DEFUN_ONCE}.
14706 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14707 @acindex{DEFUN_ONCE}
14708 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14709 Definitions}), but add additional logic that guarantees that only the
14710 first use of the macro (whether by direct expansion or
14711 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14712 expansion will occur before the start of any enclosing macro defined by
14713 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14714 Generally, it does not make sense for @var{macro-body} to use parameters
14715 such as @code{$1}.
14716 @end defmac
14718 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14719 emit a warning if it was directly expanded a second time, so for
14720 portability, it is better to use @code{AC_REQUIRE} than direct
14721 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14722 (@pxref{Prerequisite Macros}).
14724 @node Obsoleting Macros
14725 @section Obsoleting Macros
14726 @cindex Obsoleting macros
14727 @cindex Macros, obsoleting
14729 Configuration and portability technology has evolved over the years.
14730 Often better ways of solving a particular problem are developed, or
14731 ad-hoc approaches are systematized.  This process has occurred in many
14732 parts of Autoconf.  One result is that some of the macros are now
14733 considered @dfn{obsolete}; they still work, but are no longer considered
14734 the best thing to do, hence they should be replaced with more modern
14735 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14736 with their modern implementation.
14738 Autoconf provides a simple means to obsolete a macro.
14740 @anchor{AU_DEFUN}
14741 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14742 @auindex{DEFUN}
14743 Define @var{old-macro} as @var{implementation}.  The only difference
14744 with @code{AC_DEFUN} is that the user is warned that
14745 @var{old-macro} is now obsolete.
14747 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14748 replaced by the modern @var{implementation}.  @var{message} should
14749 include information on what to do after running @command{autoupdate};
14750 @command{autoupdate} prints it as a warning, and includes it
14751 in the updated @file{configure.ac} file.
14753 The details of this macro are hairy: if @command{autoconf} encounters an
14754 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14755 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14756 macros are expanded here, while all other macros are disabled and
14757 appear literally in the updated @file{configure.ac}.
14758 @end defmac
14760 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14761 @auindex{ALIAS}
14762 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14763 with the same parameters.  This happens for example if the macro was renamed.
14764 @end defmac
14766 @node Coding Style
14767 @section Coding Style
14768 @cindex Coding style
14770 The Autoconf macros follow a strict coding style.  You are encouraged to
14771 follow this style, especially if you intend to distribute your macro,
14772 either by contributing it to Autoconf itself or the
14773 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14774 Archive}, or by other means.
14776 The first requirement is to pay great attention to the quotation.  For
14777 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14779 Do not try to invent new interfaces.  It is likely that there is a macro
14780 in Autoconf that resembles the macro you are defining: try to stick to
14781 this existing interface (order of arguments, default values, etc.).  We
14782 @emph{are} conscious that some of these interfaces are not perfect;
14783 nevertheless, when harmless, homogeneity should be preferred over
14784 creativity.
14786 Be careful about clashes both between M4 symbols and between shell
14787 variables.
14789 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14790 you are unlikely to generate conflicts.  Nevertheless, when you need to
14791 set a special value, @emph{avoid using a regular macro name}; rather,
14792 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14793 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14794 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14795 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14796 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14797 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14798 have been used (yes, with the parentheses).
14799 @c or better yet, high-level macros such as @code{m4_expand_once}
14801 No Autoconf macro should ever enter the user-variable name space; i.e.,
14802 except for the variables that are the actual result of running the
14803 macro, all shell variables should start with @code{ac_}.  In
14804 addition, small macros or any macro that is likely to be embedded in
14805 other macros should be careful not to use obvious names.
14807 @cindex @code{dnl}
14808 Do not use @code{dnl} to introduce comments: most of the comments you
14809 are likely to write are either header comments which are not output
14810 anyway, or comments that should make their way into @file{configure}.
14811 There are exceptional cases where you do want to comment special M4
14812 constructs, in which case @code{dnl} is right, but keep in mind that it
14813 is unlikely.
14815 M4 ignores the leading blanks and newlines before each argument.
14816 Use this feature to
14817 indent in such a way that arguments are (more or less) aligned with the
14818 opening parenthesis of the macro being called.  For instance, instead of
14820 @example
14821 AC_CACHE_CHECK(for EMX OS/2 environment,
14822 ac_cv_emxos2,
14823 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14824 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14825 @end example
14827 @noindent
14828 write
14830 @example
14831 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14832 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14833                    [ac_cv_emxos2=yes],
14834                    [ac_cv_emxos2=no])])
14835 @end example
14837 @noindent
14838 or even
14840 @example
14841 AC_CACHE_CHECK([for EMX OS/2 environment],
14842                [ac_cv_emxos2],
14843                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14844                                                    [return __EMX__;])],
14845                                   [ac_cv_emxos2=yes],
14846                                   [ac_cv_emxos2=no])])
14847 @end example
14849 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14850 cross-compiling, provide a pessimistic value (typically @samp{no}).
14852 Feel free to use various tricks to prevent auxiliary tools, such as
14853 syntax-highlighting editors, from behaving improperly.  For instance,
14854 instead of:
14856 @example
14857 m4_bpatsubst([$1], [$"])
14858 @end example
14860 @noindent
14863 @example
14864 m4_bpatsubst([$1], [$""])
14865 @end example
14867 @noindent
14868 so that Emacsen do not open an endless ``string'' at the first quote.
14869 For the same reasons, avoid:
14871 @example
14872 test $[#] != 0
14873 @end example
14875 @noindent
14876 and use:
14878 @example
14879 test $[@@%:@@] != 0
14880 @end example
14882 @noindent
14883 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14884 breaking the bracket-matching highlighting from Emacsen.  Note the
14885 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14886 not escape when it is unnecessary.  Common examples of useless quotation
14887 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14888 etc.  If you add portability issues to the picture, you'll prefer
14889 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14890 better than hacking Autoconf @code{:-)}.
14892 When using @command{sed}, don't use @option{-e} except for indenting
14893 purposes.  With the @code{s} and @code{y} commands, the preferred
14894 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14895 or replacement, in which case you should use @samp{|}, or optionally
14896 @samp{,} if you know the pattern and replacement cannot contain a file
14897 name.  If none of these characters will do, choose a printable character
14898 that cannot appear in the pattern or replacement.  Characters from the
14899 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14900 replacement might contain a file name, since they have special meaning
14901 to the shell and are less likely to occur in file names.
14903 @xref{Macro Definitions}, for details on how to define a macro.  If a
14904 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14905 of an @code{AC_REQUIRE} directive, and macros required by other macros
14906 inside arguments do not need to be expanded before this macro, then
14907 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14908 Also take into account that public third-party macros need to use
14909 @code{AC_DEFUN} in order to be found by @command{aclocal}
14910 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14911 All the @code{AC_REQUIRE} statements should be at the beginning of the
14912 macro, and each statement should be followed by @code{dnl}.
14914 You should not rely on the number of arguments: instead of checking
14915 whether an argument is missing, test that it is not empty.  It provides
14916 both a simpler and a more predictable interface to the user, and saves
14917 room for further arguments.
14919 Unless the macro is short, try to leave the closing @samp{])} at the
14920 beginning of a line, followed by a comment that repeats the name of the
14921 macro being defined.  This introduces an additional newline in
14922 @command{configure}; normally, that is not a problem, but if you want to
14923 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14924 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14925 is recommended instead of @samp{dnl} to ensure that M4 does not
14926 interpret the @samp{dnl} as being attached to the preceding text or
14927 macro output.  For example, instead of:
14929 @example
14930 AC_DEFUN([AC_PATH_X],
14931 [AC_MSG_CHECKING([for X])
14932 AC_REQUIRE_CPP()
14933 @r{# @dots{}omitted@dots{}}
14934   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14935 fi])
14936 @end example
14938 @noindent
14939 you would write:
14941 @example
14942 AC_DEFUN([AC_PATH_X],
14943 [AC_REQUIRE_CPP()[]dnl
14944 AC_MSG_CHECKING([for X])
14945 @r{# @dots{}omitted@dots{}}
14946   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14947 fi[]dnl
14948 ])# AC_PATH_X
14949 @end example
14951 If the macro is long, try to split it into logical chunks.  Typically,
14952 macros that check for a bug in a function and prepare its
14953 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14954 this setup.  Do not hesitate to introduce auxiliary macros to factor
14955 your code.
14957 In order to highlight the recommended coding style, here is a macro
14958 written the old way:
14960 @example
14961 dnl Check for EMX on OS/2.
14962 dnl _AC_EMXOS2
14963 AC_DEFUN(_AC_EMXOS2,
14964 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14965 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14966 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14967 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14968 @end example
14970 @noindent
14971 and the new way:
14973 @example
14974 # _AC_EMXOS2
14975 # ----------
14976 # Check for EMX on OS/2.
14977 m4_define([_AC_EMXOS2],
14978 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14979 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14980                    [ac_cv_emxos2=yes],
14981                    [ac_cv_emxos2=no])])
14982 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14983 ])# _AC_EMXOS2
14984 @end example
14989 @c ============================================= Portable Shell Programming
14991 @node Portable Shell
14992 @chapter Portable Shell Programming
14993 @cindex Portable shell programming
14995 When writing your own checks, there are some shell-script programming
14996 techniques you should avoid in order to make your code portable.  The
14997 Bourne shell and upward-compatible shells like the Korn shell and Bash
14998 have evolved over the years, and many features added to the original
14999 System7 shell are now supported on all interesting porting targets.
15000 However, the following discussion between Russ Allbery and Robert Lipe
15001 is worth reading:
15003 @noindent
15004 Russ Allbery:
15006 @quotation
15007 The GNU assumption that @command{/bin/sh} is the one and only shell
15008 leads to a permanent deadlock.  Vendors don't want to break users'
15009 existing shell scripts, and there are some corner cases in the Bourne
15010 shell that are not completely compatible with a Posix shell.  Thus,
15011 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15012 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15013 Posix shell.
15014 @end quotation
15016 @noindent
15017 Robert Lipe:
15019 @quotation
15020 This is exactly the problem.  While most (at least most System V's) do
15021 have a Bourne shell that accepts shell functions most vendor
15022 @command{/bin/sh} programs are not the Posix shell.
15024 So while most modern systems do have a shell @emph{somewhere} that meets the
15025 Posix standard, the challenge is to find it.
15026 @end quotation
15028 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15029 is to find such a shell.  But to prevent trouble, if you're not using
15030 M4sh you should not take advantage of features that were added after Unix
15031 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15032 negated character classes, or even @command{unset}.  @code{#} comments,
15033 while not in Unix version 7, were retrofitted in the original Bourne
15034 shell and can be assumed to be part of the least common denominator.
15036 On the other hand, if you're using M4sh you can assume that the shell
15037 has the features that were added in SVR2 (circa 1984), including shell
15038 functions,
15039 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15040 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15041 However, some pitfalls have to be avoided for portable use of these
15042 constructs; these will be documented in the rest of this chapter.
15043 See in particular @ref{Shell Functions} and @ref{Limitations of
15044 Builtins, , Limitations of Shell Builtins}.
15046 Some ancient systems have quite
15047 small limits on the length of the @samp{#!} line; for instance, 32
15048 bytes (not including the newline) on SunOS 4.
15049 However, these ancient systems are no longer of practical concern.
15051 The set of external programs you should run in a @command{configure} script
15052 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15053 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15054 restriction allows users to start out with a fairly small set of
15055 programs and build the rest, avoiding too many interdependencies between
15056 packages.
15058 Some of these external utilities have a portable subset of features; see
15059 @ref{Limitations of Usual Tools}.
15061 There are other sources of documentation about shells.  The
15062 specification for the Posix
15063 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15064 Command Language}, though more generous than the restrictive shell
15065 subset described above, is fairly portable nowadays.  Also please see
15066 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15068 @menu
15069 * Shellology::                  A zoology of shells
15070 * Here-Documents::              Quirks and tricks
15071 * File Descriptors::            FDs and redirections
15072 * Signal Handling::             Shells, signals, and headaches
15073 * File System Conventions::     File names
15074 * Shell Pattern Matching::      Pattern matching
15075 * Shell Substitutions::         Variable and command expansions
15076 * Assignments::                 Varying side effects of assignments
15077 * Parentheses::                 Parentheses in shell scripts
15078 * Slashes::                     Slashes in shell scripts
15079 * Special Shell Variables::     Variables you should not change
15080 * Shell Functions::             What to look out for if you use them
15081 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15082 * Limitations of Usual Tools::  Portable use of portable tools
15083 @end menu
15085 @node Shellology
15086 @section Shellology
15087 @cindex Shellology
15089 There are several families of shells, most prominently the Bourne family
15090 and the C shell family which are deeply incompatible.  If you want to
15091 write portable shell scripts, avoid members of the C shell family.  The
15092 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15093 Shell difference FAQ} includes a small history of Posix shells, and a
15094 comparison between several of them.
15096 Below we describe some of the members of the Bourne shell family.
15098 @table @asis
15099 @item Ash
15100 @cindex Ash
15101 Ash is often used on GNU/Linux and BSD
15102 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15103 bugs that are fixed in the 0.3.x series, but portable shell scripts
15104 should work around them, since version 0.2 is still shipped with many
15105 GNU/Linux distributions.
15107 To be compatible with Ash 0.2:
15109 @itemize @minus
15110 @item
15111 don't use @samp{$?} after expanding empty or unset variables,
15112 or at the start of an @command{eval}:
15114 @example
15115 foo=
15116 false
15117 $foo
15118 echo "Do not use it: $?"
15119 false
15120 eval 'echo "Do not use it: $?"'
15121 @end example
15123 @item
15124 don't use command substitution within variable expansion:
15126 @example
15127 cat $@{FOO=`bar`@}
15128 @end example
15130 @item
15131 beware that single builtin substitutions are not performed by a
15132 subshell, hence their effect applies to the current shell!  @xref{Shell
15133 Substitutions}, item ``Command Substitution''.
15134 @end itemize
15136 @item Bash
15137 @cindex Bash
15138 To detect whether you are running Bash, test whether
15139 @code{BASH_VERSION} is set.  To require
15140 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15141 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15142 Manual}, for details.
15144 @item Bash 2.05 and later
15145 @cindex Bash 2.05 and later
15146 Versions 2.05 and later of Bash use a different format for the
15147 output of the @command{set} builtin, designed to make evaluating its
15148 output easier.  However, this output is not compatible with earlier
15149 versions of Bash (or with many other shells, probably).  So if
15150 you use Bash 2.05 or higher to execute @command{configure},
15151 you'll need to use Bash 2.05 for all other build tasks as well.
15153 @item Ksh
15154 @cindex Ksh
15155 @cindex Korn shell
15156 @prindex @samp{ksh}
15157 @prindex @samp{ksh88}
15158 @prindex @samp{ksh93}
15159 The Korn shell is compatible with the Bourne family and it mostly
15160 conforms to Posix.  It has two major variants commonly
15161 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15162 release.  It is usually called @command{ksh}, but is called @command{sh}
15163 on some hosts if you set your path appropriately.
15165 Solaris systems have three variants:
15166 @prindex @command{/usr/bin/ksh} on Solaris
15167 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15168 standard on Solaris 2.0 and later.
15169 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15170 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15171 @samp{ksh88}; it is standard on Solaris 9 and later.
15172 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15173 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15174 Variants that are not standard may be parts of optional
15175 packages.  There is no extra charge for these packages, but they are
15176 not part of a minimal OS install and therefore some installations may
15177 not have it.
15179 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15180 is also available as @command{/usr/bin/posix/sh}.  If the environment
15181 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15182 the standard shell conform to Posix.
15184 @item Pdksh
15185 @prindex @samp{pdksh}
15186 A public-domain clone of the Korn shell called @command{pdksh} is widely
15187 available: it has most of the @samp{ksh88} features along with a few of
15188 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15189 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15190 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15191 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15192 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15193 at least one respect, see @ref{Shell Substitutions}.
15195 @item Zsh
15196 @cindex Zsh
15197 To detect whether you are running @command{zsh}, test whether
15198 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15199 compatible with the Bourne shell: you must execute @samp{emulate sh},
15200 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15201 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15202 zsh, The Z Shell Manual}, for details.
15204 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15205 Bash in Mac OS X 10.2.
15206 @end table
15208 @node Here-Documents
15209 @section Here-Documents
15210 @cindex Here-documents
15211 @cindex Shell here-documents
15213 Don't rely on @samp{\} being preserved just because it has no special
15214 meaning together with the next symbol.  In the native @command{sh}
15215 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15216 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15217 use @samp{\\} to get @samp{\}.
15219 With OpenBSD 2.7's @command{sh}
15221 @example
15222 @group
15223 $ @kbd{cat <<EOF
15224 > \" \\
15225 > EOF}
15226 " \
15227 @end group
15228 @end example
15230 @noindent
15231 and with Bash:
15233 @example
15234 @group
15235 bash-2.04$ @kbd{cat <<EOF
15236 > \" \\
15237 > EOF}
15238 \" \
15239 @end group
15240 @end example
15242 Some shells mishandle large here-documents: for example,
15243 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15244 derived from Korn shell version M-12/28/93d, mishandle braced variable
15245 expansion that crosses a 1024- or 4096-byte buffer boundary
15246 within a here-document.  Only the part of the variable name after the boundary
15247 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15248 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15249 boundary, the shell reports an error, as if you used @code{$@{@}}.
15250 Instead of @code{$@{variable-default@}}, the shell may expand
15251 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15252 be worked around by omitting the braces: @code{$variable}.  The bug was
15253 fixed in
15254 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15255 still shipping older versions with the bug.
15257 Empty here-documents are not portable either; with the following code,
15258 @command{zsh} up to at least version 4.3.10 creates a file with a single
15259 newline, whereas other shells create an empty file:
15261 @example
15262 cat >file <<EOF
15264 @end example
15266 Many shells (including the Bourne shell) implement here-documents
15267 inefficiently.  In particular, some shells can be extremely inefficient when
15268 a single statement contains many here-documents.  For instance if your
15269 @file{configure.ac} includes something like:
15271 @example
15272 @group
15273 if <cross_compiling>; then
15274   assume this and that
15275 else
15276   check this
15277   check that
15278   check something else
15279   @dots{}
15280   on and on forever
15281   @dots{}
15283 @end group
15284 @end example
15286 A shell parses the whole @code{if}/@code{fi} construct, creating
15287 temporary files for each here-document in it.  Some shells create links
15288 for such here-documents on every @code{fork}, so that the clean-up code
15289 they had installed correctly removes them.  It is creating the links
15290 that can take the shell forever.
15292 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15293 @code{if}/@code{fi} constructs, would improve the performance
15294 significantly.  Anyway, this kind of construct is not exactly the
15295 typical use of Autoconf.  In fact, it's even not recommended, because M4
15296 macros can't look into shell conditionals, so we may fail to expand a
15297 macro when it was expanded before in a conditional path, and the
15298 condition turned out to be false at runtime, and we end up not
15299 executing the macro at all.
15301 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15302 behavior is only portable for stripping leading @key{TAB}s, and things
15303 can silently break if an overzealous editor converts to using leading
15304 spaces (not all shells are nice enough to warn about unterminated
15305 here-documents).
15307 @example
15308 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15311 done
15312 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15314   2
15316 done
15317 @end example
15319 @node File Descriptors
15320 @section File Descriptors
15321 @cindex Descriptors
15322 @cindex File descriptors
15323 @cindex Shell file descriptors
15325 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15326 stderr, even for subshells.  This might result in undesirable content
15327 if you meant to capture the standard-error output of the inner command:
15329 @example
15330 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15331 $ @kbd{cat stderr}
15332 + eval echo foo >&2
15333 + echo foo
15335 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15336 $ @kbd{cat stderr}
15337 + eval 'echo foo >&2'
15338 ++ echo foo
15340 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15341 @i{# Traces on startup files deleted here.}
15342 $ @kbd{cat stderr}
15343 +zsh:1> eval echo foo >&2
15344 +zsh:1> echo foo
15346 @end example
15348 @noindent
15349 One workaround is to grep out uninteresting lines, hoping not to remove
15350 good ones.
15352 If you intend to redirect both standard error and standard output,
15353 redirect standard output first.  This works better with HP-UX,
15354 since its shell mishandles tracing if standard error is redirected
15355 first:
15357 @example
15358 $ @kbd{sh -x -c ': 2>err >out'}
15359 + :
15360 + 2> err $ @kbd{cat err}
15361 1> out
15362 @end example
15364 Don't try to redirect the standard error of a command substitution.  It
15365 must be done @emph{inside} the command substitution.  When running
15366 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15367 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15369 On the other hand, some shells, such as Solaris or FreeBSD
15370 @command{/bin/sh}, warn about missing programs before performing
15371 redirections.  Therefore, to silently check whether a program exists, it
15372 is necessary to perform redirections on a subshell or brace group:
15373 @example
15374 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15375 nosuch: not found
15376 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15377 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15378 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15379 @end example
15381 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15382 shell pipeline.
15384 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15385 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15387 Some shells, like @command{ash}, don't recognize bi-directional
15388 redirection (@samp{<>}).  And even on shells that recognize it, it is
15389 not portable to use on fifos: Posix does not require read-write support
15390 for named pipes, and Cygwin does not support it:
15392 @example
15393 $ @kbd{mkfifo fifo}
15394 $ @kbd{exec 5<>fifo}
15395 $ @kbd{echo hi >&5}
15396 bash: echo: write error: Communication error on send
15397 @end example
15399 @noindent
15400 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15401 regular files when using @samp{<>}:
15403 @example
15404 $ @kbd{echo a > file}
15405 $ @kbd{bash -c ': 1<>file'; cat file}
15407 $ @kbd{dash -c ': 1<>file'; cat file}
15408 $ rm a
15409 @end example
15411 When catering to old systems, don't redirect the same file descriptor
15412 several times, as you are doomed to failure under Ultrix.
15414 @example
15415 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15416 UWS V4.4 (Rev. 11)
15417 $ @kbd{eval 'echo matter >fullness' >void}
15418 illegal io
15419 $ @kbd{eval '(echo matter >fullness)' >void}
15420 illegal io
15421 $ @kbd{(eval '(echo matter >fullness)') >void}
15422 Ambiguous output redirect.
15423 @end example
15425 @noindent
15426 In each case the expected result is of course @file{fullness} containing
15427 @samp{matter} and @file{void} being empty.  However, this bug is
15428 probably not of practical concern to modern platforms.
15430 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15431 (even if it is redirected) in a loop after the first iteration, or in a
15432 shell function after the first call:
15434 @example
15435 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15436 $ @kbd{ls x*}
15438 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15439 $ @kbd{ls y*}
15441 @end example
15443 @noindent
15444 As a workaround, @command{echo} or @command{eval} can be used.
15446 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15447 subsidiary program.  If any of these descriptors is closed, the
15448 operating system may open an unspecified file for the descriptor in the
15449 new process image.  Posix 2008 says this may be done only if the
15450 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15451 it even for ordinary programs, and the next version of Posix will allow
15452 HP-UX behavior.
15454 If you want a file descriptor above 2 to be inherited into a child
15455 process, then you must use redirections specific to that command or a
15456 containing subshell or command group, rather than relying on
15457 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15458 @command{sh}, file descriptors above 2 which are opened using
15459 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15460 that involved in the fork-and-exec which runs a program or script):
15462 @example
15463 $ @kbd{echo 'echo hello >&5' >k}
15464 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15465 hello
15466 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15467 hello
15468 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15469 ./k[1]: 5: cannot open [Bad file number]
15470 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15471 hello
15472 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15473 hello
15474 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15475 hello
15476 @end example
15478 Don't rely on duplicating a closed file descriptor to cause an
15479 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15480 ignored, which can cause unintended leaks to the original file
15481 descriptor.  In this example, observe the leak to standard output:
15483 @example
15484 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15485 bash: 3: Bad file descriptor
15487 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15490 @end example
15492 Fortunately, an attempt to close an already closed file descriptor will
15493 portably succeed.  Likewise, it is safe to use either style of
15494 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15495 even if it doesn't match the read/write mode that the file descriptor
15496 was opened with.
15498 DOS variants cannot rename or remove open files, such as in
15499 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15500 perfectly portable among Posix hosts.
15502 A few ancient systems reserved some file descriptors.  By convention,
15503 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15504 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15505 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15506 1990), though we don't now remember what it was.  Both these systems are
15507 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15508 other file descriptors.
15510 On the other hand, you can't portably use multi-digit file descriptors.
15511 Solaris @command{ksh} doesn't understand any file descriptor larger than
15512 @samp{9}:
15514 @example
15515 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15517 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15519 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15520 ksh[1]: exec: 10: not found
15522 @end example
15524 @c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15525 @node Signal Handling
15526 @section Signal Handling
15527 @cindex Signal handling in the shell
15528 @cindex Signals, shells and
15530 Portable handling of signals within the shell is another major source of
15531 headaches.  This is worsened by the fact that various different, mutually
15532 incompatible approaches are possible in this area, each with its
15533 distinctive merits and demerits.  A detailed description of these possible
15534 approaches, as well as of their pros and cons, can be found in
15535 @uref{http://www.cons.org/cracauer/sigint.html, this article}.
15537 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15538 @c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15539 the shell still exits with error upon termination by one of those signals,
15540 but in such a case the exit status might be somewhat unexpected (even if
15541 allowed by POSIX, strictly speaking):
15543 @example
15544 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15545 Hangup
15547 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15548 Terminated
15550 $ @kbd{for sig in 1 2 3 15; do}
15551 > @kbd{  echo $sig:}
15552 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15553 > @kbd{done}
15554 signal 1:
15555 Hangup
15557 signal 2:
15559 signal 3:
15561 signal 15:
15563 @end example
15565 This gets even worse if one is using the POSIX `wait' interface to get
15566 details about the shell process terminations: it will result in the shell
15567 having exited normally, rather than by receiving a signal.
15569 @example
15570 $ @kbd{cat > foo.c <<'END'}
15571 #include <stdio.h>    /* for printf */
15572 #include <stdlib.h>   /* for system */
15573 #include <sys/wait.h> /* for WIF* macros */
15574 int main(void)
15576   int status = system ("kill -15 $$");
15577   printf ("Terminated by signal: %s\n",
15578           WIFSIGNALED (status) ? "yes" : "no");
15579   printf ("Exited normally: %s\n",
15580           WIFEXITED (status) ? "yes" : "no");
15581   return 0;
15584 @c $$ font-lock
15585 $ @kbd{cc -o foo foo.c}
15586 $ @kbd{./a.out} # On GNU/Linux
15587 Terminated by signal: no
15588 Exited normally: yes
15589 $ @kbd{./a.out} # On Solaris 10
15590 Terminated by signal: yes
15591 Exited normally: no
15592 @end example
15594 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15595 if it is not blocked, and even if the shell is not running interactively
15596 (in fact, even if the shell has no attached tty); among these shells
15597 are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15598 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15599 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15600 these shells.  OTOH, some other shells doesn't special-case the handling
15601 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15602 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15604 @c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15605 Some shells (especially Korn shells and derivatives) might try to
15606 propagate to themselves a signal that has killed a child process; this is
15607 not a bug, but a conscious design choice (although its overall value might
15608 be debatable).  The exact details of how this is attained vary from shell
15609 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15610 the perl process has been interrupted AT&T @code{ksh93} (2011) will
15611 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15612 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15613 128 + 2). In any case, if there is an active trap associated with
15614 @code{SIGINT}, those shells will correctly execute it.
15616 @c See: <http://www.austingroupbugs.net/view.php?id=51>
15617 Some Korn shells, when a child process die due receiving a signal with
15618 signal number @var{n}, can leave in @samp{$?} an exit status of
15619 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15620 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15621 Debian:
15623 @example
15624 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15625 /bin/ksh: line 1: 7837: Hangup
15627 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15628 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15630 @end example
15632 @noindent
15633 This @command{ksh} behavior is allowed by POSIX, if implemented with
15634 due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15635 Austin Group discussion} for more background.  However, if it is not
15636 implemented with proper care, such a behavior might cause problems
15637 in some corner cases.  To see why, assume we have a ``wrapper'' script
15638 like this:
15640 @example
15641 #!/bin/sh
15642 # Ignore some signals in the shell only, not in its child processes.
15643 trap : 1 2 13 15
15644 wrapped_command "$@@"
15645 ret=$?
15646 other_command
15647 exit $ret
15648 @end example
15650 @noindent
15651 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15652 has signal number 1), @code{ret} will be set to 257.  Unless the
15653 @command{exit} shell builtin is smart enough to understand that such
15654 a value can only have originated from a signal, and adjust the final
15655 wait status of the shell appropriately, the value 257 will just get
15656 truncated to 1 by the closing @code{exit} call, so that a caller of
15657 the script will have no way to determine that termination by a signal
15658 was involved.  Observe the different behavior of AT&T @code{ksh93}
15659 (2011) and @code{bash} 4.1.5 on Debian:
15661 @example
15662 $ @kbd{cat foo.sh}
15663 #!/bin/sh
15664 sh -c 'kill -1 $$'
15665 ret=$?
15666 echo $ret
15667 exit $ret
15668 $ @kbd{/bin/ksh foo.sh; echo $?}
15669 foo.sh: line 2: 12479: Hangup
15672 $ @kbd{/bin/bash foo.sh; echo $?}
15673 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15676 @end example
15678 @node File System Conventions
15679 @section File System Conventions
15680 @cindex File system conventions
15682 Autoconf uses shell-script processing extensively, so the file names
15683 that it processes should not contain characters that are special to the
15684 shell.  Special characters include space, tab, newline, NUL, and
15685 the following:
15687 @example
15688 " # $ & ' ( ) * ; < = > ? [ \ ` |
15689 @end example
15691 Also, file names should not begin with @samp{~} or @samp{-}, and should
15692 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15693 immediately after @samp{:}.  On Posix-like platforms, directory names
15694 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15695 path separator.
15697 These restrictions apply not only to the files that you distribute, but
15698 also to the absolute file names of your source, build, and destination
15699 directories.
15701 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15702 they should be avoided.
15704 Posix lets implementations treat leading @file{//} specially, but
15705 requires leading @file{///} and beyond to be equivalent to @file{/}.
15706 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15707 @file{//} as a ``super-root'' that can provide access to files that are
15708 not otherwise reachable from @file{/}.  The super-root tradition began
15709 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15710 has revived it.
15712 While @command{autoconf} and friends are usually run on some Posix
15713 variety, they can be used on other systems, most notably DOS
15714 variants.  This impacts several assumptions regarding file names.
15716 @noindent
15717 For example, the following code:
15719 @example
15720 case $foo_dir in
15721   /*) # Absolute
15722      ;;
15723   *)
15724      foo_dir=$dots$foo_dir ;;
15725 esac
15726 @end example
15728 @noindent
15729 fails to properly detect absolute file names on those systems, because
15730 they can use a drivespec, and usually use a backslash as directory
15731 separator.  If you want to be portable to DOS variants (at the
15732 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15733 you can check for absolute file names like this:
15735 @cindex absolute file names, detect
15736 @example
15737 case $foo_dir in
15738   [\\/]* | ?:[\\/]* ) # Absolute
15739      ;;
15740   *)
15741      foo_dir=$dots$foo_dir ;;
15742 esac
15743 @end example
15745 @noindent
15746 Make sure you quote the brackets if appropriate and keep the backslash as
15747 first character (@pxref{case, , Limitations of Shell Builtins}).
15749 Also, because the colon is used as part of a drivespec, these systems don't
15750 use it as path separator.  When creating or accessing paths, you can use the
15751 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15752 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15753 starts up.
15755 File names need extra care as well.  While DOS variants
15756 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15757 are usually able to handle long file names properly, there are still
15758 limitations that can seriously break packages.  Several of these issues
15759 can be easily detected by the
15760 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15761 package.
15763 A short overview follows; problems are marked with SFN/LFN to
15764 indicate where they apply: SFN means the issues are only relevant to
15765 plain DOS, not to DOS under Microsoft Windows
15766 variants, while LFN identifies problems that exist even under
15767 Microsoft Windows variants.
15769 @table @asis
15770 @item No multiple dots (SFN)
15771 DOS cannot handle multiple dots in file names.  This is an especially
15772 important thing to remember when building a portable configure script,
15773 as @command{autoconf} uses a .in suffix for template files.
15775 This is perfectly OK on Posix variants:
15777 @example
15778 AC_CONFIG_HEADERS([config.h])
15779 AC_CONFIG_FILES([source.c foo.bar])
15780 AC_OUTPUT
15781 @end example
15783 @noindent
15784 but it causes problems on DOS, as it requires @samp{config.h.in},
15785 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15786 to DOS-based environments, you should use this instead:
15788 @example
15789 AC_CONFIG_HEADERS([config.h:config.hin])
15790 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15791 AC_OUTPUT
15792 @end example
15794 @item No leading dot (SFN)
15795 DOS cannot handle file names that start with a dot.  This is usually
15796 not important for @command{autoconf}.
15798 @item Case insensitivity (LFN)
15799 DOS is case insensitive, so you cannot, for example, have both a
15800 file called @samp{INSTALL} and a directory called @samp{install}.  This
15801 also affects @command{make}; if there's a file called @samp{INSTALL} in
15802 the directory, @samp{make install} does nothing (unless the
15803 @samp{install} target is marked as PHONY).
15805 @item The 8+3 limit (SFN)
15806 Because the DOS file system only stores the first 8 characters of
15807 the file name and the first 3 of the extension, those must be unique.
15808 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15809 @file{foobar-prettybird.c} all resolve to the same file name
15810 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15811 @file{foo.bartender}.
15813 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15814 uses numeric
15815 tails in the short version of file names to make them unique.  However, a
15816 registry setting can turn this behavior off.  While this makes it
15817 possible to share file trees containing long file names between SFN
15818 and LFN environments, it also means the above problem applies there
15819 as well.
15821 @item Invalid characters (LFN)
15822 Some characters are invalid in DOS file names, and should therefore
15823 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15824 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15825 In a SFN environment, other characters are also invalid.  These
15826 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15828 @item Invalid names (LFN)
15829 Some DOS file names are reserved, and cause problems if you
15830 try to use files with those names.  These names include @file{CON},
15831 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15832 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15833 File names are case insensitive, so even names like
15834 @file{aux/config.guess} are disallowed.
15836 @end table
15838 @node Shell Pattern Matching
15839 @section Shell Pattern Matching
15840 @cindex Shell pattern matching
15842 Nowadays portable patterns can use negated character classes like
15843 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15844 some shells but not others; hence portable scripts should never use
15845 @samp{^} as the first character of a bracket pattern.
15847 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15848 they may match characters that are not lower-case letters.
15850 @node Shell Substitutions
15851 @section Shell Substitutions
15852 @cindex Shell substitutions
15854 Contrary to a persistent urban legend, the Bourne shell does not
15855 systematically split variables and back-quoted expressions, in particular
15856 on the right-hand side of assignments and in the argument of @code{case}.
15857 For instance, the following code:
15859 @example
15860 case "$given_srcdir" in
15861 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15862 *)  top_srcdir="$dots$given_srcdir" ;;
15863 esac
15864 @end example
15866 @noindent
15867 is more readable when written as:
15869 @example
15870 case $given_srcdir in
15871 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15872 *)  top_srcdir=$dots$given_srcdir ;;
15873 esac
15874 @end example
15876 @noindent
15877 and in fact it is even @emph{more} portable: in the first case of the
15878 first attempt, the computation of @code{top_srcdir} is not portable,
15879 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15880 for example Solaris 10 ksh:
15882 @example
15883 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15884 ksh: : cannot execute
15885 ksh: bar | sed 's, ,,': cannot execute
15886 @end example
15888 @noindent
15889 Posix does not specify behavior for this sequence.  On the other hand,
15890 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15891 but in practice, not all shells understand it the same way: pdksh 5.2.14
15892 prints spurious quotes when in Posix mode:
15894 @example
15895 $ @kbd{echo "`echo \"hello\"`"}
15896 hello
15897 $ @kbd{set -o posix}
15898 $ @kbd{echo "`echo \"hello\"`"}
15899 "hello"
15900 @end example
15902 @noindent
15903 There is just no portable way to use double-quoted strings inside
15904 double-quoted back-quoted expressions (pfew!).
15906 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15907 parameter expansions are elided during word splitting.  Meanwhile, zsh
15908 does not perform word splitting except when in Bourne compatibility
15909 mode.  In the example below, the correct behavior is to have five
15910 arguments to the function, and exactly two spaces on either side of the
15911 middle @samp{-}, since word splitting collapses multiple spaces in
15912 @samp{$f} but leaves empty arguments intact.
15914 @example
15915 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15916 3- - -
15917 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15918 5-  -  -
15919 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15920 3-   -   -
15921 $ @kbd{zsh -c 'emulate sh;}
15922 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15923 5-  -  -
15924 @end example
15926 @noindent
15927 You can work around this by doing manual word splitting, such as using
15928 @samp{"$str" $list} rather than @samp{"$str"$list}.
15930 There are also portability pitfalls with particular expansions:
15932 @table @code
15933 @item $@@
15934 @cindex @code{"$@@"}
15935 One of the most famous shell-portability issues is related to
15936 @samp{"$@@"}.  When there are no positional arguments, Posix says
15937 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15938 original Unix version 7 Bourne shell treated it as equivalent to
15939 @samp{""} instead, and this behavior survives in later implementations
15940 like Digital Unix 5.0.
15942 The traditional way to work around this portability problem is to use
15943 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15944 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15945 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15947 @example
15948 zsh $ @kbd{emulate sh}
15949 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15950 Hello World
15952 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15953 Hello
15954 World
15956 @end example
15958 @noindent
15959 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15960 @samp{"$@@"} because of the portability problems mentioned above.
15961 One workaround relies on Zsh's ``global aliases'' to convert
15962 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15964 @example
15965 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15966 @end example
15968 Zsh only recognizes this alias when a shell word matches it exactly;
15969 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
15970 case always yields at least one shell word, use plain @samp{"$@@"}.
15972 A more conservative workaround is to avoid @samp{"$@@"} if it is
15973 possible that there may be no positional arguments.  For example,
15974 instead of:
15976 @example
15977 cat conftest.c "$@@"
15978 @end example
15980 you can use this instead:
15982 @example
15983 case $# in
15984 0) cat conftest.c;;
15985 *) cat conftest.c "$@@";;
15986 esac
15987 @end example
15989 Autoconf macros often use the @command{set} command to update
15990 @samp{$@@}, so if you are writing shell code intended for
15991 @command{configure} you should not assume that the value of @samp{$@@}
15992 persists for any length of time.
15995 @item $@{10@}
15996 @cindex positional parameters
15997 The 10th, 11th, @dots{} positional parameters can be accessed only after
15998 a @code{shift}.  The 7th Edition shell reported an error if given
15999 @code{$@{10@}}, and
16000 Solaris 10 @command{/bin/sh} still acts that way:
16002 @example
16003 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16004 $ @kbd{echo $@{10@}}
16005 bad substitution
16006 @end example
16008 Conversely, not all shells obey the Posix rule that when braces are
16009 omitted, multiple digits beyond a @samp{$} imply the single-digit
16010 positional parameter expansion concatenated with the remaining literal
16011 digits.  To work around the issue, you must use braces.
16013 @example
16014 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16015 a0 a0
16016 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16017 j a0
16018 @end example
16020 @item $@{@var{var}:-@var{value}@}
16021 @c Info cannot handle `:' in index entries.
16022 @ifnotinfo
16023 @cindex @code{$@{@var{var}:-@var{value}@}}
16024 @end ifnotinfo
16025 @cindex @code{$@{@var{var}-@var{value}@}}
16026 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16027 colon for any shell substitution, and complain and die.
16028 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
16029 However, all shells that support functions allow the use of colon in
16030 shell substitution, and since m4sh requires functions, you can portably
16031 use null variable substitution patterns in configure scripts.
16033 @item $@{@var{var}+@var{value}@}
16034 @cindex @code{$@{@var{var}+@var{value}@}}
16035 When using @samp{$@{@var{var}-@var{value}@}} or
16036 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16037 @var{value} must either be a single shell word, quoted, or in the
16038 context of an unquoted here-document.  Solaris
16039 @command{/bin/sh} complains otherwise.
16041 @example
16042 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16043 /bin/sh: bad substitution
16044 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16045 b c
16046 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16047 b c
16048 $ @kbd{/bin/sh -c 'cat <<EOF
16049 $@{a-b c@}
16050 EOF}
16051 b c
16052 @end example
16054 According to Posix, if an expansion occurs inside double quotes, then
16055 the use of unquoted double quotes within @var{value} is unspecified, and
16056 any single quotes become literal characters; in that case, escaping must
16057 be done with backslash.  Likewise, the use of unquoted here-documents is
16058 a case where double quotes have unspecified results:
16060 @example
16061 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16062 /bin/sh: bad substitution
16063 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16064 b c
16065 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16066 b  c
16067 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16068 b  c
16069 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16070 'b  c'
16071 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16072 "b  c"
16073 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16074 b  c
16075 $ @kbd{/bin/sh -c 'cat <<EOF
16076 $@{a-"b  c"@}
16077 EOF'}
16078 "b  c"
16079 $ @kbd{/bin/sh -c 'cat <<EOF
16080 $@{a-'b  c'@}
16081 EOF'}
16082 'b  c'
16083 $ @kbd{bash -c 'cat <<EOF
16084 $@{a-"b  c"@}
16085 EOF'}
16086 b  c
16087 $ @kbd{bash -c 'cat <<EOF
16088 $@{a-'b  c'@}
16089 EOF'}
16090 'b  c'
16091 @end example
16093 Perhaps the easiest way to work around quoting issues in a manner
16094 portable to all shells is to place the results in a temporary variable,
16095 then use @samp{$t} as the @var{value}, rather than trying to inline
16096 the expression needing quoting.
16098 @example
16099 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16100 b  c"'@}\
16101 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16102 b  c"'@}\
16103 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16104 b  c"'@}\
16105 @end example
16107 @item $@{@var{var}=@var{value}@}
16108 @cindex @code{$@{@var{var}=@var{value}@}}
16109 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16110 to @var{var}, remember that even though the assignment to @var{var} does
16111 not undergo file name expansion, the result of the variable expansion
16112 does unless the expansion occurred within double quotes.  In particular,
16113 when using @command{:} followed by unquoted variable expansion for the
16114 side effect of setting a default value, if the final value of
16115 @samp{$var} contains any globbing characters (either from @var{value} or
16116 from prior contents), the shell has to spend time performing file name
16117 expansion and field splitting even though those results will not be
16118 used.  Therefore, it is a good idea to consider double quotes when performing
16119 default initialization; while remembering how this impacts any quoting
16120 characters appearing in @var{value}.
16122 @example
16123 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16124 /usr/bin/*
16126 real    0m0.005s
16127 user    0m0.002s
16128 sys     0m0.003s
16129 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16130 /usr/bin/*
16132 real    0m0.039s
16133 user    0m0.026s
16134 sys     0m0.009s
16135 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16136 /usr/bin/*
16138 real    0m0.031s
16139 user    0m0.020s
16140 sys     0m0.010s
16142 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16143 /usr/bin/*
16145 real    0m0.006s
16146 user    0m0.002s
16147 sys     0m0.003s
16148 @end example
16150 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16151 if the @var{value} contains more than one shell word; either single
16152 quotes for just the @var{value}, or double quotes around the entire
16153 expansion:
16155 @example
16156 $ @kbd{: $@{var1='Some words'@}}
16157 $ @kbd{: "$@{var2=like this@}"}
16158 $ @kbd{echo $var1 $var2}
16159 Some words like this
16160 @end example
16162 @noindent
16163 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16164 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16165 requires that with @samp{=}, quote removal happens prior to the
16166 assignment, and the expansion be the final contents of @var{var} without
16167 quoting (and thus subject to field splitting), in contrast to the
16168 behavior with @samp{-} passing the quoting through to the final
16169 expansion.  However, @command{bash} 4.1 does not obey this rule.
16171 @example
16172 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16173 a  b
16174 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16175 a b
16176 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16177 a  b
16178 @end example
16180 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16181 commands, it is unspecified whether the assignments affect the parent
16182 shell environment.  It is best to perform assignments independently from
16183 commands, to avoid the problems demonstrated in this example:
16185 @example
16186 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16187 +b+b+
16189 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16190 ++b+
16192 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16193 +b+b+
16195 @end example
16197 @item $@{@var{var}=@var{value}@}
16198 @cindex @code{$@{@var{var}=@var{literal}@}}
16199 Solaris @command{/bin/sh} has a frightening bug in its handling of
16200 literal assignments.  Imagine you need set a variable to a string containing
16201 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16202 when the affected variable was already set.  This bug can be exercised
16203 by running:
16205 @example
16206 $ @kbd{unset foo}
16207 $ @kbd{foo=$@{foo='@}'@}}
16208 $ @kbd{echo $foo}
16210 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16211 $ @kbd{echo $foo}
16213 $ @kbd{foo=$@{foo='@}'@}}
16214 $ @kbd{echo $foo}
16215 @}@}
16216  ^ ugh!
16217 @end example
16219 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16220 though it is enclosed in single quotes.  The problem doesn't happen
16221 using double quotes, or when using a temporary variable holding the
16222 problematic string.
16224 @item $@{@var{var}=@var{expanded-value}@}
16225 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16226 On Ultrix,
16227 running
16229 @example
16230 default="yu,yaa"
16231 : $@{var="$default"@}
16232 @end example
16234 @noindent
16235 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16236 each char is set.  You don't observe the phenomenon using a simple
16237 @samp{echo $var} since apparently the shell resets the 8th bit when it
16238 expands $var.  Here are two means to make this shell confess its sins:
16240 @example
16241 $ @kbd{cat -v <<EOF
16242 $var
16243 EOF}
16244 @end example
16246 @noindent
16249 @example
16250 $ @kbd{set | grep '^var=' | cat -v}
16251 @end example
16253 One classic incarnation of this bug is:
16255 @example
16256 default="a b c"
16257 : $@{list="$default"@}
16258 for c in $list; do
16259   echo $c
16260 done
16261 @end example
16263 @noindent
16264 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16265 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16266 bit set, hence no IFS splitting is performed!!!
16268 One piece of good news is that Ultrix works fine with @samp{:
16269 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16270 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16271 @var{default}!
16273 The portable way out consists in using a double assignment, to switch
16274 the 8th bit twice on Ultrix:
16276 @example
16277 list=$@{list="$default"@}
16278 @end example
16280 @noindent
16281 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16282 use:
16284 @example
16285 test "$@{var+set@}" = set || var=@var{@{value@}}
16286 @end example
16288 @item $@{#@var{var}@}
16289 @itemx $@{@var{var}%@var{word}@}
16290 @itemx $@{@var{var}%%@var{word}@}
16291 @itemx $@{@var{var}#@var{word}@}
16292 @itemx $@{@var{var}##@var{word}@}
16293 @cindex @code{$@{#@var{var}@}}
16294 @cindex @code{$@{@var{var}%@var{word}@}}
16295 @cindex @code{$@{@var{var}%%@var{word}@}}
16296 @cindex @code{$@{@var{var}#@var{word}@}}
16297 @cindex @code{$@{@var{var}##@var{word}@}}
16298 Posix requires support for these usages, but they do not work with many
16299 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16301 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16302 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16303 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16304 yields the empty string.
16307 @item `@var{commands}`
16308 @cindex @code{`@var{commands}`}
16309 @cindex Command Substitution
16310 Posix requires shells to trim all trailing newlines from command
16311 output before substituting it, so assignments like
16312 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16313 @samp{$file} ends in a newline.
16315 While in general it makes no sense, do not substitute a single builtin
16316 with side effects, because Ash 0.2, trying to optimize, does not fork a
16317 subshell to perform the command.
16319 For instance, if you wanted to check that @command{cd} is silent, do not
16320 use @samp{test -z "`cd /`"} because the following can happen:
16322 @example
16323 $ @kbd{pwd}
16324 /tmp
16325 $ @kbd{test -z "`cd /`" && pwd}
16327 @end example
16329 @noindent
16330 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16332 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16333 command substitution of a native program, if the end of the substitution
16334 is not aligned with the end of the double quote.  This may be worked
16335 around by inserting another pair of quotes:
16337 @example
16338 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16339 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16340 - broken differ: char 4, line 1
16341 @end example
16343 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16344 replace it with a null string, and wrongly evaluate the enclosing
16345 command before entering the trap or ending the script.  This can lead to
16346 spurious errors:
16348 @example
16349 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16350 $ @kbd{^C}
16351 sh: test: hi: unexpected operator/operand
16352 @end example
16354 @noindent
16355 You can avoid this by assigning the command substitution to a temporary
16356 variable:
16358 @example
16359 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16360          if test "x$res" = xhi; then echo yes; fi'}
16361 $ @kbd{^C}
16362 @end example
16364 @item $(@var{commands})
16365 @cindex @code{$(@var{commands})}
16366 This construct is meant to replace @samp{`@var{commands}`},
16367 and it has most of the problems listed under @code{`@var{commands}`}.
16369 This construct can be
16370 nested while this is impossible to do portably with back quotes.
16371 Unfortunately it is not yet universally supported.  Most notably, even recent
16372 releases of Solaris don't support it:
16374 @example
16375 $ @kbd{showrev -c /bin/sh | grep version}
16376 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
16377 $ @kbd{echo $(echo blah)}
16378 syntax error: `(' unexpected
16379 @end example
16381 @noindent
16382 nor does IRIX 6.5's Bourne shell:
16383 @example
16384 $ @kbd{uname -a}
16385 IRIX firebird-image 6.5 07151432 IP22
16386 $ @kbd{echo $(echo blah)}
16387 $(echo blah)
16388 @end example
16390 If you do use @samp{$(@var{commands})}, make sure that the commands
16391 do not start with a parenthesis, as that would cause confusion with
16392 a different notation @samp{$((@var{expression}))} that in modern
16393 shells is an arithmetic expression not a command.  To avoid the
16394 confusion, insert a space between the two opening parentheses.
16396 Avoid @var{commands} that contain unbalanced parentheses in
16397 here-documents, comments, or case statement patterns, as many shells
16398 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16399 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16401 @example
16402 echo $(case x in x) echo hello;; esac)
16403 @end example
16406 @item $((@var{expression}))
16407 @cindex @code{$((@var{expression}))}
16408 Arithmetic expansion is not portable as some shells (most
16409 notably Solaris 10 @command{/bin/sh}) don't support it.
16411 Among shells that do support @samp{$(( ))}, not all of them obey the
16412 Posix rule that octal and hexadecimal constants must be recognized:
16414 @example
16415 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16417 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16419 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16421 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16422 pdksh:  010 + 0x10 : bad number `0x10'
16423 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16425 @end example
16427 When it is available, using arithmetic expansion provides a noticeable
16428 speedup in script execution; but testing for support requires
16429 @command{eval} to avoid syntax errors.  The following construct is used
16430 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16431 arguments are provided in decimal and without a leading zero, and all
16432 operators are properly quoted and appear as distinct arguments:
16434 @example
16435 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16436   eval 'func_arith ()
16437   @{
16438     func_arith_result=$(( $* ))
16439   @}'
16440 else
16441   func_arith ()
16442   @{
16443     func_arith_result=`expr "$@@"`
16444   @}
16446 func_arith 1 + 1
16447 foo=$func_arith_result
16448 @end example
16451 @item ^
16452 @cindex @code{^} quoting
16453 Always quote @samp{^}, otherwise traditional shells such as
16454 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16456 @end table
16459 @node Assignments
16460 @section Assignments
16461 @cindex Shell assignments
16463 When setting several variables in a row, be aware that the order of the
16464 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16465 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16466 You must use
16467 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16469 Don't rely on the following to find @file{subdir/program}:
16471 @example
16472 PATH=subdir$PATH_SEPARATOR$PATH program
16473 @end example
16475 @noindent
16476 as this does not work with Zsh 3.0.6.  Use something like this
16477 instead:
16479 @example
16480 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16481 @end example
16483 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16484 the status and propagates that of the last statement:
16486 @example
16487 $ @kbd{false || foo=bar; echo $?}
16489 $ @kbd{false || foo=`:`; echo $?}
16491 @end example
16493 @noindent
16494 and to make things even worse, QNX 4.25 just sets the exit status
16495 to 0 in any case:
16497 @example
16498 $ @kbd{foo=`exit 1`; echo $?}
16500 @end example
16502 To assign default values, follow this algorithm:
16504 @enumerate
16505 @item
16506 If the default value is a literal and does not contain any closing
16507 brace, use:
16509 @example
16510 : "$@{var='my literal'@}"
16511 @end example
16513 @item
16514 If the default value contains no closing brace, has to be expanded, and
16515 the variable being initialized is not intended to be IFS-split
16516 (i.e., it's not a list), then use:
16518 @example
16519 : $@{var="$default"@}
16520 @end example
16522 @item
16523 If the default value contains no closing brace, has to be expanded, and
16524 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16525 then use:
16527 @example
16528 var=$@{var="$default"@}
16529 @end example
16531 @item
16532 If the default value contains a closing brace, then use:
16534 @example
16535 test "$@{var+set@}" = set || var="has a '@}'"
16536 @end example
16537 @end enumerate
16539 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16540 doubt, just use the last form.  @xref{Shell Substitutions}, items
16541 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16542 for the rationale.
16544 @node Parentheses
16545 @section Parentheses in Shell Scripts
16546 @cindex Shell parentheses
16548 Beware of two opening parentheses in a row, as many shell
16549 implementations treat them specially, and Posix says that a portable
16550 script cannot use @samp{((} outside the @samp{$((} form used for shell
16551 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16552 @samp{(cat)}; but many shells, including
16553 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16554 expression equivalent to @samp{let "cat"}, and may or may not report an
16555 error when they detect that @samp{cat} is not a number.  As another
16556 example, @samp{pdksh} 5.2.14 does not treat the following code
16557 as a traditional shell would:
16559 @example
16560 if ((true) || false); then
16561   echo ok
16563 @end example
16565 @noindent
16566 To work around this problem, insert a space between the two opening
16567 parentheses.  There is a similar problem and workaround with
16568 @samp{$((}; see @ref{Shell Substitutions}.
16570 @node Slashes
16571 @section Slashes in Shell Scripts
16572 @cindex Shell slashes
16574 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16575 arguments that contain two trailing slashes:
16577 @example
16578 $ @kbd{echo / // /// //// .// //.}
16579 / / // /// ./ //.
16580 $ @kbd{x=//}
16581 $ @kbd{eval "echo \$x"}
16583 $ @kbd{set -x}
16584 $ @kbd{echo abc | tr -t ab //}
16585 + echo abc
16586 + tr -t ab /
16588 @end example
16590 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16591 variable is empty and the second double-quote is followed by a word that
16592 begins and ends with slash:
16594 @example
16595 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16597 + echo //ouch/
16598 //ouch/
16599 @end example
16601 However, our understanding is that patches are available, so perhaps
16602 it's not worth worrying about working around these horrendous bugs.
16604 @node Special Shell Variables
16605 @section Special Shell Variables
16606 @cindex Shell variables
16607 @cindex Special shell variables
16609 Some shell variables should not be used, since they can have a deep
16610 influence on the behavior of the shell.  In order to recover a sane
16611 behavior from the shell, some variables should be unset; M4sh takes
16612 care of this and provides fallback values, whenever needed, to cater
16613 for a very old @file{/bin/sh} that does not support @command{unset}.
16614 (@pxref{Portable Shell, , Portable Shell Programming}).
16616 As a general rule, shell variable names containing a lower-case letter
16617 are safe; you can define and use these variables without worrying about
16618 their effect on the underlying system, and without worrying about
16619 whether the shell changes them unexpectedly.  (The exception is the
16620 shell variable @code{status}, as described below.)
16622 Here is a list of names that are known to cause trouble.  This list is
16623 not exhaustive, but you should be safe if you avoid the name
16624 @code{status} and names containing only upper-case letters and
16625 underscores.
16627 @c Alphabetical order, case insensitive, `A' before `a'.
16628 @table @code
16629 @item ?
16630 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16631 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16632 correctly in shell functions (@pxref{Shell Functions}) or in traps
16633 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16634 @samp{$?} to zero after an empty command.
16636 @example
16637 $ @kbd{bash -c 'false; $empty; echo $?'}
16639 $ @kbd{zsh -c 'false; $empty; echo $?'}
16641 @end example
16643 @item _
16644 @evindex _
16645 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16646 the last command executed.
16648 @item BIN_SH
16649 @evindex BIN_SH
16650 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16651 the standard shell conform to Posix.
16653 @item CDPATH
16654 @evindex CDPATH
16655 When this variable is set it specifies a list of directories to search
16656 when invoking @code{cd} with a relative file name that did not start
16657 with @samp{./} or @samp{../}.  Posix
16658 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16659 is used successfully, @code{cd} prints the resulting absolute
16660 file name.  Unfortunately this output can break idioms like
16661 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16662 Also, many shells do not conform to this part of Posix; for
16663 example, @command{zsh} prints the result only if a directory name
16664 other than @file{.} was chosen from @env{CDPATH}.
16666 In practice the shells that have this problem also support
16667 @command{unset}, so you can work around the problem as follows:
16669 @example
16670 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16671 @end example
16673 You can also avoid output by ensuring that your directory name is
16674 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16676 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16677 possible, so you need not worry about this problem in those scripts.
16679 @item CLICOLOR_FORCE
16680 @evindex CLICOLOR_FORCE
16681 When this variable is set, some implementations of tools like
16682 @command{ls} attempt to add color to their output via terminal escape
16683 sequences, even when the output is not directed to a terminal, and can
16684 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16685 which automatically unsets this variable.
16687 @item DUALCASE
16688 @evindex DUALCASE
16689 In the MKS shell, case statements and file name generation are
16690 case-insensitive unless @env{DUALCASE} is nonzero.
16691 Autoconf-generated scripts export this variable when they start up.
16693 @item ENV
16694 @itemx MAIL
16695 @itemx MAILPATH
16696 @itemx PS1
16697 @itemx PS2
16698 @itemx PS4
16699 @evindex ENV
16700 @evindex MAIL
16701 @evindex MAILPATH
16702 @evindex PS1
16703 @evindex PS2
16704 @evindex PS4
16705 These variables should not matter for shell scripts, since they are
16706 supposed to affect only interactive shells.  However, at least one
16707 shell (the pre-3.0 UWIN Korn shell) gets confused about
16708 whether it is interactive, which means that (for example) a @env{PS1}
16709 with a side effect can unexpectedly modify @samp{$?}.  To work around
16710 this bug, M4sh scripts (including @file{configure} scripts) do something
16711 like this:
16713 @example
16714 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16715 PS1='$ '
16716 PS2='> '
16717 PS4='+ '
16718 @end example
16720 @noindent
16721 (actually, there is some complication due to bugs in @command{unset};
16722 see @pxref{unset, , Limitations of Shell Builtins}).
16724 @item FPATH
16725 @evindex FPATH
16726 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16727 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16728 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16729 to find whether a command exists, since they might report the wrong
16730 result if @env{FPATH} is also set.
16732 @item GREP_OPTIONS
16733 @evindex GREP_OPTIONS
16734 When this variable is set, some implementations of @command{grep} honor
16735 these options, even if the options include direction to enable colored
16736 output via terminal escape sequences, and the result can cause spurious
16737 failures when the output is not directed to a terminal.  Configure
16738 scripts use M4sh, which automatically unsets this variable.
16740 @item IFS
16741 @evindex IFS
16742 Long ago, shell scripts inherited @env{IFS} from the environment,
16743 but this caused many problems so modern shells ignore any environment
16744 settings for @env{IFS}.
16746 Don't set the first character of @env{IFS} to backslash.  Indeed,
16747 Bourne shells use the first character (backslash) when joining the
16748 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16749 backslash escapes, so you can end up with backspace and other strange
16750 characters.
16752 The proper value for @env{IFS} (in regular code, not when performing
16753 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16754 especially important, as it is used to join the arguments in @samp{$*};
16755 however, note that traditional shells, but also bash-2.04, fail to adhere
16756 to this and join with a space anyway.
16758 M4sh guarantees that @env{IFS} will have the default value at the
16759 beginning of a script, and many macros within autoconf rely on this
16760 setting.  It is okay to use blocks of shell code that temporarily change
16761 the value of @env{IFS} in order to split on another character, but
16762 remember to restore it before expanding further macros.
16764 Unsetting @code{IFS} instead of resetting it to the default sequence
16765 is not suggested, since code that tries to save and restore the
16766 variable's value will incorrectly reset it to an empty value, thus
16767 disabling field splitting:
16769 @example
16770 unset IFS
16771 # default separators used for field splitting
16773 save_IFS=$IFS
16774 IFS=:
16775 # ...
16776 IFS=$save_IFS
16777 # no field splitting performed
16778 @end example
16780 @item LANG
16781 @itemx LC_ALL
16782 @itemx LC_COLLATE
16783 @itemx LC_CTYPE
16784 @itemx LC_MESSAGES
16785 @itemx LC_MONETARY
16786 @itemx LC_NUMERIC
16787 @itemx LC_TIME
16788 @evindex LANG
16789 @evindex LC_ALL
16790 @evindex LC_COLLATE
16791 @evindex LC_CTYPE
16792 @evindex LC_MESSAGES
16793 @evindex LC_MONETARY
16794 @evindex LC_NUMERIC
16795 @evindex LC_TIME
16797 You should set all these variables to @samp{C} because so much
16798 configuration code assumes the C locale and Posix requires that locale
16799 environment variables be set to @samp{C} if the C locale is desired;
16800 @file{configure} scripts and M4sh do that for you.
16801 Export these variables after setting them.
16803 @c  However, some older, nonstandard
16804 @c  systems (notably SCO) break if locale environment variables
16805 @c  are set to @samp{C}, so when running on these systems
16806 @c  Autoconf-generated scripts unset the variables instead.
16808 @item LANGUAGE
16809 @evindex LANGUAGE
16811 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16812 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16813 should set it too.
16815 @item LC_ADDRESS
16816 @itemx LC_IDENTIFICATION
16817 @itemx LC_MEASUREMENT
16818 @itemx LC_NAME
16819 @itemx LC_PAPER
16820 @itemx LC_TELEPHONE
16821 @evindex LC_ADDRESS
16822 @evindex LC_IDENTIFICATION
16823 @evindex LC_MEASUREMENT
16824 @evindex LC_NAME
16825 @evindex LC_PAPER
16826 @evindex LC_TELEPHONE
16828 These locale environment variables are GNU extensions.  They
16829 are treated like their Posix brethren (@env{LC_COLLATE},
16830 etc.)@: as described above.
16832 @item LINENO
16833 @evindex LINENO
16834 Most modern shells provide the current line number in @code{LINENO}.
16835 Its value is the line number of the beginning of the current command.
16836 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16837 a shell that supports @code{LINENO}.  If no such shell is available, it
16838 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16839 instance of the string @code{$LINENO} (not followed by an alphanumeric
16840 character) with the line's number.  In M4sh scripts you should execute
16841 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16842 your script; configure scripts do this automatically in @code{AC_INIT}.
16844 You should not rely on @code{LINENO} within @command{eval} or shell
16845 functions, as the behavior differs in practice.  The presence of a
16846 quoted newline within simple commands can alter which line number is
16847 used as the starting point for @code{$LINENO} substitutions within that
16848 command.  Also, the possibility of the Sed prepass means that you should
16849 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16850 line continuations are used.  Subshells should be OK, though.  In the
16851 following example, lines 1, 9, and 14 are portable, but the other
16852 instances of @code{$LINENO} do not have deterministic values:
16854 @example
16855 @group
16856 $ @kbd{cat lineno}
16857 echo 1. $LINENO
16858 echo "2. $LINENO
16859 3. $LINENO"
16860 cat <<EOF
16861 5. $LINENO
16862 6. $LINENO
16863 7. \$LINENO
16865 ( echo 9. $LINENO )
16866 eval 'echo 10. $LINENO'
16867 eval 'echo 11. $LINENO
16868 echo 12. $LINENO'
16869 echo 13. '$LINENO'
16870 echo 14. $LINENO '
16871 15.' $LINENO
16872 f () @{ echo $1 $LINENO;
16873 echo $1 $LINENO @}
16874 f 18.
16875 echo 19. \
16876 $LINENO
16877 @end group
16878 @group
16879 $ @kbd{bash-3.2 ./lineno}
16880 1. 1
16881 2. 3
16882 3. 3
16883 5. 4
16884 6. 4
16885 7. $LINENO
16886 9. 9
16887 10. 10
16888 11. 12
16889 12. 13
16890 13. $LINENO
16891 14. 14
16892 15. 14
16893 18. 16
16894 18. 17
16895 19. 19
16896 @end group
16897 @group
16898 $ @kbd{zsh-4.3.4 ./lineno}
16899 1. 1
16900 2. 2
16901 3. 2
16902 5. 4
16903 6. 4
16904 7. $LINENO
16905 9. 9
16906 10. 1
16907 11. 1
16908 12. 2
16909 13. $LINENO
16910 14. 14
16911 15. 14
16912 18. 0
16913 18. 1
16914 19. 19
16915 @end group
16916 @group
16917 $ @kbd{pdksh-5.2.14 ./lineno}
16918 1. 1
16919 2. 2
16920 3. 2
16921 5. 4
16922 6. 4
16923 7. $LINENO
16924 9. 9
16925 10. 0
16926 11. 0
16927 12. 0
16928 13. $LINENO
16929 14. 14
16930 15. 14
16931 18. 16
16932 18. 17
16933 19. 19
16934 @end group
16935 @group
16936 $ @kbd{sed '=' <lineno |}
16937 > @kbd{  sed '}
16938 > @kbd{    N}
16939 > @kbd{    s,$,-,}
16940 > @kbd{    t loop}
16941 > @kbd{    :loop}
16942 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16943 > @kbd{    t loop}
16944 > @kbd{    s,-$,,}
16945 > @kbd{    s,^[0-9]*\n,,}
16946 > @kbd{  ' |}
16947 > @kbd{  sh}
16948 1. 1
16949 2. 2
16950 3. 3
16951 5. 5
16952 6. 6
16953 7. \7
16954 9. 9
16955 10. 10
16956 11. 11
16957 12. 12
16958 13. 13
16959 14. 14
16960 15. 15
16961 18. 16
16962 18. 17
16963 19. 20
16964 @end group
16965 @end example
16967 In particular, note that @file{config.status} (and any other subsidiary
16968 script created by @code{AS_INIT_GENERATED}) might report line numbers
16969 relative to the parent script as a result of the potential Sed pass.
16971 @item NULLCMD
16972 @evindex NULLCMD
16973 When executing the command @samp{>foo}, @command{zsh} executes
16974 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
16975 compatibility mode and the @command{zsh} version is newer
16976 than 3.1.6-dev-18.  If you are using an older @command{zsh}
16977 and forget to set @env{NULLCMD},
16978 your script might be suspended waiting for data on its standard input.
16980 @item options
16981 @evindex options
16982 For @command{zsh} 4.3.10, @env{options} is treated as an associative
16983 array even after @code{emulate sh}, so it should not be used.
16985 @item PATH_SEPARATOR
16986 @evindex PATH_SEPARATOR
16987 On DJGPP systems, the @env{PATH_SEPARATOR} environment
16988 variable can be set to either @samp{:} or @samp{;} to control the path
16989 separator Bash uses to set up certain environment variables (such as
16990 @env{PATH}).  You can set this variable to @samp{;} if you want
16991 @command{configure} to use @samp{;} as a separator; this might be useful
16992 if you plan to use non-Posix shells to execute files.  @xref{File System
16993 Conventions}, for more information about @code{PATH_SEPARATOR}.
16995 @item POSIXLY_CORRECT
16996 @evindex POSIXLY_CORRECT
16997 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
16998 (even empty) causes programs to try harder to conform to Posix.
16999 Autoconf does not directly manipulate this variable, but @command{bash}
17000 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17001 running in Posix mode.  Therefore, take care when exporting or unsetting
17002 this variable, so as not to change whether @command{bash} is in Posix
17003 mode.
17005 @example
17006 $ @kbd{bash --posix -c 'set -o | grep posix}
17007 > @kbd{unset POSIXLY_CORRECT}
17008 > @kbd{set -o | grep posix'}
17009 posix           on
17010 posix           off
17011 @end example
17013 @item PWD
17014 @evindex PWD
17015 Posix 1003.1-2001 requires that @command{cd} and
17016 @command{pwd} must update the @env{PWD} environment variable to point
17017 to the logical name of the current directory, but traditional shells
17018 do not support this.  This can cause confusion if one shell instance
17019 maintains @env{PWD} but a subsidiary and different shell does not know
17020 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17021 points to the wrong directory.  Use @samp{`pwd`} rather than
17022 @samp{$PWD}.
17024 @item RANDOM
17025 @evindex RANDOM
17026 Many shells provide @code{RANDOM}, a variable that returns a different
17027 integer each time it is used.  Most of the time, its value does not
17028 change when it is not used, but on IRIX 6.5 the value changes all
17029 the time.  This can be observed by using @command{set}.  It is common
17030 practice to use @code{$RANDOM} as part of a file name, but code
17031 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17033 @item status
17034 @evindex status
17035 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17036 hence read-only.  Do not use it.
17037 @end table
17039 @node Shell Functions
17040 @section Shell Functions
17041 @cindex Shell Functions
17043 Nowadays, it is difficult to find a shell that does not support
17044 shell functions at all.  However, some differences should be expected.
17046 When declaring a shell function, you must include whitespace between the
17047 @samp{)} after the function name and the start of the compound
17048 expression, to avoid upsetting @command{ksh}.  While it is possible to
17049 use any compound command, most scripts use @samp{@{@dots{}@}}.
17051 @example
17052 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17054 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17055 ksh: syntax error at line 1: `@}' unexpected
17056 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17058 @end example
17060 Inside a shell function, you should not rely on the error status of a
17061 subshell if the last command of that subshell was @code{exit} or
17062 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17063 find a shell that does not exhibit the bug, zsh might be the only shell
17064 present on the user's machine.
17066 Likewise, the state of @samp{$?} is not reliable when entering a shell
17067 function.  This has the effect that using a function as the first
17068 command in a @command{trap} handler can cause problems.
17070 @example
17071 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17074 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17077 @end example
17079 DJGPP bash 2.04 has a bug in that @command{return} from a
17080 shell function which also used a command substitution causes a
17081 segmentation fault.  To work around the issue, you can use
17082 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17083 in the execution flow of the function (@pxref{Common Shell Constructs}).
17085 Not all shells treat shell functions as simple commands impacted by
17086 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17088 @example
17089 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17090 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17091 oops
17092 @end example
17094 Shell variables and functions may share the same namespace, for example
17095 with Solaris 10 @command{/bin/sh}:
17097 @example
17098 $ @kbd{f () @{ :; @}; f=; f}
17099 f: not found
17100 @end example
17102 @noindent
17103 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17104 uses the prefix @samp{as_fn_} for its functions.
17106 Handling of positional parameters and shell options varies among shells.
17107 For example, Korn shells reset and restore trace output (@samp{set -x})
17108 and other options upon function entry and exit.  Inside a function,
17109 IRIX sh sets @samp{$0} to the function name.
17111 It is not portable to pass temporary environment variables to shell
17112 functions.  Solaris @command{/bin/sh} does not see the variable.
17113 Meanwhile, not all shells follow the Posix rule that the assignment must
17114 affect the current environment in the same manner as special built-ins.
17116 @example
17117 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17118 @result{}
17119 @result{}
17120 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17121 @result{}1
17122 @result{}
17123 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17124 @result{}1
17125 @result{}1
17126 @end example
17128 Some ancient Bourne shell variants with function support did not reset
17129 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17130 arguments of the script were lost after the first function invocation.
17131 It is probably not worth worrying about these shells any more.
17133 With AIX sh, a @command{trap} on 0 installed in a shell function
17134 triggers at function exit rather than at script exit.  @xref{trap, ,
17135 Limitations of Shell Builtins}.
17137 @node Limitations of Builtins
17138 @section Limitations of Shell Builtins
17139 @cindex Shell builtins
17140 @cindex Limitations of shell builtins
17142 No, no, we are serious: some shells do have limitations!  :)
17144 You should always keep in mind that any builtin or command may support
17145 options, and therefore differ in behavior with arguments
17146 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17147 can give unexpected results when @code{word} starts with a dash.  It is
17148 often possible to avoid this problem using @samp{echo "x$word"}, taking
17149 the @samp{x} into account later in the pipe.  Many of these limitations
17150 can be worked around using M4sh (@pxref{Programming in M4sh}).
17152 @c This table includes things like `@command{test} (files)', so we can't
17153 @c use @table @command.
17154 @table @asis
17155 @item @command{.}
17156 @c --------------
17157 @prindex @command{.}
17158 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17159 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17160 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17161 some shells, including bash 3.2, implicitly append the current directory
17162 to this @env{PATH} search, even though Posix forbids it.  So if you want
17163 to use @command{.} on a file @file{foo} in the current directory, you
17164 must use @samp{. ./foo}.
17166 Not all shells gracefully handle syntax errors within a sourced file.
17167 On one extreme, some non-interactive shells abort the entire script.  On
17168 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17169 syntax error.
17171 @example
17172 $ @kbd{echo 'fi' > syntax}
17173 $ @kbd{bash -c '. ./syntax; echo $?'}
17174 ./syntax: line 1: syntax error near unexpected token `fi'
17175 ./syntax: line 1: `fi'
17177 $ @kbd{ash -c '. ./syntax; echo $?'}
17178 ./syntax: 1: Syntax error: "fi" unexpected
17179 $ @kbd{zsh -c '. ./syntax; echo $?'}
17180 ./syntax:1: parse error near `fi'
17182 @end example
17184 @item @command{!}
17185 @c --------------
17186 @prindex @command{!}
17187 The Unix version 7 shell did not support
17188 negating the exit status of commands with @command{!}, and this feature
17189 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17190 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17191 bugs when using @command{!}:
17193 @example
17194 $ @kbd{sh -c '! : | :'; echo $?}
17196 $ @kbd{ash -c '! : | :'; echo $?}
17198 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17200 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17201 @{: not found
17202 Syntax error: "@}" unexpected
17204 @end example
17206 Shell code like this:
17208 @example
17209 if ! cmp file1 file2 >/dev/null 2>&1; then
17210   echo files differ or trouble
17212 @end example
17214 is therefore not portable in practice.  Typically it is easy to rewrite
17215 such code, e.g.:
17217 @example
17218 cmp file1 file2 >/dev/null 2>&1 ||
17219   echo files differ or trouble
17220 @end example
17222 More generally, one can always rewrite @samp{! @var{command}} as:
17224 @example
17225 if @var{command}; then (exit 1); else :; fi
17226 @end example
17229 @item @command{@{...@}}
17230 @c --------------------
17231 @prindex @command{@{...@}}
17232 Bash 3.2 (and earlier versions) sometimes does not properly set
17233 @samp{$?} when failing to write redirected output of a compound command.
17234 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17235 not occur with @samp{(@dots{})}.  For example:
17237 @example
17238 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17239 bash: line 1: /bad: Permission denied
17241 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17242 bash: line 1: /bad: Permission denied
17244 @end example
17246 To work around the bug, prepend @samp{:;}:
17248 @example
17249 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17250 bash: line 1: /bad: Permission denied
17252 @end example
17254 Posix requires a syntax error if a brace list has no contents.  However,
17255 not all shells obey this rule; and on shells where empty lists are
17256 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17257 ensure that a brace list is never empty.
17259 @example
17260 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17261 bash: line 1: syntax error near unexpected token `@}'
17262 bash: line 1: `false; @{ @}; echo $?'
17264 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17266 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17268 @end example
17271 @item @command{break}
17272 @c ------------------
17273 @prindex @command{break}
17274 The use of @samp{break 2} etc.@: is safe.
17277 @anchor{case}
17278 @item @command{case}
17279 @c -----------------
17280 @prindex @command{case}
17281 You don't need to quote the argument; no splitting is performed.
17283 You don't need the final @samp{;;}, but you should use it.
17285 Posix requires support for @code{case} patterns with opening
17286 parentheses like this:
17288 @example
17289 case $file_name in
17290   (*.c) echo "C source code";;
17291 esac
17292 @end example
17294 @noindent
17295 but the @code{(} in this example is not portable to many Bourne
17296 shell implementations, which is a pity for those of us using tools that
17297 rely on balanced parentheses.  For instance, with Solaris
17298 @command{/bin/sh}:
17300 @example
17301 $ @kbd{case foo in (foo) echo foo;; esac}
17302 @error{}syntax error: `(' unexpected
17303 @end example
17305 @noindent
17306 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17307 contexts where unbalanced parentheses cause other problems, such as when
17308 using a syntax-highlighting editor that searches for the balancing
17309 counterpart, or more importantly, when using a case statement as an
17310 underquoted argument to an Autoconf macro.  @xref{Balancing
17311 Parentheses}, for tradeoffs involved in various styles of dealing with
17312 unbalanced @samp{)}.
17314 Zsh handles pattern fragments derived from parameter expansions or
17315 command substitutions as though quoted:
17317 @example
17318 $ pat=\?; case aa in ?$pat) echo match;; esac
17319 $ pat=\?; case a? in ?$pat) echo match;; esac
17320 match
17321 @end example
17323 @noindent
17324 Because of a bug in its @code{fnmatch}, Bash fails to properly
17325 handle backslashes in character classes:
17327 @example
17328 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17329 bash-2.02$
17330 @end example
17332 @noindent
17333 This is extremely unfortunate, since you are likely to use this code to
17334 handle Posix or MS-DOS absolute file names.  To work around this
17335 bug, always put the backslash first:
17337 @example
17338 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17340 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17342 @end example
17344 Many Bourne shells cannot handle closing brackets in character classes
17345 correctly.
17347 Some shells also have problems with backslash escaping in case you do not want
17348 to match the backslash: both a backslash and the escaped character match this
17349 pattern.  To work around this, specify the character class in a variable, so
17350 that quote removal does not apply afterwards, and the special characters don't
17351 have to be backslash-escaped:
17353 @example
17354 $ @kbd{case '\' in [\<]) echo OK;; esac}
17356 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17358 @end example
17360 Even with this, Solaris @command{ksh} matches a backslash if the set
17361 contains any
17362 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17364 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17365 a closing parenthesis if not specified in a character class:
17367 @example
17368 $ @kbd{case foo in *\)*) echo fail ;; esac}
17369 fail
17370 $ @kbd{case foo in *')'*) echo fail ;; esac}
17371 fail
17372 @end example
17374 Some shells, such as Ash 0.3.8, are confused by an empty
17375 @code{case}/@code{esac}:
17377 @example
17378 ash-0.3.8 $ @kbd{case foo in esac;}
17379 @error{}Syntax error: ";" unexpected (expecting ")")
17380 @end example
17382 Posix requires @command{case} to give an exit status of 0 if no cases
17383 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17384 rule.  Meanwhile, it is unclear whether a case that matches, but
17385 contains no statements, must also change the exit status to 0.  The M4sh
17386 macro @code{AS_CASE} works around these inconsistencies.
17388 @example
17389 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17391 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17393 @end example
17396 @item @command{cd}
17397 @c ---------------
17398 @prindex @command{cd}
17399 Posix 1003.1-2001 requires that @command{cd} must support
17400 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17401 with @option{-L} being the default.  However, traditional shells do
17402 not support these options, and their @command{cd} command has the
17403 @option{-P} behavior.
17405 Portable scripts should assume neither option is supported, and should
17406 assume neither behavior is the default.  This can be a bit tricky,
17407 since the Posix default behavior means that, for example,
17408 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17409 the current logical directory is a symbolic link.  It is safe to use
17410 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17411 Also, Autoconf-generated scripts check for this problem when computing
17412 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17413 so it is safe to @command{cd} to these variables.
17415 Posix states that behavior is undefined if @command{cd} is given an
17416 explicit empty argument.  Some shells do nothing, some change to the
17417 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17418 the shell rather than returning an error.  Unfortunately, this means
17419 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17420 than @samp{cd $var} (at least the latter is well-behaved in all shells
17421 at changing to @env{HOME}, although this is probably not what you wanted
17422 in a script).  You should check that a directory name was supplied
17423 before trying to change locations.
17425 @xref{Special Shell Variables}, for portability problems involving
17426 @command{cd} and the @env{CDPATH} environment variable.
17427 Also please see the discussion of the @command{pwd} command.
17430 @anchor{echo}
17431 @item @command{echo}
17432 @c -----------------
17433 @prindex @command{echo}
17434 The simple @command{echo} is probably the most surprising source of
17435 portability troubles.  It is not possible to use @samp{echo} portably
17436 unless both options and escape sequences are omitted.  Don't expect any
17437 option.
17439 Do not use backslashes in the arguments, as there is no consensus on
17440 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17441 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17442 The problem is truly @command{echo}: all the shells
17443 understand @samp{'\n'} as the string composed of a backslash and an
17444 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17445 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17446 the first character @samp{s} only, followed by a newline, and then
17447 entirely drop the output of the next echo in a command substitution.
17449 Because of these problems, do not pass a string containing arbitrary
17450 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17451 only if you know that @var{foo}'s value cannot contain backslashes and
17452 cannot start with @samp{-}.
17454 If this may not be true, @command{printf} is in general safer and
17455 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
17456 where portability is not a major concern should use @command{printf
17457 '%s\n'} whenever @command{echo} could fail, and similarly use
17458 @command{printf %s} instead of @command{echo -n}. For portable shell
17459 scripts, instead, it is suggested to use a here-document like this:
17461 @example
17462 cat <<EOF
17463 $foo
17465 @end example
17467 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
17468 which choose between various portable implementations: @samp{echo}
17469 or @samp{print} where they work, @command{printf} if it is available,
17470 or else other creative tricks in order to work around the above problems.
17473 @item @command{eval}
17474 @c -----------------
17475 @prindex @command{eval}
17476 The @command{eval} command is useful in limited circumstances, e.g.,
17477 using commands like @samp{eval table_$key=\$value} and @samp{eval
17478 value=table_$key} to simulate a hash table when the key is known to be
17479 alphanumeric.
17481 You should also be wary of common bugs in @command{eval} implementations.
17482 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17483 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17484 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17485 @samp{$?} is 0, so they exhibit behavior like this:
17487 @example
17488 $ @kbd{false; eval 'echo $?'}
17490 @end example
17492 The correct behavior here is to output a nonzero value,
17493 but portable scripts should not rely on this.
17495 You should not rely on @code{LINENO} within @command{eval}.
17496 @xref{Special Shell Variables}.
17498 Note that, even though these bugs are easily avoided,
17499 @command{eval} is tricky to use on arbitrary arguments.
17500 It is obviously unwise to use @samp{eval $cmd} if the string value of
17501 @samp{cmd} was derived from an untrustworthy source.  But even if the
17502 string value is valid, @samp{eval $cmd} might not work as intended,
17503 since it causes field splitting and file name expansion to occur twice,
17504 once for the @command{eval} and once for the command itself.  It is
17505 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17506 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17507 equivalent of @samp{cat test;.c} if there happens to be a file named
17508 @file{test;.c} in the current directory; and this in turn
17509 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17510 then execute the command @command{.c}.  To avoid this problem, use
17511 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17513 However, suppose that you want to output the text of the evaluated
17514 command just before executing it.  Assuming the previous example,
17515 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17516 this output doesn't show the user that @samp{test;.c} is the actual name
17517 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17518 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17519 since it mistakenly replaces the contents of @file{bar} by the
17520 string @samp{cat foo}.  No simple, general, and portable solution to
17521 this problem is known.
17523 @item @command{exec}
17524 @c -----------------
17525 @prindex @command{exec}
17526 Posix describes several categories of shell built-ins.  Special
17527 built-ins (such as @command{exit}) must impact the environment of the
17528 current shell, and need not be available through @command{exec}.  All
17529 other built-ins are regular, and must not propagate variable assignments
17530 to the environment of the current shell.  However, the group of regular
17531 built-ins is further distinguished by commands that do not require a
17532 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17533 are offered as a more efficient version of something that must still be
17534 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17535 clear on whether @command{exec} must work with the list of 17 utilities
17536 that are invoked without a @env{PATH} search, and many platforms lack an
17537 executable for some of those built-ins:
17539 @example
17540 $ @kbd{sh -c 'exec cd /tmp'}
17541 sh: line 0: exec: cd: not found
17542 @end example
17544 All other built-ins that provide utilities specified by Posix must have
17545 a counterpart executable that exists on @env{PATH}, although Posix
17546 allows @command{exec} to use the built-in instead of the executable.
17547 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17549 @example
17550 $ @kbd{bash -c 'pwd --version' | head -n1}
17551 bash: line 0: pwd: --: invalid option
17552 pwd: usage: pwd [-LP]
17553 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17554 pwd (GNU coreutils) 6.10
17555 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17556 pdksh: pwd: --: unknown option
17557 @end example
17559 When it is desired to avoid a regular shell built-in, the workaround is
17560 to use some other forwarding command, such as @command{env} or
17561 @command{nice}, that will ensure a path search:
17563 @example
17564 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17565 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17566 true (GNU coreutils) 6.10
17567 $ @kbd{pdksh -c 'env true --version' | head -n1}
17568 true (GNU coreutils) 6.10
17569 @end example
17571 @item @command{exit}
17572 @c -----------------
17573 @prindex @command{exit}
17574 The default value of @command{exit} is supposed to be @code{$?};
17575 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17576 perform @samp{exit 0}.
17578 @example
17579 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17580 fail
17581 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17582 fail
17583 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17584 bash-2.04$
17585 @end example
17587 Using @samp{exit $?} restores the expected behavior.
17589 Some shell scripts, such as those generated by @command{autoconf}, use a
17590 trap to clean up before exiting.  If the last shell command exited with
17591 nonzero status, the trap also exits with nonzero status so that the
17592 invoker can tell that an error occurred.
17594 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17595 trap ignores the @code{exit} command's argument.  In these shells, a trap
17596 cannot determine whether it was invoked by plain @code{exit} or by
17597 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17598 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17601 @anchor{export}
17602 @item @command{export}
17603 @c -------------------
17604 @prindex @command{export}
17605 The builtin @command{export} dubs a shell variable @dfn{environment
17606 variable}.  Each update of exported variables corresponds to an update
17607 of the environment variables.  Conversely, each environment variable
17608 received by the shell when it is launched should be imported as a shell
17609 variable marked as exported.
17611 Alas, many shells, such as Solaris @command{/bin/sh},
17612 IRIX 6.3, IRIX 5.2,
17613 AIX 4.1.5, and Digital Unix 4.0, forget to
17614 @command{export} the environment variables they receive.  As a result,
17615 two variables coexist: the environment variable and the shell
17616 variable.  The following code demonstrates this failure:
17618 @example
17619 #!/bin/sh
17620 echo $FOO
17621 FOO=bar
17622 echo $FOO
17623 exec /bin/sh $0
17624 @end example
17626 @noindent
17627 when run with @samp{FOO=foo} in the environment, these shells print
17628 alternately @samp{foo} and @samp{bar}, although they should print only
17629 @samp{foo} and then a sequence of @samp{bar}s.
17631 Therefore you should @command{export} again each environment variable
17632 that you update; the export can occur before or after the assignment.
17634 Posix is not clear on whether the @command{export} of an undefined
17635 variable causes the variable to be defined with the value of an empty
17636 string, or merely marks any future definition of a variable by that name
17637 for export.  Various shells behave differently in this regard:
17639 @example
17640 $ @kbd{sh -c 'export foo; env | grep foo'}
17641 $ @kbd{ash -c 'export foo; env | grep foo'}
17642 foo=
17643 @end example
17645 Posix requires @command{export} to honor assignments made as arguments,
17646 but older shells do not support this, including @command{/bin/sh} in
17647 Solaris 10.  Portable scripts should separate assignments and exports
17648 into different statements.
17650 @example
17651 $ @kbd{bash -c 'export foo=bar; echo $foo'}
17653 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17654 /bin/sh: foo=bar: is not an identifier
17655 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17657 @end example
17659 @item @command{false}
17660 @c ------------------
17661 @prindex @command{false}
17662 Don't expect @command{false} to exit with status 1: in native
17663 Solaris @file{/bin/false} exits with status 255.
17666 @item @command{for}
17667 @c ----------------
17668 @prindex @command{for}
17669 To loop over positional arguments, use:
17671 @example
17672 for arg
17674   echo "$arg"
17675 done
17676 @end example
17678 @noindent
17679 You may @emph{not} leave the @code{do} on the same line as @code{for},
17680 since some shells improperly grok:
17682 @example
17683 for arg; do
17684   echo "$arg"
17685 done
17686 @end example
17688 If you want to explicitly refer to the positional arguments, given the
17689 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17691 @example
17692 for arg in $@{1+"$@@"@}; do
17693   echo "$arg"
17694 done
17695 @end example
17697 @noindent
17698 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17699 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17700 item @samp{$@@}, for more.
17702 In Solaris @command{/bin/sh}, when the list of arguments of a
17703 @command{for} loop starts with @emph{unquoted} tokens looking like
17704 variable assignments, the loop is not executed on those tokens:
17706 @example
17707 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17710 @end example
17712 @noindent
17713 Thankfully, quoting the assignment-like tokens, or starting the list
17714 with other tokens (including unquoted variable expansion that results in
17715 an assignment-like result), avoids the problem, so it is easy to work
17716 around:
17718 @example
17719 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17721 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17724 @end example
17726 @anchor{if}
17727 @item @command{if}
17728 @c ---------------
17729 @prindex @command{if}
17730 Using @samp{!} is not portable.  Instead of:
17732 @example
17733 if ! cmp -s file file.new; then
17734   mv file.new file
17736 @end example
17738 @noindent
17739 use:
17741 @example
17742 if cmp -s file file.new; then :; else
17743   mv file.new file
17745 @end example
17747 @noindent
17748 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17749 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17750 of conditionals:
17752 @example
17753 AS_IF([cmp -s file file.new], [], [mv file.new file])
17754 @end example
17756 This is especially useful in other M4 macros, where the @dfn{then} and
17757 @dfn{else} branches might be macro arguments.
17759 Some very old shells did not reset the exit status from an @command{if}
17760 with no @command{else}:
17762 @example
17763 $ @kbd{if (exit 42); then true; fi; echo $?}
17765 @end example
17767 @noindent
17768 whereas a proper shell should have printed @samp{0}.  But this is no
17769 longer a portability problem; any shell that supports functions gets it
17770 correct.  However, it explains why some makefiles have lengthy
17771 constructs:
17773 @example
17774 if test -f "$file"; then
17775   install "$file" "$dest"
17776 else
17777   :
17779 @end example
17782 @item @command{printf}
17783 @c ------------------
17784 @prindex @command{printf}
17785 A format string starting with a @samp{-} can cause problems.
17786 Bash interprets it as an option and
17787 gives an error.  And @samp{--} to mark the end of options is not good
17788 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17789 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17790 or @samp{%s} is probably easiest:
17792 @example
17793 printf %s -foo
17794 @end example
17796 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17798 @example
17799 $ @kbd{printf '\045'}
17800 bash: printf: `%': missing format character
17801 @end example
17803 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17804 example, @file{/usr/bin/printf} is buggy, so when using
17805 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17806 core.
17808 Since @command{printf} is not always a shell builtin, there is a
17809 potential speed penalty for using @code{printf '%s\n'} as a replacement
17810 for an @command{echo} that does not interpret @samp{\} or leading
17811 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17812 -r --} for this role instead.
17814 For a discussion of portable alternatives to both @command{printf}
17815 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
17818 @item @command{pwd}
17819 @c ----------------
17820 @prindex @command{pwd}
17821 With modern shells, plain @command{pwd} outputs a ``logical''
17822 directory name, some of whose components may be symbolic links.  These
17823 directory names are in contrast to ``physical'' directory names, whose
17824 components are all directories.
17826 Posix 1003.1-2001 requires that @command{pwd} must support
17827 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17828 with @option{-L} being the default.  However, traditional shells do
17829 not support these options, and their @command{pwd} command has the
17830 @option{-P} behavior.
17832 Portable scripts should assume neither option is supported, and should
17833 assume neither behavior is the default.  Also, on many hosts
17834 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17835 does not require this behavior and portable scripts should not rely on
17838 Typically it's best to use plain @command{pwd}.  On modern hosts this
17839 outputs logical directory names, which have the following advantages:
17841 @itemize @bullet
17842 @item
17843 Logical names are what the user specified.
17844 @item
17845 Physical names may not be portable from one installation
17846 host to another due to network file system gymnastics.
17847 @item
17848 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17849 some parent directory, but plain @command{pwd} cannot fail for this
17850 reason.
17851 @end itemize
17853 Also please see the discussion of the @command{cd} command.
17856 @item @command{read}
17857 @c -----------------
17858 @prindex @command{read}
17859 No options are portable, not even support @option{-r} (Solaris
17860 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
17861 @command{read} as a special built-in, so it may exit if input is
17862 redirected from a non-existent or unreadable file.
17865 @anchor{set}
17866 @item @command{set}
17867 @c ----------------
17868 @prindex @command{set}
17869 With the FreeBSD 6.0 shell, the @command{set} command (without
17870 any options) does not sort its output.
17872 The @command{set} builtin faces the usual problem with arguments
17873 starting with a
17874 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17875 the end of the options (any argument after @option{--} is a parameter,
17876 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
17877 10 @command{/bin/sh}) simply stop option
17878 processing as soon as a non-option argument is found.  Therefore, use
17879 @samp{dummy} or simply @samp{x} to end the option processing, and use
17880 @command{shift} to pop it out:
17882 @example
17883 set x $my_list; shift
17884 @end example
17886 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17887 longer requires support for this command, and in traditional shells
17888 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17889 makes scripts harder to debug.
17891 Some nonstandard shells do not recognize more than one option
17892 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17893 better to combine them:
17895 @example
17896 set -ex
17897 @end example
17899 @cindex @command{set -e}
17900 The option @option{-e} has historically been underspecified, with enough
17901 ambiguities to cause numerous differences across various shell
17902 implementations; see for example
17903 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
17904 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
17905 documenting a change to Posix 2008 to match @command{ksh88} behavior.
17906 Note that mixing @code{set -e} and shell functions is asking for surprises:
17908 @example
17909 set -e
17910 doit()
17912   rm file
17913   echo one
17915 doit || echo two
17916 @end example
17918 @noindent
17919 According to the recommendation, @samp{one} should always be output
17920 regardless of whether the @command{rm} failed, because it occurs within
17921 the body of the shell function @samp{doit} invoked on the left side of
17922 @samp{||}, where the effects of @samp{set -e} are not enforced.
17923 Likewise, @samp{two} should never be printed, since the failure of
17924 @command{rm} does not abort the function, such that the status of
17925 @samp{doit} is 0.
17927 The BSD shell has had several problems with the @option{-e}
17928 option.  Older versions of the BSD
17929 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17930 @samp{case} when @option{-e} was in effect, causing the shell to exit
17931 unexpectedly in some cases.  This was particularly a problem with
17932 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17933 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17934 wrapper works around the bug (@pxref{Failure in Make Rules}).
17936 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17937 wrongly exit with @option{-e} if the last command within a compound
17938 statement fails and is guarded by an @samp{&&} only.  For example:
17940 @example
17941 #! /bin/sh
17942 set -e
17943 foo=''
17944 test -n "$foo" && exit 1
17945 echo one
17946 if :; then
17947   test -n "$foo" && exit 1
17948   echo two
17949   test -n "$foo" && exit 1
17951 echo three
17952 @end example
17954 @noindent
17955 does not print @samp{three}.  One workaround is to change the last
17956 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
17957 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
17958 users not to use @samp{sh -e}.
17960 When @samp{set -e} is in effect, a failed command substitution in
17961 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
17963 @example
17964 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
17965 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
17968 @end example
17970 @noindent
17971 Moreover, a command substitution, successful or not, causes this shell to
17972 exit from a failing outer command even in presence of an @samp{&&} list:
17974 @example
17975 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
17977 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
17979 @end example
17981 Portable scripts should not use @samp{set -e} if @command{trap} is used
17982 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
17983 sometimes enters the trap handler with the exit status of the command
17984 prior to the one that triggered the errexit handler:
17986 @example
17987 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
17989 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
17991 @end example
17993 @noindent
17994 Thus, when writing a script in M4sh, rather than trying to rely on
17995 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
17996 statement where it is desirable to abort on failure.
17998 @cindex @command{set -b}
17999 @cindex @command{set -m}
18000 Job control is not provided by all shells, so the use of @samp{set -m}
18001 or @samp{set -b} must be done with care.  When using @command{zsh} in
18002 native mode, asynchronous notification (@samp{set -b}) is enabled by
18003 default, and using @samp{emulate sh} to switch to Posix mode does not
18004 clear this setting (although asynchronous notification has no impact
18005 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18006 earlier have a bug where job control can be manipulated in interactive
18007 shells, but not in subshells or scripts.  Furthermore, some shells, like
18008 @command{pdksh}, fail to treat subshells as interactive, even though the
18009 parent shell was.
18011 @example
18012 $ @kbd{echo $ZSH_VERSION}
18013 4.3.10
18014 $ @kbd{set -m; echo $?}
18016 $ @kbd{zsh -c 'set -m; echo $?'}
18017 set: can't change option: -m
18018 $ @kbd{(set -m); echo $?}
18019 set: can't change option: -m
18021 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18024 @end example
18027 @item @command{shift}
18028 @c ------------------
18029 @prindex @command{shift}
18030 Not only is @command{shift}ing a bad idea when there is nothing left to
18031 shift, but in addition it is not portable: the shell of MIPS
18032 RISC/OS 4.52 refuses to do it.
18034 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18035 it is also absent in many pre-Posix shells.
18038 @item @command{source}
18039 @c -------------------
18040 @prindex @command{source}
18041 This command is not portable, as Posix does not require it; use
18042 @command{.} instead.
18045 @item @command{test}
18046 @c -----------------
18047 @prindex @command{test}
18048 The @code{test} program is the way to perform many file and string
18049 tests.  It is often invoked by the alternate name @samp{[}, but using
18050 that name in Autoconf code is asking for trouble since it is an M4 quote
18051 character.
18053 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18054 present in all implementations, and have been marked obsolete by Posix
18055 2008.  This is because there are inherent ambiguities in using them.
18056 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18057 check whether two strings are both non-empty, but if @samp{$1} is the
18058 literal @samp{!}, then some implementations of @command{test} treat it
18059 as a negation of the unary operator @option{-a}.
18061 Thus, portable uses of @command{test} should never have more than four
18062 arguments, and scripts should use shell constructs like @samp{&&} and
18063 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18064 statement, keep in mind that they have equal precedence, so it is often
18065 better to parenthesize even when this is redundant.  For example:
18067 @smallexample
18068 # Not portable:
18069 test "X$a" = "X$b" -a \
18070   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18072 # Portable:
18073 test "X$a" = "X$b" &&
18074   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18075 @end smallexample
18077 @command{test} does not process options like most other commands do; for
18078 example, it does not recognize the @option{--} argument as marking the
18079 end of options.
18081 It is safe to use @samp{!} as a @command{test} operator.  For example,
18082 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18083 -d foo; @dots{}} is not.
18086 @item @command{test} (files)
18087 @c -------------------------
18088 To enable @command{configure} scripts to support cross-compilation, they
18089 shouldn't do anything that tests features of the build system instead of
18090 the host system.  But occasionally you may find it necessary to check
18091 whether some arbitrary file exists.  To do so, use @samp{test -f} or
18092 @samp{test -r}.  Do not use @samp{test -x}, because 4.3BSD does not
18093 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
18094 lacks it.  To test for symbolic links on systems that have them, use
18095 @samp{test -h} rather than @samp{test -L}; either form conforms to
18096 Posix 1003.1-2001, but older shells like Solaris 8
18097 @code{/bin/sh} support only @option{-h}.
18099 @item @command{test} (strings)
18100 @c ---------------------------
18101 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18102 not null, but this usage is not portable to traditional platforms like
18103 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18104 @samp{-n}.
18106 Posix also says that @samp{test ! "@var{string}"},
18107 @samp{test -n "@var{string}"} and
18108 @samp{test -z "@var{string}"} work with any string, but many
18109 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18110 Digital Unix 4, etc.)@: get confused if
18111 @var{string} looks like an operator:
18113 @example
18114 $ @kbd{test -n =}
18115 test: argument expected
18116 $ @kbd{test ! -n}
18117 test: argument expected
18118 $ @kbd{test -z ")"; echo $?}
18120 @end example
18122 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18123 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18124 strings, but in practice this is not true for troublesome strings that
18125 look like operators or parentheses, or that begin with @samp{-}.
18127 It is best to protect such strings with a leading @samp{X}, e.g.,
18128 @samp{test "X@var{string}" != X} rather than @samp{test -n
18129 "@var{string}"} or @samp{test ! "@var{string}"}.
18131 It is common to find variations of the following idiom:
18133 @example
18134 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18135   @var{action}
18136 @end example
18138 @noindent
18139 to take an action when a token matches a given pattern.  Such constructs
18140 should be avoided by using:
18142 @example
18143 case $ac_feature in
18144   *[!-a-zA-Z0-9_]*) @var{action};;
18145 esac
18146 @end example
18148 If the pattern is a complicated regular expression that cannot be
18149 expressed as a shell pattern, use something like this instead:
18151 @example
18152 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18153   @var{action}
18154 @end example
18156 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18157 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18158 @samp{@var{foo}} contains backslashes.
18161 @anchor{trap}
18162 @item @command{trap}
18163 @c -----------------
18164 @prindex @command{trap}
18165 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18166 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18167 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18168 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18169 will invoke the trap at the end of this function.
18171 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18172 specified signals to their default values, but many common shells (e.g.,
18173 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18174 ``command'' named @command{-} when the specified conditions arise.
18175 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18176 reset traps, as this is supported by a larger set of shells, but there
18177 are still shells like @command{dash} that mistakenly try to execute
18178 @command{1} instead of resetting the traps.  Therefore, there is no
18179 portable workaround, except for @samp{trap - 0}, for which
18180 @samp{trap '' 0} is a portable substitute.
18182 Although Posix is not absolutely clear on this point, it is widely
18183 admitted that when entering the trap @samp{$?} should be set to the exit
18184 status of the last command run before the trap.  The ambiguity can be
18185 summarized as: ``when the trap is launched by an @command{exit}, what is
18186 the @emph{last} command run: that before @command{exit}, or
18187 @command{exit} itself?''
18189 Bash considers @command{exit} to be the last command, while Zsh and
18190 Solaris @command{/bin/sh} consider that when the trap is run it is
18191 @emph{still} in the @command{exit}, hence it is the previous exit status
18192 that the trap receives:
18194 @example
18195 $ @kbd{cat trap.sh}
18196 trap 'echo $?' 0
18197 (exit 42); exit 0
18198 $ @kbd{zsh trap.sh}
18200 $ @kbd{bash trap.sh}
18202 @end example
18204 The portable solution is then simple: when you want to @samp{exit 42},
18205 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18206 set the exit status to 42 for Zsh, and the second to trigger the trap
18207 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18208 @code{AS_EXIT}.
18210 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18211 reset to 0 by empty lines if the code is inside @command{trap}.
18213 @example
18214 $ @kbd{trap 'false}
18216 echo $?' 0
18217 $ @kbd{exit}
18219 @end example
18221 @noindent
18222 Fortunately, this bug only affects @command{trap}.
18224 Several shells fail to execute an exit trap that is defined inside a
18225 subshell, when the last command of that subshell is not a builtin.  A
18226 workaround is to use @samp{exit $?} as the shell builtin.
18228 @example
18229 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18231 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18232 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18234 @end example
18236 @noindent
18237 Likewise, older implementations of @command{bash} failed to preserve
18238 @samp{$?} across an exit trap consisting of a single cleanup command.
18240 @example
18241 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18243 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18245 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18247 @end example
18249 @item @command{true}
18250 @c -----------------
18251 @prindex @command{true}
18252 @c Info cannot handle `:' in index entries.
18253 @c @prindex @command{:}
18254 Don't worry: as far as we know @command{true} is portable.
18255 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18256 portable shell community tends to prefer using @command{:}.  This has a
18257 funny side effect: when asked whether @command{false} is more portable
18258 than @command{true} Alexandre Oliva answered:
18260 @quotation
18261 In a sense, yes, because if it doesn't exist, the shell will produce an
18262 exit status of failure, which is correct for @command{false}, but not
18263 for @command{true}.
18264 @end quotation
18266 Remember that even though @samp{:} ignores its arguments, it still takes
18267 time to compute those arguments.  It is a good idea to use double quotes
18268 around any arguments to @samp{:} to avoid time spent in field splitting
18269 and file name expansion.
18272 @anchor{unset}
18273 @item @command{unset}
18274 @c ------------------
18275 @prindex @command{unset}
18276 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18277 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18278 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18279 with @code{set -e} operation.  You can use
18281 @smallexample
18282 FOO=; unset FOO
18283 @end smallexample
18285 @noindent
18286 if you are not sure that @code{FOO} is set.
18288 A few ancient shells lack @command{unset} entirely.  For some variables
18289 such as @code{PS1}, you can use a neutralizing value instead:
18291 @smallexample
18292 PS1='$ '
18293 @end smallexample
18295 Usually, shells that do not support @command{unset} need less effort to
18296 make the environment sane, so for example is not a problem if you cannot
18297 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18298 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18299 So, you should do something like
18301 @smallexample
18302 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18303 @end smallexample
18305 @noindent
18306 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18307 @ref{export, , Limitations of Builtins}, for
18308 the case of environment variables.
18310 @item @command{wait}
18311 @c -----------------
18312 @prindex @command{wait}
18313 The exit status of @command{wait} is not always reliable.
18314 @end table
18316 @node Limitations of Usual Tools
18317 @section Limitations of Usual Tools
18318 @cindex Limitations of usual tools
18320 The small set of tools you can expect to find on any machine can still
18321 include some limitations you should be aware of.
18323 @comment Between this list and the list of builtins above, we should
18324 @comment mention all the tools in GNU Coding Standards ``Utilities in
18325 @comment Makefiles''.
18327 @c This table includes things like `@command{expr} (|)', so we can't
18328 @c use @table @command.
18329 @table @asis
18330 @anchor{awk}
18331 @item @command{awk}
18332 @c ----------------
18333 @prindex @command{awk}
18334 Don't leave white space before the opening parenthesis in a user function call.
18335 Posix does not allow this and GNU Awk rejects it:
18337 @example
18338 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18339         BEGIN @{ die () @}'}
18340 gawk: cmd. line:2:         BEGIN @{ die () @}
18341 gawk: cmd. line:2:                      ^ parse error
18342 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18343         BEGIN @{ die() @}'}
18344 Aaaaarg!
18345 @end example
18347 Posix says that if a program contains only @samp{BEGIN} actions, and
18348 contains no instances of @code{getline}, then the program merely
18349 executes the actions without reading input.  However, traditional Awk
18350 implementations (such as Solaris 10 @command{awk}) read and discard
18351 input in this case.  Portable scripts can redirect input from
18352 @file{/dev/null} to work around the problem.  For example:
18354 @example
18355 awk 'BEGIN @{print "hello world"@}' </dev/null
18356 @end example
18358 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18359 @samp{$1}) retain their value from the last record read, if no
18360 intervening @samp{getline} occurred.  However, some implementations
18361 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18362 @samp{awk}) reset these variables.  A workaround is to use an
18363 intermediate variable prior to the @samp{END} block.  For example:
18365 @example
18366 $ @kbd{cat end.awk}
18367 @{ tmp = $1 @}
18368 END @{ print "a", $1, $NF, "b", tmp @}
18369 $ @kbd{echo 1 | awk -f end.awk}
18370 a   b 1
18371 $ @kbd{echo 1 | gawk -f end.awk}
18372 a 1 1 b 1
18373 @end example
18375 If you want your program to be deterministic, don't depend on @code{for}
18376 on arrays:
18378 @example
18379 $ @kbd{cat for.awk}
18380 END @{
18381   arr["foo"] = 1
18382   arr["bar"] = 1
18383   for (i in arr)
18384     print i
18386 $ @kbd{gawk -f for.awk </dev/null}
18389 $ @kbd{nawk -f for.awk </dev/null}
18392 @end example
18394 Some Awk implementations, such as HP-UX 11.0's native one,
18395 mishandle anchors:
18397 @example
18398 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18399 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18401 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18402 xfoo
18403 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18405 @end example
18407 @noindent
18408 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18409 or use a simple test to reject such implementations.
18411 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18412 after @code{%u}:
18414 @example
18415 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18416 0 0
18417 @end example
18419 AIX version 5.2 has an arbitrary limit of 399 on the
18420 length of regular expressions and literal strings in an Awk program.
18422 Traditional Awk implementations derived from Unix version 7, such as
18423 Solaris @command{/bin/awk}, have many limitations and do not
18424 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18425 Programs}) finds you an Awk that doesn't have these problems, but if
18426 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18427 address them.  For more detailed descriptions, see @ref{Language
18428 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18430 Traditional Awk does not support multidimensional arrays or user-defined
18431 functions.
18433 Traditional Awk does not support the @option{-v} option.  You can use
18434 assignments after the program instead, e.g., @code{$AWK '@{print v
18435 $1@}' v=x}; however, don't forget that such assignments are not
18436 evaluated until they are encountered (e.g., after any @code{BEGIN}
18437 action).
18439 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18441 Traditional Awk does not support the expressions
18442 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18443 or @code{@var{a}^=@var{b}}.
18445 Traditional Awk does not support the predefined @code{CONVFMT} or
18446 @code{ENVIRON} variables.
18448 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18449 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18450 @code{sqrt}, and @code{substr}.
18452 Traditional Awk @code{getline} is not at all compatible with Posix;
18453 avoid it.
18455 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18456 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18458 In code portable to both traditional and modern Awk, @code{FS} must be a
18459 string containing just one ordinary character, and similarly for the
18460 field-separator argument to @code{split}.
18462 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18463 implementations, like Tru64's, split the input even if you don't refer
18464 to any field in the script, to circumvent this problem, set @samp{FS}
18465 to an unusual character and use @code{split}.
18467 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18468 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18469 dumps core.
18471 The original version of Awk had a limit of at most 99 bytes per
18472 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18473 per run of non-special characters in a @code{printf} format, but these
18474 bugs have been fixed on all practical hosts that we know of.
18476 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18477 of at most 3070 bytes.
18479 @item @command{basename}
18480 @c ---------------------
18481 @prindex @command{basename}
18482 Not all hosts have a working @command{basename}.
18483 You can use @command{expr} instead.
18485 @c AS_BASENAME is to be replaced by a better API.
18486 @ignore
18487 Not all hosts have a working @command{basename}, and you should instead
18488 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18489 @command{expr} if you need to strip a suffix.  For example:
18491 @example
18492 a=`basename "$aname"`       # This is not portable.
18493 a=`AS_BASENAME(["$aname"])` # This is more portable.
18495 # This is not portable.
18496 c=`basename "$cname" .c`
18498 # This is more portable.
18499 c=`AS_BASENAME(["$cname"])`
18500 case $c in
18501 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18502 esac
18503 @end example
18504 @end ignore
18507 @item @command{cat}
18508 @c ----------------
18509 @prindex @command{cat}
18510 Don't rely on any option.
18513 @item @command{cc}
18514 @c ---------------
18515 @prindex @command{cc}
18516 The command @samp{cc -c foo.c} traditionally produces an object file
18517 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18518 with @option{-o} to specify a different object file name, but
18519 Posix does not require this combination and a few compilers
18520 lack support for it.  @xref{C Compiler}, for how GNU Make
18521 tests for this feature with @code{AC_PROG_CC_C_O}.
18523 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18524 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18526 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18527 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18528 nothing.
18530 The default executable, produced by @samp{cc foo.c}, can be
18532 @itemize
18533 @item @file{a.out} --- usual Posix convention.
18534 @item @file{b.out} --- i960 compilers (including @command{gcc}).
18535 @item @file{a.exe} --- DJGPP port of @command{gcc}.
18536 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
18537 @item @file{foo.exe} --- various MS-DOS compilers.
18538 @end itemize
18540 The C compiler's traditional name is @command{cc}, but other names like
18541 @command{gcc} are common.  Posix 1003.1-2001 specifies the
18542 name @command{c99}, but older Posix editions specified
18543 @command{c89} and anyway these standard names are rarely used in
18544 practice.  Typically the C compiler is invoked from makefiles that use
18545 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18546 compiler name.
18548 @item @command{chgrp}
18549 @itemx @command{chown}
18550 @c -------------------
18551 @prindex @command{chgrp}
18552 @prindex @command{chown}
18553 It is not portable to change a file's group to a group that the owner
18554 does not belong to.
18556 @item @command{chmod}
18557 @c ------------------
18558 @prindex @command{chmod}
18559 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18560 instead, for two reasons.  First, plain @option{-w} does not necessarily
18561 make the file unwritable, since it does not affect mode bits that
18562 correspond to bits in the file mode creation mask.  Second,
18563 Posix says that the @option{-w} might be interpreted as an
18564 implementation-specific option, not as a mode; Posix suggests
18565 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18566 @samp{--} does not work on some older hosts.
18569 @item @command{cmp}
18570 @c ----------------
18571 @prindex @command{cmp}
18572 @command{cmp} performs a raw data comparison of two files, while
18573 @command{diff} compares two text files.  Therefore, if you might compare
18574 DOS files, even if only checking whether two files are different, use
18575 @command{diff} to avoid spurious differences due to differences of
18576 newline encoding.
18579 @item @command{cp}
18580 @c ---------------
18581 @prindex @command{cp}
18582 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18583 obsolescent and its behavior on special files is implementation-defined.
18584 Use @option{-R} instead.  On GNU hosts the two options
18585 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18586 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18587 corrupt its own memory with some directory hierarchies and error out or
18588 dump core:
18590 @example
18591 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18592 @kbd{touch 12345678/12345678/x}
18593 @kbd{cp -R 12345678 t}
18594 cp: 0653-440 12345678/12345678/: name too long.
18595 @end example
18597 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18598 trailing slashes at the end of nonexistent destination directories.  To
18599 avoid this problem, omit the trailing slashes.  For example, use
18600 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18601 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18603 @c This is thanks to Ian.
18604 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18605 its @command{mv} does.
18607 @cindex timestamp resolution
18608 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18609 -p} copied the timestamps exactly.  However, many modern file systems
18610 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18611 @samp{cp -p} implementations truncate timestamps when copying files,
18612 which can cause the destination file to appear to be older than the
18613 source.  The exact amount of truncation depends on the resolution of
18614 the system calls that @command{cp} uses.  Traditionally this was
18615 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18616 implementations such as GNU Core Utilities 5.0.91 (2003) use
18617 @code{utimes}, which has 1-microsecond resolution.  Modern
18618 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18619 the full nanosecond resolution, using the modern system calls
18620 @code{futimens} and @code{utimensat} when they are available.  As of
18621 2011, though, many platforms do not yet fully support these new system
18622 calls.
18624 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18625 ownerships.  But whether it actually does copy ownerships or not is a
18626 system dependent policy decision implemented by the kernel.  If the
18627 kernel allows it then it happens.  If the kernel does not allow it then
18628 it does not happen.  It is not something @command{cp} itself has control
18629 over.
18631 In Unix System V any user can chown files to any other user, and System
18632 V also has a non-sticky @file{/tmp}.  That probably derives from the
18633 heritage of System V in a business environment without hostile users.
18634 BSD changed this
18635 to be a more secure model where only root can @command{chown} files and
18636 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18637 of BSD in a campus environment.
18639 GNU/Linux and Solaris by default follow BSD, but
18640 can be configured to allow a System V style @command{chown}.  On the
18641 other hand, HP-UX follows System V, but can
18642 be configured to use the modern security model and disallow
18643 @command{chown}.  Since it is an administrator-configurable parameter
18644 you can't use the name of the kernel as an indicator of the behavior.
18648 @item @command{date}
18649 @c -----------------
18650 @prindex @command{date}
18651 Some versions of @command{date} do not recognize special @samp{%} directives,
18652 and unfortunately, instead of complaining, they just pass them through,
18653 and exit with success:
18655 @example
18656 $ @kbd{uname -a}
18657 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18658 $ @kbd{date "+%s"}
18660 @end example
18663 @item @command{diff}
18664 @c -----------------
18665 @prindex @command{diff}
18666 Option @option{-u} is nonportable.
18668 Some implementations, such as Tru64's, fail when comparing to
18669 @file{/dev/null}.  Use an empty file instead.
18672 @item @command{dirname}
18673 @c --------------------
18674 @prindex @command{dirname}
18675 Not all hosts have a working @command{dirname}, and you should instead
18676 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18678 @example
18679 dir=`dirname "$file"`       # This is not portable.
18680 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18681 @end example
18684 @item @command{egrep}
18685 @c ------------------
18686 @prindex @command{egrep}
18687 Posix 1003.1-2001 no longer requires @command{egrep},
18688 but many hosts do not yet support the Posix
18689 replacement @code{grep -E}.  Also, some traditional implementations do
18690 not work on long input lines.  To work around these problems, invoke
18691 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18693 Portable extended regular expressions should use @samp{\} only to escape
18694 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18695 is not portable, even though it typically matches @samp{@}}.
18697 The empty alternative is not portable.  Use @samp{?} instead.  For
18698 instance with Digital Unix v5.0:
18700 @example
18701 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18702 |foo
18703 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18704 bar|
18705 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18707 |bar
18708 @end example
18710 @command{$EGREP} also suffers the limitations of @command{grep}
18711 (@pxref{grep, , Limitations of Usual Tools}).
18713 @item @command{expr}
18714 @c -----------------
18715 @prindex @command{expr}
18716 Not all implementations obey the Posix rule that @samp{--} separates
18717 options from arguments; likewise, not all implementations provide the
18718 extension to Posix that the first argument can be treated as part of a
18719 valid expression rather than an invalid option if it begins with
18720 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18721 @samp{$var} might be a negative number, to keep @command{expr} from
18722 interpreting it as an option.
18724 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18725 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18726 misinterpreting @var{word}.
18728 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18730 @item @command{expr} (@samp{|})
18731 @prindex @command{expr} (@samp{|})
18732 You can use @samp{|}.  Although Posix does require that @samp{expr
18733 ''} return the empty string, it does not specify the result when you
18734 @samp{|} together the empty string (or zero) with the empty string.  For
18735 example:
18737 @example
18738 expr '' \| ''
18739 @end example
18741 Posix 1003.2-1992 returns the empty string
18742 for this case, but traditional Unix returns @samp{0} (Solaris is
18743 one such example).  In Posix 1003.1-2001, the specification was
18744 changed to match traditional Unix's behavior (which is
18745 bizarre, but it's too late to fix this).  Please note that the same
18746 problem does arise when the empty string results from a computation,
18747 as in:
18749 @example
18750 expr bar : foo \| foo : bar
18751 @end example
18753 @noindent
18754 Avoid this portability problem by avoiding the empty string.
18757 @item @command{expr} (@samp{:})
18758 @c ----------------------------
18759 @prindex @command{expr}
18760 Portable @command{expr} regular expressions should use @samp{\} to
18761 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18762 For example, alternation, @samp{\|}, is common but Posix does not
18763 require its support, so it should be avoided in portable scripts.
18764 Similarly, @samp{\+} and @samp{\?} should be avoided.
18766 Portable @command{expr} regular expressions should not begin with
18767 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18768 not needed anyway.
18770 On the other hand, the behavior of the @samp{$} anchor is not portable
18771 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18772 each line, as was done in older versions of the GNU Core Utilities, or
18773 whether it applies only to the end of the overall string, as in
18774 Coreutils 6.0 and most other implementations.
18776 @example
18777 $ @kbd{baz='foo}
18778 > @kbd{bar'}
18779 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18781 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18783 @end example
18785 The Posix standard is ambiguous as to whether
18786 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18787 In practice, it outputs the empty string on most platforms, but portable
18788 scripts should not assume this.  For instance, the QNX 4.25 native
18789 @command{expr} returns @samp{0}.
18791 One might think that a way to get a uniform behavior would be to use
18792 the empty string as a default value:
18794 @example
18795 expr a : '\(b\)' \| ''
18796 @end example
18798 @noindent
18799 Unfortunately this behaves exactly as the original expression; see the
18800 @command{expr} (@samp{|}) entry for more information.
18802 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18803 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18804 @command{expr} to fail if the matched substring is longer than 120
18805 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18806 @command{expr} fails.  Nowadays this is of practical importance only for
18807 the rare installer who mistakenly puts @file{/usr/ucb} before
18808 @file{/usr/bin} in @env{PATH}.
18810 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18811 some cases.  For example, the command
18812 @example
18813 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18814 @end example
18816 @noindent
18817 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18818 This particular case can be worked around by substituting @samp{[^--]}
18819 for @samp{[^-]}.
18821 Don't leave, there is some more!
18823 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18824 the empty string, has a funny behavior in its exit status: it's always 1
18825 when parentheses are used!
18827 @example
18828 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
18829 0: 1
18830 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
18831 1: 0
18833 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
18834 1: a
18835 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
18836 1: 0
18837 @end example
18839 @noindent
18840 In practice this can be a big problem if you are ready to catch failures
18841 of @command{expr} programs with some other method (such as using
18842 @command{sed}), since you may get twice the result.  For instance
18844 @example
18845 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18846 @end example
18848 @noindent
18849 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18850 simple workaround consists of testing @command{expr} and using a variable
18851 set to @command{expr} or to @command{false} according to the result.
18853 Tru64 @command{expr} incorrectly treats the result as a number, if it
18854 can be interpreted that way:
18856 @example
18857 $ @kbd{expr 00001 : '.*\(...\)'}
18859 @end example
18861 On HP-UX 11, @command{expr} only supports a single
18862 sub-expression.
18864 @example
18865 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18866 expr: More than one '\(' was used.
18867 @end example
18870 @item @command{fgrep}
18871 @c ------------------
18872 @prindex @command{fgrep}
18873 Posix 1003.1-2001 no longer requires @command{fgrep},
18874 but many hosts do not yet support the Posix
18875 replacement @code{grep -F}.  Also, some traditional implementations do
18876 not work on long input lines.  To work around these problems, invoke
18877 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
18879 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18882 @item @command{find}
18883 @c -----------------
18884 @prindex @command{find}
18885 The option @option{-maxdepth} seems to be GNU specific.
18886 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18887 commands do not understand it.
18889 The replacement of @samp{@{@}} is guaranteed only if the argument is
18890 exactly @emph{@{@}}, not if it's only a part of an argument.  For
18891 instance on DU, and HP-UX 10.20 and HP-UX 11:
18893 @example
18894 $ @kbd{touch foo}
18895 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18896 @{@}-@{@}
18897 @end example
18899 @noindent
18900 while GNU @command{find} reports @samp{./foo-./foo}.
18903 @anchor{grep}
18904 @item @command{grep}
18905 @c -----------------
18906 @prindex @command{grep}
18907 Portable scripts can rely on the @command{grep} options @option{-c},
18908 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
18909 options.  For example, don't use @option{-w}, as Posix does not require
18910 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
18911 portable scripts should not combine @option{-c} with @option{-l},
18912 as Posix does not allow this.
18914 Some of the options required by Posix are not portable in practice.
18915 Don't use @samp{grep -q} to suppress output, because many @command{grep}
18916 implementations (e.g., Solaris) do not support @option{-q}.
18917 Don't use @samp{grep -s} to suppress output either, because Posix
18918 says @option{-s} does not suppress output, only some error messages;
18919 also, the @option{-s} option of traditional @command{grep} behaved
18920 like @option{-q} does in most modern implementations.  Instead,
18921 redirect the standard output and standard error (in case the file
18922 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
18923 status of @code{grep} to determine whether it found a match.
18925 The QNX4 implementation fails to count lines with @code{grep -c '$'},
18926 but works with @code{grep -c '^'}.  Other alternatives for counting
18927 lines are to use @code{sed -n '$='} or @code{wc -l}.
18929 Some traditional @command{grep} implementations do not work on long
18930 input lines.  On AIX the default @code{grep} silently truncates long
18931 lines on the input before matching.
18933 Also, many implementations do not support multiple regexps
18934 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
18935 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
18936 work around these problems, invoke @code{AC_PROG_GREP} and then use
18937 @code{$GREP}.
18939 Another possible workaround for the multiple @option{-e} problem is to
18940 separate the patterns by newlines, for example:
18942 @example
18943 grep 'foo
18944 bar' in.txt
18945 @end example
18947 @noindent
18948 except that this fails with traditional @command{grep}
18949 implementations and with OpenBSD 3.8 @command{grep}.
18951 Traditional @command{grep} implementations (e.g., Solaris) do not
18952 support the @option{-E} or @option{-F} options.  To work around these
18953 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
18954 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
18955 willing to require support for Posix @command{grep}, your script should
18956 not use both @option{-E} and @option{-F}, since Posix does not allow
18957 this combination.
18959 Portable @command{grep} regular expressions should use @samp{\} only to
18960 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
18961 alternation, @samp{\|}, is common but Posix does not require its
18962 support in basic regular expressions, so it should be avoided in
18963 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
18964 Similarly, the following escape sequences should also be avoided:
18965 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
18966 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
18968 Posix does not specify the behavior of @command{grep} on binary files.
18969 An example where this matters is using BSD @command{grep} to
18970 search text that includes embedded ANSI escape sequences for
18971 colored output to terminals (@samp{\033[m} is the sequence to restore
18972 normal output); the behavior depends on whether input is seekable:
18974 @example
18975 $ @kbd{printf 'esc\033[mape\n' > sample}
18976 $ @kbd{grep . sample}
18977 Binary file sample matches
18978 $ @kbd{cat sample | grep .}
18979 escape
18980 @end example
18983 @item @command{join}
18984 @c -----------------
18985 @prindex @command{join}
18986 Solaris 8 @command{join} has bugs when the second operand is standard
18987 input, and when standard input is a pipe.  For example, the following
18988 shell script causes Solaris 8 @command{join} to loop forever:
18990 @example
18991 cat >file <<'EOF'
18992 1 x
18993 2 y
18995 cat file | join file -
18996 @end example
18998 Use @samp{join - file} instead.
19000 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19001 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19002 the workaround is to use @command{join -a1 file1 file2} instead.
19004 @item @command{ln}
19005 @c ---------------
19006 @prindex @command{ln}
19007 @cindex Symbolic links
19008 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
19009 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
19011 For versions of the DJGPP before 2.04,
19012 @command{ln} emulates symbolic links
19013 to executables by generating a stub that in turn calls the real
19014 program.  This feature also works with nonexistent files like in the
19015 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19016 which attempts to call @file{file.exe} if run.  But this feature only
19017 works for executables, so @samp{cp -p} is used instead for these
19018 systems.  DJGPP versions 2.04 and later have full support
19019 for symbolic links.
19022 @item @command{ls}
19023 @c ---------------
19024 @prindex @command{ls}
19025 @cindex Listing directories
19026 The portable options are @option{-acdilrtu}.  Current practice is for
19027 @option{-l} to output both owner and group, even though ancient versions
19028 of @command{ls} omitted the group.
19030 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19031 to standard output if @file{foo} did not exist.  Hence a shell command
19032 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19033 was equivalent to @samp{sources='*.c not found'} in the absence of
19034 @samp{.c} files.  This is no longer a practical problem, since current
19035 @command{ls} implementations send diagnostics to standard error.
19037 The behavior of @command{ls} on a directory that is being concurrently
19038 modified is not always predictable, because of a data race where cached
19039 information returned by @code{readdir} does not match the current
19040 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19041 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19042 once if other files were added or removed from the directory immediately
19043 prior to the @command{ls} call.  Since @command{ls} already sorts its
19044 output, the duplicate entries can be avoided by piping the results
19045 through @code{uniq}.
19047 @anchor{mkdir}
19048 @item @command{mkdir}
19049 @c ------------------
19050 @prindex @command{mkdir}
19051 @cindex Making directories
19052 No @command{mkdir} option is portable to older systems.  Instead of
19053 @samp{mkdir -p @var{file-name}}, you should use
19054 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19055 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19057 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19058 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19059 @command{mkdir} incorrectly attempts to change the permissions of
19060 @var{dir} even if it already exists.  HP-UX 11.23 and
19061 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19062 any newly-created parents of @var{dir}.
19064 Posix does not clearly specify whether @samp{mkdir -p foo}
19065 should succeed when @file{foo} is a symbolic link to an already-existing
19066 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19067 succeeds, but Solaris @command{mkdir} fails.
19069 Traditional @code{mkdir -p} implementations suffer from race conditions.
19070 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19071 at the same time, both processes might detect that @file{a} is missing,
19072 one might create @file{a}, then the other might try to create @file{a}
19073 and fail with a @code{File exists} diagnostic.  The GNU Core
19074 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19075 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19076 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19077 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19078 vulnerable as of Solaris 10, and other traditional Unix systems are
19079 probably vulnerable too.  This possible race is harmful in parallel
19080 builds when several Make rules call @code{mkdir -p} to
19081 construct directories.  You may use
19082 @code{install-sh -d} as a safe replacement, provided this script is
19083 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19084 OK, but copies from older versions are vulnerable.
19087 @item @command{mkfifo}
19088 @itemx @command{mknod}
19089 @c -------------------
19090 @prindex @command{mkfifo}
19091 @prindex @command{mknod}
19092 The GNU Coding Standards state that @command{mknod} is safe to use on
19093 platforms where it has been tested to exist; but it is generally portable
19094 only for creating named FIFOs, since device numbers are
19095 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19096 testsuites.  Posix states that behavior is unspecified when opening a
19097 named FIFO for both reading and writing; on at least Cygwin, this
19098 results in failure on any attempt to read or write to that file
19099 descriptor.
19101 @item @command{mktemp}
19102 @c -------------------
19103 @prindex @command{mktemp}
19104 @cindex Creating temporary files
19105 Shell scripts can use temporary files safely with @command{mktemp}, but
19106 it does not exist on all systems.  A portable way to create a safe
19107 temporary file name is to create a temporary directory with mode 700 and
19108 use a file inside this directory.  Both methods prevent attackers from
19109 gaining control, though @command{mktemp} is far less likely to fail
19110 gratuitously under attack.
19112 Here is sample code to create a new temporary directory @samp{$dir} safely:
19114 @example
19115 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19116 # Use mktemp if possible; otherwise fall back on mkdir,
19117 # with $RANDOM to make collisions less likely.
19118 : "$@{TMPDIR:=/tmp@}"
19120   dir=`
19121     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19122   ` &&
19123   test -d "$dir"
19124 @} || @{
19125   dir=$TMPDIR/foo$$-$RANDOM
19126 @c $$ restore font-lock
19127   (umask 077 && mkdir "$dir")
19128 @} || exit $?
19129 @end example
19132 @item @command{mv}
19133 @c ---------------
19134 @prindex @command{mv}
19135 @cindex Moving open files
19136 The only portable options are @option{-f} and @option{-i}.
19138 Moving individual files between file systems is portable (it was in Unix
19139 version 6),
19140 but it is not always atomic: when doing @samp{mv new existing}, there's
19141 a critical section where neither the old nor the new version of
19142 @file{existing} actually exists.
19144 On some systems moving files from @file{/tmp} can sometimes cause
19145 undesirable (but perfectly valid) warnings, even if you created these
19146 files.  This is because @file{/tmp} belongs to a group that ordinary
19147 users are not members of, and files created in @file{/tmp} inherit
19148 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19149 a diagnostic without failing:
19151 @smallexample
19152 $ @kbd{touch /tmp/foo}
19153 $ @kbd{mv /tmp/foo .}
19154 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19155 $ @kbd{echo $?}
19157 $ @kbd{ls foo}
19159 @end smallexample
19161 @noindent
19162 This annoying behavior conforms to Posix, unfortunately.
19164 Moving directories across mount points is not portable, use @command{cp}
19165 and @command{rm}.
19167 DOS variants cannot rename or remove open files, and do not
19168 support commands like @samp{mv foo bar >foo}, even though this is
19169 perfectly portable among Posix hosts.
19172 @item @command{od}
19173 @c ---------------
19174 @prindex @command{od}
19176 In Mac OS X 10.3, @command{od} does not support the
19177 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19178 @option{-t}, or the XSI option @option{-s}.  The only
19179 supported Posix option is @option{-v}, and the only supported
19180 XSI options are those in @option{-bcdox}.  The BSD
19181 @command{hexdump} program can be used instead.
19183 This problem no longer exists in Mac OS X 10.4.3.
19186 @item @command{rm}
19187 @c ---------------
19188 @prindex @command{rm}
19189 The @option{-f} and @option{-r} options are portable.
19191 It is not portable to invoke @command{rm} without operands.  For
19192 example, on many systems @samp{rm -f -r} (with no other arguments)
19193 silently succeeds without doing anything, but it fails with a diagnostic
19194 on NetBSD 2.0.2.
19196 A file might not be removed even if its parent directory is writable
19197 and searchable.  Many Posix hosts cannot remove a mount point, a named
19198 stream, a working directory, or a last link to a file that is being
19199 executed.
19201 DOS variants cannot rename or remove open files, and do not
19202 support commands like @samp{rm foo >foo}, even though this is
19203 perfectly portable among Posix hosts.
19205 @item @command{rmdir}
19206 @c ------------------
19207 @prindex @command{rmdir}
19208 Just as with @command{rm}, some platforms refuse to remove a working
19209 directory.
19211 @anchor{sed}
19212 @item @command{sed}
19213 @c ----------------
19214 @prindex @command{sed}
19215 Patterns should not include the separator (unless escaped), even as part
19216 of a character class.  In conformance with Posix, the Cray
19217 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19218 Even when escaped, patterns should not include separators that are also
19219 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19220 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19221 before evaluating the basic regular expression.
19223 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19224 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19225 them.
19227 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19229 Sed scripts should not use branch labels longer than 7 characters and
19230 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19231 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19232 48 labels, which can not be circumvented by using more than one script
19233 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19234 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19235 about 6000 bytes for the internal representation of commands.
19237 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19238 NetBSD 1.4.2's, incorrectly try to interpret the second
19239 @samp{;} as a command:
19241 @example
19242 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19243 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19244 @end example
19246 Input should not have unreasonably long lines, since some @command{sed}
19247 implementations have an input buffer limited to 4000 bytes.  Likewise,
19248 not all @command{sed} implementations can handle embedded @code{NUL} or
19249 a missing trailing newline.
19251 Remember that ranges within a bracket expression of a regular expression
19252 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19253 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19254 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19255 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19256 than to rely on @samp{[A-Z]}.
19258 Additionally, Posix states that regular expressions are only
19259 well-defined on characters.  Unfortunately, there exist platforms such
19260 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19261 even though that platform has a single-byte @samp{C} locale.  And Posix
19262 allows the existence of a multi-byte @samp{C} locale, although that does
19263 not yet appear to be a common implementation.  At any rate, it means
19264 that not all bytes will be matched by the regular expression @samp{.}:
19266 @example
19267 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19269 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19271 @end example
19273 Portable @command{sed} regular expressions should use @samp{\} only to escape
19274 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19275 alternation, @samp{\|}, is common but Posix does not require its
19276 support, so it should be avoided in portable scripts.  Solaris
19277 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19278 deletes only lines that contain the literal string @samp{a|b}.
19279 Similarly, @samp{\+} and @samp{\?} should be avoided.
19281 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19283 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19284 quite portable to current hosts, but was not supported by some ancient
19285 @command{sed} implementations like SVR3.
19287 Some @command{sed} implementations, e.g., Solaris, restrict the special
19288 role of the asterisk @samp{*} to one-character regular expressions and
19289 back-references, and the special role of interval expressions
19290 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19291 to one-character regular expressions.  This may lead to unexpected behavior:
19293 @example
19294 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19295 x2x4
19296 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19298 @end example
19300 The @option{-e} option is mostly portable.
19301 However, its argument
19302 cannot start with @samp{a}, @samp{c}, or @samp{i},
19303 as this runs afoul of a Tru64 5.1 bug.
19304 Also, its argument cannot be empty, as this fails on AIX 5.3.
19305 Some people prefer to use @samp{-e}:
19307 @example
19308 sed -e '@var{command-1}' \
19309     -e '@var{command-2}'
19310 @end example
19312 @noindent
19313 as opposed to the equivalent:
19315 @example
19316 sed '
19317   @var{command-1}
19318   @var{command-2}
19320 @end example
19322 @noindent
19323 The following usage is sometimes equivalent:
19325 @example
19326 sed '@var{command-1};@var{command-2}'
19327 @end example
19329 but Posix says that this use of a semicolon has undefined effect if
19330 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19331 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19332 should use semicolon only with simple scripts that do not use these
19333 verbs.
19335 Posix up to the 2008 revision requires the argument of the @option{-e}
19336 option to be a syntactically complete script.  GNU @command{sed} allows
19337 to pass multiple script fragments, each as argument of a separate
19338 @option{-e} option, that are then combined, with newlines between the
19339 fragments, and a future Posix revision may allow this as well.  This
19340 approach is not portable with script fragments ending in backslash; for
19341 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19342 don't allow splitting in this case:
19344 @example
19345 $ @kbd{echo a | sed -n -e 'i\}
19346 @kbd{0'}
19348 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19349 Unrecognized command: 0
19350 @end example
19352 @noindent
19353 In practice, however, this technique of joining fragments
19354 through @option{-e} works for multiple @command{sed} functions within
19355 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19357 @example
19358 @c The quote around the closing brace silences interactive zsh.
19359 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19361 @end example
19363 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19364 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19365 each command must be followed immediately by a newline, without any
19366 intervening blanks or semicolons.  The closing bracket must be alone on
19367 a line, other than white space preceding or following it.  However, a
19368 future version of Posix may standardize the use of addresses within brackets.
19370 Contrary to yet another urban legend, you may portably use @samp{&} in
19371 the replacement part of the @code{s} command to mean ``what was
19372 matched''.  All descendants of Unix version 7 @command{sed}
19373 (at least; we
19374 don't have first hand experience with older @command{sed} implementations) have
19375 supported it.
19377 Posix requires that you must not have any white space between
19378 @samp{!} and the following command.  It is OK to have blanks between
19379 the address and the @samp{!}.  For instance, on Solaris:
19381 @example
19382 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19383 @error{}Unrecognized command: /bar/ ! p
19384 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19385 @error{}Unrecognized command: /bar/! p
19386 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19388 @end example
19390 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19391 you use @samp{!}, it is best to put it on a command that is delimited by
19392 newlines rather than @samp{;}.
19394 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19395 @samp{w} commands be followed by exactly one space before their argument.
19396 On the other hand, no white space is allowed between @samp{:} and the
19397 subsequent label name.
19399 If a sed script is specified on the command line and ends in an
19400 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19401 should be followed by a newline.  Otherwise some @command{sed}
19402 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19403 inserted text.
19405 Many @command{sed} implementations (e.g., MacOS X 10.4,
19406 OpenBSD 3.9, Solaris 10
19407 @command{/usr/ucb/sed}) strip leading white space from the text of
19408 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19409 work around this incompatibility with Posix:
19411 @example
19412 $ @kbd{echo flushleft | sed 'a\}
19413 > @kbd{   indented}
19414 > @kbd{'}
19415 flushleft
19416 indented
19417 $ @kbd{echo foo | sed 'a\}
19418 > @kbd{\   indented}
19419 > @kbd{'}
19420 flushleft
19421    indented
19422 @end example
19424 Posix requires that with an empty regular expression, the last non-empty
19425 regular expression from either an address specification or substitution
19426 command is applied.  However, busybox 1.6.1 complains when using a
19427 substitution command with a replacement containing a back-reference to
19428 an empty regular expression; the workaround is repeating the regular
19429 expression.
19431 @example
19432 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19433 sed: No previous regexp.
19434 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19436 @end example
19439 @item @command{sed} (@samp{t})
19440 @c ---------------------------
19441 @prindex @command{sed} (@samp{t})
19442 Some old systems have @command{sed} that ``forget'' to reset their
19443 @samp{t} flag when starting a new cycle.  For instance on MIPS
19444 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19445 script (the line numbers are not actual part of the texts):
19447 @example
19448 s/keep me/kept/g  # a
19449 t end             # b
19450 s/.*/deleted/g    # c
19451 :end              # d
19452 @end example
19454 @noindent
19457 @example
19458 delete me         # 1
19459 delete me         # 2
19460 keep me           # 3
19461 delete me         # 4
19462 @end example
19464 @noindent
19465 you get
19467 @example
19468 deleted
19469 delete me
19470 kept
19471 deleted
19472 @end example
19474 @noindent
19475 instead of
19477 @example
19478 deleted
19479 deleted
19480 kept
19481 deleted
19482 @end example
19484 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19485 flag, and the output is produced.  When processing
19486 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19487 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19488 flag when a substitution fails.  Command (b) sees that the flag is set,
19489 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19490 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19491 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19492 Finally, since the flag is clear, line 4 is processed properly.
19494 There are two things one should remember about @samp{t} in @command{sed}.
19495 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19496 succeeded, not only the immediately preceding substitution.  Therefore,
19497 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19498 line, to reset the @samp{t} flag where needed.
19500 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19501 cycle.
19503 One portable implementation of the script above is:
19505 @example
19506 t clear
19507 :clear
19508 s/keep me/kept/g
19509 t end
19510 s/.*/deleted/g
19511 :end
19512 @end example
19514 @item @command{sleep}
19515 @c ------------------
19516 @prindex @command{sleep}
19517 Using @command{sleep} is generally portable.  However, remember that
19518 adding a @command{sleep} to work around timestamp issues, with a minimum
19519 granularity of one second, doesn't scale well for parallel builds on
19520 modern machines with sub-second process completion.
19522 @item @command{sort}
19523 @c -----------------
19524 @prindex @command{sort}
19525 Remember that sort order is influenced by the current locale.  Inside
19526 @file{configure}, the C locale is in effect, but in Makefile snippets,
19527 you may need to specify @code{LC_ALL=C sort}.
19529 @item @command{tar}
19530 @c ----------------
19531 @prindex @command{tar}
19532 There are multiple file formats for @command{tar}; if you use Automake,
19533 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19534 level of portability to use.
19536 @anchor{touch}
19537 @item @command{touch}
19538 @c ------------------
19539 @prindex @command{touch}
19540 @cindex timestamp resolution
19541 If you specify the desired timestamp (e.g., with the @option{-r}
19542 option), older @command{touch} implementations use the @code{utime} or
19543 @code{utimes} system call, which can result in the same kind of
19544 timestamp truncation problems that @samp{cp -p} has.
19546 On ancient BSD systems, @command{touch} or any command that
19547 results in an empty file does not update the timestamps, so use a
19548 command like @command{echo} as a workaround.
19549 Also,
19550 GNU @command{touch} 3.16r (and presumably all before that)
19551 fails to work on SunOS 4.1.3 when the empty file is on an
19552 NFS-mounted 4.2 volume.
19553 However, these problems are no longer of practical concern.
19555 @item @command{tr}
19556 @c ---------------
19557 @prindex @command{tr}
19558 @cindex carriage return, deleting
19559 @cindex newline, deleting
19560 @cindex deleting carriage return
19561 Not all versions of @command{tr} handle all backslash character escapes.
19562 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19563 Solaris contains more modern @command{tr} in other locations.
19564 Using octal escapes is more portable for carriage returns, since
19565 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19566 literal carriage returns in scripts causes a number of other problems.
19567 But for other characters, like newline, using octal escapes ties the
19568 operation to ASCII, so it is better to use literal characters.
19570 @example
19571 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19573 light
19574 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19575 moonlight
19576 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19577 moonlight
19578 $ @kbd{nl='}
19579 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19580 moonlight
19581 @end example
19583 Not all versions of @command{tr} recognize direct ranges of characters: at
19584 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19585 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19586 transliterate to themselves).
19588 @example
19589 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19590 HAZy FAntAZy
19591 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19592 HAZY FANTAZY
19593 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19594 HAZY FANTAZY
19595 @end example
19597 When providing two arguments, be sure the second string is at least as
19598 long as the first.
19600 @example
19601 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19603 $ @kbd{echo abc | coreutils/tr bc d}
19605 @end example
19607 Posix requires @command{tr} to operate on binary files.  But at least
19608 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19609 @code{NUL} in the input prior to doing any translation.  When using
19610 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19611 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19612 @command{/usr/xpg6/bin/tr} if that is available.
19614 @example
19615 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19616  61 62
19617 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19618  61 62
19619 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19620  61 00 62
19621 @end example
19623 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19624 octal escape for @code{NUL}.
19626 @example
19627 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19628  61 62 63
19629 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19630  61 00 64
19631 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19632  61 00 64
19633 @end example
19635 @end table
19638 @node Portable Make
19639 @chapter Portable Make Programming
19640 @prindex @command{make}
19641 @cindex Limitations of @command{make}
19643 Writing portable makefiles is an art.  Since a makefile's commands are
19644 executed by the shell, you must consider the shell portability issues
19645 already mentioned.  However, other issues are specific to @command{make}
19646 itself.
19648 @menu
19649 * $< in Ordinary Make Rules::   $< in ordinary rules
19650 * Failure in Make Rules::       Failing portably in rules
19651 * Special Chars in Names::      Special Characters in Macro Names
19652 * Backslash-Newline-Newline::   Empty last lines in macro definitions
19653 * Backslash-Newline Comments::  Spanning comments across line boundaries
19654 * Long Lines in Makefiles::     Line length limitations
19655 * Macros and Submakes::         @code{make macro=value} and submakes
19656 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19657 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19658 * Parallel Make::               Parallel @command{make} quirks
19659 * Comments in Make Rules::      Other problems with Make comments
19660 * Newlines in Make Rules::      Using literal newlines in rules
19661 * Comments in Make Macros::     Other problems with Make comments in macros
19662 * Trailing whitespace in Make Macros::  Macro substitution problems
19663 * Command-line Macros and whitespace::  Whitespace trimming of values
19664 * obj/ and Make::               Don't name a subdirectory @file{obj}
19665 * make -k Status::              Exit status of @samp{make -k}
19666 * VPATH and Make::              @code{VPATH} woes
19667 * Single Suffix Rules::         Single suffix rules and separated dependencies
19668 * Timestamps and Make::         Subsecond timestamp resolution
19669 @end menu
19671 @node $< in Ordinary Make Rules
19672 @section @code{$<} in Ordinary Make Rules
19674 Posix says that the @samp{$<} construct in makefiles can be
19675 used only in inference rules and in the @samp{.DEFAULT} rule; its
19676 meaning in ordinary rules is unspecified.  Solaris @command{make}
19677 for instance replaces it with the empty string.  OpenBSD (3.0 and
19678 later) @command{make} diagnoses these uses and errors out.
19680 @node Failure in Make Rules
19681 @section Failure in Make Rules
19683 Posix 2008 requires that @command{make} must invoke each command with
19684 the equivalent of a @samp{sh -e -c} subshell, which causes the
19685 subshell to exit immediately if a subsidiary simple-command fails,
19686 although not all @command{make} implementations have historically
19687 followed this rule.  For
19688 example, the command @samp{touch T; rm -f U} may attempt to
19689 remove @file{U} even if the @command{touch} fails, although this is not
19690 permitted with Posix make.  One way to work around failures in simple
19691 commands is to reword them so that they always succeed, e.g., @samp{touch
19692 T || :; rm -f U}.
19693 However, even this approach can run into common bugs in BSD
19694 implementations of the @option{-e} option of @command{sh} and
19695 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19696 are worried
19697 about porting to buggy BSD shells it may be simpler to migrate
19698 complicated @command{make} actions into separate scripts.
19700 @node Special Chars in Names
19701 @section Special Characters in Make Macro Names
19703 Posix limits macro names to nonempty strings containing only
19704 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19705 @command{make} implementations allow a wider variety of characters, but
19706 portable makefiles should avoid them.  It is portable to start a name
19707 with a special character, e.g., @samp{$(.FOO)}.
19709 Some ancient @command{make} implementations don't support leading
19710 underscores in macro names.  An example is NEWS-OS 4.2R.
19712 @example
19713 $ @kbd{cat Makefile}
19714 _am_include = #
19715 _am_quote =
19716 all:; @@echo this is test
19717 $ @kbd{make}
19718 Make: Must be a separator on rules line 2.  Stop.
19719 $ @kbd{cat Makefile2}
19720 am_include = #
19721 am_quote =
19722 all:; @@echo this is test
19723 $ @kbd{make -f Makefile2}
19724 this is test
19725 @end example
19727 @noindent
19728 However, this problem is no longer of practical concern.
19730 @node Backslash-Newline-Newline
19731 @section Backslash-Newline-Newline in Make Macro Values
19733 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19734 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19735 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19736 On some versions of HP-UX, @command{make} reads multiple newlines
19737 following a backslash, continuing to the next non-empty line.  For
19738 example,
19740 @example
19741 FOO = one \
19743 BAR = two
19745 test:
19746         : FOO is "$(FOO)"
19747         : BAR is "$(BAR)"
19748 @end example
19750 @noindent
19751 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19752 sensibly let a backslash continue only to the immediately following
19753 line.
19755 @node Backslash-Newline Comments
19756 @section Backslash-Newline in Make Comments
19758 According to Posix, Make comments start with @code{#}
19759 and continue until an unescaped newline is reached.
19761 @example
19762 $ @kbd{cat Makefile}
19763 # A = foo \
19764       bar \
19765       baz
19767 all:
19768         @@echo ok
19769 $ @kbd{make}   # GNU make
19771 @end example
19773 @noindent
19774 However this is not always the case.  Some implementations
19775 discard everything from @code{#} through the end of the line, ignoring any
19776 trailing backslash.
19778 @example
19779 $ @kbd{pmake}  # BSD make
19780 "Makefile", line 3: Need an operator
19781 Fatal errors encountered -- cannot continue
19782 @end example
19784 @noindent
19785 Therefore, if you want to comment out a multi-line definition, prefix each
19786 line with @code{#}, not only the first.
19788 @example
19789 # A = foo \
19790 #     bar \
19791 #     baz
19792 @end example
19794 @node Long Lines in Makefiles
19795 @section Long Lines in Makefiles
19797 Tru64 5.1's @command{make} has been reported to crash when given a
19798 makefile with lines longer than around 20 kB.  Earlier versions are
19799 reported to exit with @code{Line too long} diagnostics.
19801 @node Macros and Submakes
19802 @section @code{make macro=value} and Submakes
19804 A command-line variable definition such as @code{foo=bar} overrides any
19805 definition of @code{foo} in a makefile.  Some @command{make}
19806 implementations (such as GNU @command{make}) propagate this
19807 override to subsidiary invocations of @command{make}.  Some other
19808 implementations do not pass the substitution along to submakes.
19810 @example
19811 $ @kbd{cat Makefile}
19812 foo = foo
19813 one:
19814         @@echo $(foo)
19815         $(MAKE) two
19816 two:
19817         @@echo $(foo)
19818 $ @kbd{make foo=bar}            # GNU make 3.79.1
19820 make two
19821 make[1]: Entering directory `/home/adl'
19823 make[1]: Leaving directory `/home/adl'
19824 $ @kbd{pmake foo=bar}           # BSD make
19826 pmake two
19828 @end example
19830 You have a few possibilities if you do want the @code{foo=bar} override
19831 to propagate to submakes.  One is to use the @option{-e}
19832 option, which causes all environment variables to have precedence over
19833 the makefile macro definitions, and declare foo as an environment
19834 variable:
19836 @example
19837 $ @kbd{env foo=bar make -e}
19838 @end example
19840 The @option{-e} option is propagated to submakes automatically,
19841 and since the environment is inherited between @command{make}
19842 invocations, the @code{foo} macro is overridden in
19843 submakes as expected.
19845 This syntax (@code{foo=bar make -e}) is portable only when used
19846 outside of a makefile, for instance from a script or from the
19847 command line.  When run inside a @command{make} rule, GNU
19848 @command{make} 3.80 and prior versions forget to propagate the
19849 @option{-e} option to submakes.
19851 Moreover, using @option{-e} could have unexpected side effects if your
19852 environment contains some other macros usually defined by the
19853 makefile.  (See also the note about @code{make -e} and @code{SHELL}
19854 below.)
19856 If you can foresee all macros that a user might want to override, then
19857 you can propagate them to submakes manually, from your makefile:
19859 @example
19860 foo = foo
19861 one:
19862         @@echo $(foo)
19863         $(MAKE) foo=$(foo) two
19864 two:
19865         @@echo $(foo)
19866 @end example
19868 Another way to propagate a variable to submakes in a portable way is to
19869 expand an extra variable in every invocation of @samp{$(MAKE)} within
19870 your makefile:
19872 @example
19873 foo = foo
19874 one:
19875         @@echo $(foo)
19876         $(MAKE) $(SUBMAKEFLAGS) two
19877 two:
19878         @@echo $(foo)
19879 @end example
19881 Users must be aware that this technique is in use to take advantage of
19882 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
19883 allows any macro to be overridden.  Makefiles generated by
19884 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
19885 on the command lines of submakes (@pxref{Subdirectories, , Automake,
19886 automake, GNU Automake}).
19888 @node The Make Macro MAKEFLAGS
19889 @section The Make Macro MAKEFLAGS
19890 @cindex @code{MAKEFLAGS} and @command{make}
19891 @cindex @command{make} and @code{MAKEFLAGS}
19893 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
19894 current and recursive invocations of make, but allows implementations
19895 several formats for the variable.  It is tricky to parse
19896 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
19897 or @option{-k} for continued execution are in effect.  For example, you
19898 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
19899 contains single-letter options, since in the Cygwin version of
19900 GNU @command{make} it is either @option{--unix} or
19901 @option{--win32} with the second word containing single-letter options.
19903 @example
19904 $ @kbd{cat Makefile}
19905 all:
19906         @@echo MAKEFLAGS = $(MAKEFLAGS)
19907 $ @kbd{make}
19908 MAKEFLAGS = --unix
19909 $ @kbd{make -k}
19910 MAKEFLAGS = --unix -k
19911 @end example
19913 @node The Make Macro SHELL
19914 @section The Make Macro @code{SHELL}
19915 @cindex @code{SHELL} and @command{make}
19916 @cindex @command{make} and @code{SHELL}
19918 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
19919 macro to spawn shell processes and execute Make rules.  This
19920 is a builtin macro supplied by @command{make}, but it can be modified
19921 by a makefile or by a command-line argument.
19923 Not all @command{make} implementations define this @code{SHELL} macro.
19924 Tru64
19925 @command{make} is an example; this implementation always uses
19926 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
19927 your makefiles.  If you use Autoconf, do
19929 @example
19930 SHELL = @@SHELL@@
19931 @end example
19933 @noindent
19934 If you use Automake, this is done for you.
19936 Do not force @code{SHELL = /bin/sh} because that is not correct
19937 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
19938 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
19939 Additionally, DJGPP lacks @code{/bin/sh}, and when its
19940 GNU @command{make} port sees such a setting it enters a
19941 special emulation mode where features like pipes and redirections are
19942 emulated on top of DOS's @command{command.com}.  Unfortunately this
19943 emulation is incomplete; for instance it does not handle command
19944 substitutions.  Using @code{@@SHELL@@} means that your makefile will
19945 benefit from the same improved shell, such as @command{bash} or
19946 @command{ksh}, that was discovered during @command{configure}, so that
19947 you aren't fighting two different sets of shell bugs between the two
19948 contexts.
19950 Posix-compliant @command{make} should never acquire the value of
19951 $(SHELL) from the environment, even when @code{make -e} is used
19952 (otherwise, think about what would happen to your rules if
19953 @code{SHELL=/bin/tcsh}).
19955 However not all @command{make} implementations have this exception.
19956 For instance it's not surprising that Tru64 @command{make} doesn't
19957 protect @code{SHELL}, since it doesn't use it.
19959 @example
19960 $ @kbd{cat Makefile}
19961 SHELL = /bin/sh
19962 FOO = foo
19963 all:
19964         @@echo $(SHELL)
19965         @@echo $(FOO)
19966 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
19967 /bin/tcsh
19969 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
19970 /bin/sh
19972 @end example
19974 Conversely, @command{make} is not supposed to export any changes to the
19975 macro @code{SHELL} to child processes.  Again, many implementations
19976 break this rule:
19978 @example
19979 $ @kbd{cat Makefile}
19980 all:
19981         @@echo $(SHELL)
19982         @@printenv SHELL
19983 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
19984 /bin/ksh
19985 /bin/ksh
19986 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
19987 /bin/ksh
19989 @end example
19991 @node Parallel Make
19992 @section Parallel Make
19993 @cindex Parallel @command{make}
19995 Support for parallel execution in @command{make} implementation varies.
19996 Generally, using GNU make is your best bet.
19998 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
19999 reuse the same shell for multiple commands within one recipe.  This can
20000 have various unexpected consequences.  For example, changes of directories
20001 or variables persist between recipes, so that:
20003 @example
20004 all:
20005         @@var=value; cd /; pwd; echo $$var; echo $$$$
20006         @@pwd; echo $$var; echo $$$$
20007 @end example
20009 @noindent
20010 may output the following with @code{make -j1}, at least on NetBSD up to
20011 5.1 and FreeBSD up to 8.2:
20013 @example
20015 value
20016 32235
20018 value
20019 32235
20020 @end example
20022 @noindent
20023 while without @option{-j1}, or with @option{-B}, the output looks less
20024 surprising:
20026 @example
20028 value
20029 32238
20030 /tmp
20032 32239
20033 @end example
20035 @noindent
20036 Another consequence is that, if one command in a recipe uses @code{exit 0}
20037 to indicate a successful exit, the shell will be gone and the remaining
20038 commands of this recipe will not be executed.
20040 The BSD @command{make} implementations, when run in parallel mode,
20041 will also pass the @command{Makefile} recipes to the shell through
20042 its standard input, thus making it unusable from the recipes:
20044 @example
20045 $ @kbd{cat Makefile}
20046 read:
20047         @@read line; echo LINE: $$line
20048 @c $$ @c restore font-lock
20049 $ @kbd{echo foo | make read}
20050 LINE: foo
20051 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20052 LINE:
20053 @end example
20055 @noindent
20056 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20057 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20058 modifiers'' by dynamically modifying the active shell flags.  This
20059 behavior has the effects of potentially clobbering the exit status
20060 of recipes silenced with the @code{@@} modifier if they also unset
20061 the @option{errexit} shell flag, and of mangling the output in
20062 unexpected ways:
20064 @example
20065 $ @kbd{cat Makefile}
20067         @@echo $$-; set +e; false
20069         -echo $$-; false; echo set -
20070 $ @kbd{make a; echo status: $?}
20071 ehBc
20072 *** Error code 1
20073 status: 1
20074 $ @kbd{make -j1 a; echo status: $?}
20076 status: 0
20077 $ @kbd{make b}
20078 echo $-; echo set -
20080 set -
20081 $ @kbd{make -j1 b}
20082 echo $-; echo hvB
20083 @end example
20085 @noindent
20086 You can avoid all these issues by using the @option{-B} option to enable
20087 compatibility semantics.  However, that will effectively also disable
20088 all parallelism as that will cause prerequisites to be updated in the
20089 order they are listed in a rule.
20091 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20092 @command{make}, and Solaris @command{dmake}), when invoked with a
20093 @option{-j@var{N}} option, connect the standard output and standard
20094 error of all their child processes to pipes or temporary regular
20095 files.  This can lead to subtly different semantics in the behavior
20096 of the spawned processes.  For example, even if the @command{make}
20097 standard output is connected to a tty, the recipe command will not be:
20099 @example
20100 $ @kbd{cat Makefile}
20101 all:
20102         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20103 $ @kbd{make -j 2} # FreeBSD 8.2 make
20104 Is not a tty
20105 $ @kbd{make -j 2} # NetBSD 5.1 make
20106 --- all ---
20107 Is not a tty
20108 $ @kbd{dmake -j 2} # Solaris 10 dmake
20109 @var{hostname} --> 1 job
20110 @var{hostname} --> Job output
20111 Is not a tty
20112 @end example
20114 @noindent
20115 On the other hand:
20117 @example
20118 $ @kbd{make -j 2} # GNU make, Heirloom make
20119 Is a tty
20120 @end example
20122 @noindent
20123 The above examples also show additional status output produced in parallel
20124 mode for targets being updated by Solaris @command{dmake} and NetBSD
20125 @command{make} (but @emph{not} by FreeBSD @command{make}).
20127 Furthermore, parallel runs of those @command{make} implementations will
20128 route standard error from commands that they spawn into their own
20129 standard output, and may remove leading whitespace from output lines.
20132 @node Comments in Make Rules
20133 @section Comments in Make Rules
20134 @cindex Comments in @file{Makefile} rules
20135 @cindex @file{Makefile} rules and comments
20137 Never put comments in a rule.
20139 Some @command{make} treat anything starting with a tab as a command for
20140 the current rule, even if the tab is immediately followed by a @code{#}.
20141 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20142 makefile runs @code{# foo} through the shell.
20144 @example
20145 all:
20146         # foo
20147 @end example
20149 As a workaround, you can use the @command{:} no-op command with a string
20150 argument that gets ignored:
20152 @example
20153 all:
20154         : "foo"
20155 @end example
20157 Conversely, if you want to use the @samp{#} character in some command,
20158 you can only do so by expanding it inside a rule (@pxref{Comments in
20159 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20160 @command{config.status} as @samp{#}, then the following substitutes
20161 @samp{@@COMMENT_CHAR@@} in a generated header:
20163 @example
20164 foo.h: foo.h.in
20165         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20166             $(srcdir)/foo.h.in > $@@
20167 @end example
20169 The funny shell quoting avoids a substitution at @command{config.status}
20170 run time of the left-hand side of the @command{sed} @samp{s} command.
20172 @node Newlines in Make Rules
20173 @section Newlines in Make Rules
20174 @cindex Newlines in @file{Makefile} rules
20175 @cindex @file{Makefile} rules and newlines
20177 In shell scripts, newlines can be used inside string literals.  But in
20178 the shell statements of @file{Makefile} rules, this is not possible:
20179 A newline not preceded by a backslash is a separator between shell
20180 statements.  Whereas a newline that is preceded by a backslash becomes
20181 part of the shell statement according to POSIX, but gets replaced,
20182 together with the backslash that precedes it, by a space in GNU
20183 @command{make} 3.80 and older.  So, how can a newline be used in a string
20184 literal?
20186 The trick is to set up a shell variable that contains a newline:
20188 @example
20189 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20190 @end example
20192 For example, in order to create a multiline @samp{sed} expression that
20193 inserts a blank line after every line of a file, this code can be used:
20195 @example
20196 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20197 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20198 @end example
20200 @node Comments in Make Macros
20201 @section Comments in Make Macros
20202 @cindex Comments in @file{Makefile} macros
20203 @cindex @file{Makefile} macros and comments
20205 Avoid putting comments in macro values as far as possible.  Posix
20206 specifies that the text starting from the @samp{#} sign until the end of
20207 the line is to be ignored, which has the unfortunate effect of
20208 disallowing them even within quotes.  Thus, the following might lead to
20209 a syntax error at compile time:
20211 @example
20212 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20213 @end example
20215 @noindent
20216 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20218 Most @command{make} implementations disregard this and treat single and
20219 double quotes specially here.  Also, GNU @command{make} lets you put
20220 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20221 @samp{\#}.  However, neither of these usages are portable.
20222 @xref{Comments in Make Rules}, for a portable alternative.
20224 Even without quoting involved, comments can have surprising effects,
20225 because the whitespace before them is part of the variable value:
20227 @example
20228 foo = bar # trailing comment
20229 print: ; @@echo "$(foo)."
20230 @end example
20232 @noindent
20233 prints @samp{bar .}, which is usually not intended, and can expose
20234 @command{make} bugs as described below.
20236 @node Trailing whitespace in Make Macros
20237 @section Trailing whitespace in Make Macros
20238 @cindex whitespace in @file{Makefile} macros
20239 @cindex @file{Makefile} macros and whitespace
20241 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20242 substitutions and appends another spurious suffix:
20244 @example
20245 empty =
20246 foo = bar $(empty)
20247 print: ; @@echo $(foo:=.test)
20248 @end example
20250 @noindent
20251 prints @samp{bar.test .test}.
20253 BSD and Solaris @command{make} implementations do not honor trailing
20254 whitespace in macro definitions as Posix requires:
20256 @example
20257 foo = bar # Note the space after "bar".
20258 print: ; @@echo $(foo)t
20259 @end example
20261 @noindent
20262 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20263 can use a helper macro as in the previous example.
20266 @node Command-line Macros and whitespace
20267 @section Command-line Macros and whitespace
20268 @cindex whitespace in command-line macros
20269 @cindex command-line, macros set on
20270 @cindex environment, macros set from
20272 Some @command{make} implementations may strip trailing whitespace off
20273 of macros set on the command line in addition to leading whitespace.
20274 Further, some may strip leading whitespace off of macros set from
20275 environment variables:
20277 @example
20278 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20279   foo=' f f ' make -f - bar=' b b '}
20280 x f f xb b x  # AIX, BSD, GNU make
20281 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20282 x f f xb bx   # Solaris make
20283 @end example
20286 @node obj/ and Make
20287 @section The @file{obj/} Subdirectory and Make
20288 @cindex @file{obj/}, subdirectory
20289 @cindex BSD @command{make} and @file{obj/}
20291 Never name one of your subdirectories @file{obj/} if you don't like
20292 surprises.
20294 If an @file{obj/} directory exists, BSD @command{make} enters it
20295 before reading the makefile.  Hence the makefile in the
20296 current directory is not read.
20298 @example
20299 $ @kbd{cat Makefile}
20300 all:
20301         echo Hello
20302 $ @kbd{cat obj/Makefile}
20303 all:
20304         echo World
20305 $ @kbd{make}      # GNU make
20306 echo Hello
20307 Hello
20308 $ @kbd{pmake}     # BSD make
20309 echo World
20310 World
20311 @end example
20313 @node make -k Status
20314 @section Exit Status of @code{make -k}
20315 @cindex @code{make -k}
20317 Do not rely on the exit status of @code{make -k}.  Some implementations
20318 reflect whether they encountered an error in their exit status; other
20319 implementations always succeed.
20321 @example
20322 $ @kbd{cat Makefile}
20323 all:
20324         false
20325 $ @kbd{make -k; echo exit status: $?}    # GNU make
20326 false
20327 make: *** [all] Error 1
20328 exit status: 2
20329 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20330 false
20331 *** Error code 1 (continuing)
20332 exit status: 0
20333 @end example
20335 @node VPATH and Make
20336 @section @code{VPATH} and Make
20337 @cindex @code{VPATH}
20339 Posix does not specify the semantics of @code{VPATH}.  Typically,
20340 @command{make} supports @code{VPATH}, but its implementation is not
20341 consistent.
20343 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20344 portable to recent-enough popular implementations of @command{make}, but
20345 to keep the resulting makefiles portable, a package's makefile
20346 prototypes must take the following issues into account.  These issues
20347 are complicated and are often poorly understood, and installers who use
20348 @code{VPATH} should expect to find many bugs in this area.  If you use
20349 @code{VPATH}, the simplest way to avoid these portability bugs is to
20350 stick with GNU @command{make}, since it is the most
20351 commonly-used @command{make} among Autoconf users.
20353 Here are some known issues with some @code{VPATH}
20354 implementations.
20356 @menu
20357 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20358 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20359 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20360 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20361 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20362 * Make Target Lookup::          More details about @code{VPATH} lookup
20363 @end menu
20365 @node Variables listed in VPATH
20366 @subsection Variables listed in @code{VPATH}
20367 @cindex @code{VPATH} and variables
20368 @cindex variables and @code{VPATH}
20370 Do not set @code{VPATH} to the value of another variable, for example
20371 @samp{VPATH = $(srcdir)}, because some ancient versions of
20372 @command{make} do not do variable substitutions on the value of
20373 @code{VPATH}.  For example, use this
20375 @example
20376 srcdir = @@srcdir@@
20377 VPATH = @@srcdir@@
20378 @end example
20380 @noindent
20381 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20382 Automake, there is no need to set this yourself.
20384 @node VPATH and Double-colon
20385 @subsection @code{VPATH} and Double-colon Rules
20386 @cindex @code{VPATH} and double-colon rules
20387 @cindex double-colon rules and @code{VPATH}
20389 With ancient versions of Sun @command{make},
20390 any assignment to @code{VPATH} causes @command{make} to execute only
20391 the first set of double-colon rules.
20392 However, this problem is no longer of practical concern.
20394 @node $< in Explicit Rules
20395 @subsection @code{$<} Not Supported in Explicit Rules
20396 @cindex explicit rules, @code{$<}, and @code{VPATH}
20397 @cindex @code{$<}, explicit rules, and @code{VPATH}
20398 @cindex @code{VPATH}, explicit rules, and @code{$<}
20400 Using @code{$<} in explicit rules is not portable.
20401 The prerequisite file must be named explicitly in the rule.  If you want
20402 to find the prerequisite via a @code{VPATH} search, you have to code the
20403 whole thing manually.  @xref{Build Directories}.
20405 @node Automatic Rule Rewriting
20406 @subsection Automatic Rule Rewriting
20407 @cindex @code{VPATH} and automatic rule rewriting
20408 @cindex automatic rule rewriting and @code{VPATH}
20410 Some @command{make} implementations, such as Solaris and Tru64,
20411 search for prerequisites in @code{VPATH} and
20412 then rewrite each occurrence as a plain word in the rule.
20413 For instance:
20415 @example
20416 # This isn't portable to GNU make.
20417 VPATH = ../pkg/src
20418 f.c: if.c
20419         cp if.c f.c
20420 @end example
20422 @noindent
20423 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20424 found in @file{../pkg/src}.
20426 However, this rule leads to real problems in practice.  For example, if
20427 the source directory contains an ordinary file named @file{test} that is
20428 used in a dependency, Solaris @command{make} rewrites commands like
20429 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20430 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20431 completely unaware of shell syntax used in the rules, so the VPATH
20432 rewrite can potentially apply to @emph{any} whitespace-separated word
20433 in a rule, including shell variables, functions, and keywords.
20435 @example
20436 $ @kbd{mkdir build}
20437 $ @kbd{cd build}
20438 $ @kbd{cat > Makefile <<'END'}
20439 VPATH = ..
20440 all: arg func for echo
20441         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20442         func "hello world"
20444 $ @kbd{touch ../arg ../func ../for ../echo}
20445 $ @kbd{make}
20446 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20447 ../func "hello world"
20448 sh: syntax error at line 1: `do' unexpected
20449 *** Error code 2
20450 @end example
20452 @noindent
20453 To avoid this problem, portable makefiles should never mention a source
20454 file or dependency whose name is that of a shell keyword like @file{for}
20455 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20456 @command{test}, or a shell function or variable used in the corresponding
20457 @command{Makefile} recipe.
20459 Because of these problems GNU @command{make} and many other @command{make}
20460 implementations do not rewrite commands, so portable makefiles should
20461 search @code{VPATH} manually.  It is tempting to write this:
20463 @smallexample
20464 # This isn't portable to Solaris make.
20465 VPATH = ../pkg/src
20466 f.c: if.c
20467         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20468 @end smallexample
20470 @noindent
20471 However, the ``prerequisite rewriting'' still applies here.  So if
20472 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20473 execute
20475 @smallexample
20476 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20477 @end smallexample
20479 @noindent
20480 which reduces to
20482 @example
20483 cp if.c f.c
20484 @end example
20486 @noindent
20487 and thus fails.  Oops.
20489 A simple workaround, and good practice anyway, is to use @samp{$?} and
20490 @samp{$@@} when possible:
20492 @smallexample
20493 VPATH = ../pkg/src
20494 f.c: if.c
20495         cp $? $@@
20496 @end smallexample
20498 @noindent
20499 but this does not generalize well to commands with multiple
20500 prerequisites.  A more general workaround is to rewrite the rule so that
20501 the prerequisite @file{if.c} never appears as a plain word.  For
20502 example, these three rules would be safe, assuming @file{if.c} is in
20503 @file{../pkg/src} and the other files are in the working directory:
20505 @smallexample
20506 VPATH = ../pkg/src
20507 f.c: if.c f1.c
20508         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20509 g.c: if.c g1.c
20510         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20511 h.c: if.c h1.c
20512         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20513 @end smallexample
20515 Things get worse when your prerequisites are in a macro.
20517 @example
20518 VPATH = ../pkg/src
20519 HEADERS = f.h g.h h.h
20520 install-HEADERS: $(HEADERS)
20521         for i in $(HEADERS); do \
20522           $(INSTALL) -m 644 \
20523             `test -f $$i || echo $(VPATH)/`$$i \
20524             $(DESTDIR)$(includedir)/$$i; \
20525 @c $$ restore font-lock
20526         done
20527 @end example
20529 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20530 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20531 where @code{f.h} and @code{g.h} are plain words and are hence
20532 subject to @code{VPATH} adjustments.
20534 If the three files are in @file{../pkg/src}, the rule is run as:
20536 @example
20537 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20538   install -m 644 \
20539      `test -f $i || echo ../pkg/src/`$i \
20540      /usr/local/include/$i; \
20541 done
20542 @end example
20544 where the two first @command{install} calls fail.  For instance,
20545 consider the @code{f.h} installation:
20547 @example
20548 install -m 644 \
20549   `test -f ../pkg/src/f.h || \
20550     echo ../pkg/src/ \
20551   `../pkg/src/f.h \
20552   /usr/local/include/../pkg/src/f.h;
20553 @end example
20555 @noindent
20556 It reduces to:
20558 @example
20559 install -m 644 \
20560   ../pkg/src/f.h \
20561   /usr/local/include/../pkg/src/f.h;
20562 @end example
20564 Note that the manual @code{VPATH} search did not cause any problems here;
20565 however this command installs @file{f.h} in an incorrect directory.
20567 Trying to quote @code{$(HEADERS)} in some way, as we did for
20568 @code{foo.c} a few makefiles ago, does not help:
20570 @example
20571 install-HEADERS: $(HEADERS)
20572         headers='$(HEADERS)'; \
20573         for i in $$headers; do \
20574           $(INSTALL) -m 644 \
20575             `test -f $$i || echo $(VPATH)/`$$i \
20576             $(DESTDIR)$(includedir)/$$i; \
20577         done
20578 @end example
20580 Now, @code{headers='$(HEADERS)'} macro-expands to:
20582 @example
20583 headers='f.h g.h h.h'
20584 @end example
20586 @noindent
20587 but @code{g.h} is still a plain word.  (As an aside, the idiom
20588 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20589 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20590 syntax error on @code{for i in;}.)
20592 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20594 @example
20595 VPATH = ../pkg/src
20596 HEADERS = f.h g.h h.h
20597 install-HEADERS: $(HEADERS)
20598         headers='$(HEADERS)'; \
20599         for i in $$headers; do \
20600           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20601           $(INSTALL) -m 644 \
20602             `test -f $$i || echo $(VPATH)/`$$i \
20603             $(DESTDIR)$(includedir)/$$i; \
20604 @c $$ restore font-lock
20605         done
20606 @end example
20608 Automake does something similar.  However the above hack works only if
20609 the files listed in @code{HEADERS} are in the current directory or a
20610 subdirectory; they should not be in an enclosing directory.  If we had
20611 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20612 build with Tru64 @command{make}.  The reason is that not only does
20613 Tru64 @command{make} rewrite dependencies, but it also simplifies
20614 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20615 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20616 a leading @file{../pkg/src/} component.
20618 The following example makes the behavior of Tru64 @command{make}
20619 more apparent.
20621 @example
20622 $ @kbd{cat Makefile}
20623 VPATH = sub
20624 all: ../foo
20625         echo ../foo
20626 $ @kbd{ls}
20627 Makefile foo
20628 $ @kbd{make}
20629 echo foo
20631 @end example
20633 @noindent
20634 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20635 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20636 directory does not even exist, this just means that the simplification
20637 occurred before the file was checked for.)
20639 For the record here is how SunOS 4 @command{make} behaves on this
20640 example.
20642 @smallexample
20643 $ @kbd{make}
20644 make: Fatal error: Don't know how to make target `../foo'
20645 $ @kbd{mkdir sub}
20646 $ @kbd{make}
20647 echo sub/../foo
20648 sub/../foo
20649 @end smallexample
20652 @node Tru64 Directory Magic
20653 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20654 @cindex @code{VPATH} and prerequisite directories
20655 @cindex prerequisite directories and @code{VPATH}
20657 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20658 @command{make} creates it in the current directory.
20660 @example
20661 $ @kbd{mkdir -p foo/bar build}
20662 $ @kbd{cd build}
20663 $ @kbd{cat >Makefile <<END
20664 VPATH = ..
20665 all: foo/bar
20666 END}
20667 $ @kbd{make}
20668 mkdir foo
20669 mkdir foo/bar
20670 @end example
20672 This can yield unexpected results if a rule uses a manual @code{VPATH}
20673 search as presented before.
20675 @example
20676 VPATH = ..
20677 all : foo/bar
20678         command `test -d foo/bar || echo ../`foo/bar
20679 @end example
20681 The above @command{command} is run on the empty @file{foo/bar}
20682 directory that was created in the current directory.
20684 @node Make Target Lookup
20685 @subsection Make Target Lookup
20686 @cindex @code{VPATH}, resolving target pathnames
20688 GNU @command{make} uses a complex algorithm to decide when it
20689 should use files found via a @code{VPATH} search.  @xref{Search
20690 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20691 Manual}.
20693 If a target needs to be rebuilt, GNU @command{make} discards the
20694 file name found during the @code{VPATH} search for this target, and
20695 builds the file locally using the file name given in the makefile.
20696 If a target does not need to be rebuilt, GNU @command{make} uses the
20697 file name found during the @code{VPATH} search.
20699 Other @command{make} implementations, like NetBSD @command{make}, are
20700 easier to describe: the file name found during the @code{VPATH} search
20701 is used whether the target needs to be rebuilt or not.  Therefore
20702 new files are created locally, but existing files are updated at their
20703 @code{VPATH} location.
20705 OpenBSD and FreeBSD @command{make}, however,
20706 never perform a
20707 @code{VPATH} search for a dependency that has an explicit rule.
20708 This is extremely annoying.
20710 When attempting a @code{VPATH} build for an autoconfiscated package
20711 (e.g., @code{mkdir build && cd build && ../configure}), this means
20713 @command{make} builds everything locally in the @file{build}
20714 directory, while BSD @command{make} builds new files locally and
20715 updates existing files in the source directory.
20717 @example
20718 $ @kbd{cat Makefile}
20719 VPATH = ..
20720 all: foo.x bar.x
20721 foo.x bar.x: newer.x
20722         @@echo Building $@@
20723 $ @kbd{touch ../bar.x}
20724 $ @kbd{touch ../newer.x}
20725 $ @kbd{make}        # GNU make
20726 Building foo.x
20727 Building bar.x
20728 $ @kbd{pmake}       # NetBSD make
20729 Building foo.x
20730 Building ../bar.x
20731 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20732 Building foo.x
20733 Building bar.x
20734 $ @kbd{tmake}       # Tru64 make
20735 Building foo.x
20736 Building bar.x
20737 $ @kbd{touch ../bar.x}
20738 $ @kbd{make}        # GNU make
20739 Building foo.x
20740 $ @kbd{pmake}       # NetBSD make
20741 Building foo.x
20742 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20743 Building foo.x
20744 Building bar.x
20745 $ @kbd{tmake}       # Tru64 make
20746 Building foo.x
20747 Building bar.x
20748 @end example
20750 Note how NetBSD @command{make} updates @file{../bar.x} in its
20751 VPATH location, and how FreeBSD, OpenBSD, and Tru64
20752 @command{make} always
20753 update @file{bar.x}, even when @file{../bar.x} is up to date.
20755 Another point worth mentioning is that once GNU @command{make} has
20756 decided to ignore a @code{VPATH} file name (e.g., it ignored
20757 @file{../bar.x} in the above example) it continues to ignore it when
20758 the target occurs as a prerequisite of another rule.
20760 The following example shows that GNU @command{make} does not look up
20761 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20762 because it ignored the @code{VPATH} result of @file{bar.x} while running
20763 the @code{bar.x: newer.x} rule.
20765 @example
20766 $ @kbd{cat Makefile}
20767 VPATH = ..
20768 all: bar.y
20769 bar.x: newer.x
20770         @@echo Building $@@
20771 .SUFFIXES: .x .y
20772 .x.y:
20773         cp $< $@@
20774 $ @kbd{touch ../bar.x}
20775 $ @kbd{touch ../newer.x}
20776 $ @kbd{make}        # GNU make
20777 Building bar.x
20778 cp bar.x bar.y
20779 cp: cannot stat `bar.x': No such file or directory
20780 make: *** [bar.y] Error 1
20781 $ @kbd{pmake}       # NetBSD make
20782 Building ../bar.x
20783 cp ../bar.x bar.y
20784 $ @kbd{rm bar.y}
20785 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20786 echo Building bar.x
20787 cp bar.x bar.y
20788 cp: cannot stat `bar.x': No such file or directory
20789 *** Error code 1
20790 $ @kbd{tmake}       # Tru64 make
20791 Building bar.x
20792 cp: bar.x: No such file or directory
20793 *** Exit 1
20794 @end example
20796 Note that if you drop away the command from the @code{bar.x: newer.x}
20797 rule, GNU @command{make} magically starts to work: it
20798 knows that @code{bar.x} hasn't been updated, therefore it doesn't
20799 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
20800 uses.  Tru64 also works, but FreeBSD and OpenBSD
20801 still don't.
20803 @example
20804 $ @kbd{cat Makefile}
20805 VPATH = ..
20806 all: bar.y
20807 bar.x: newer.x
20808 .SUFFIXES: .x .y
20809 .x.y:
20810         cp $< $@@
20811 $ @kbd{touch ../bar.x}
20812 $ @kbd{touch ../newer.x}
20813 $ @kbd{make}        # GNU make
20814 cp ../bar.x bar.y
20815 $ @kbd{rm bar.y}
20816 $ @kbd{pmake}       # NetBSD make
20817 cp ../bar.x bar.y
20818 $ @kbd{rm bar.y}
20819 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20820 cp bar.x bar.y
20821 cp: cannot stat `bar.x': No such file or directory
20822 *** Error code 1
20823 $ @kbd{tmake}       # Tru64 make
20824 cp ../bar.x bar.y
20825 @end example
20827 It seems the sole solution that would please every @command{make}
20828 implementation is to never rely on @code{VPATH} searches for targets.
20829 In other words, @code{VPATH} should be reserved to unbuilt sources.
20832 @node Single Suffix Rules
20833 @section Single Suffix Rules and Separated Dependencies
20834 @cindex Single Suffix Inference Rule
20835 @cindex Rule, Single Suffix Inference
20836 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
20837 (@samp{.from.to:}), but which @emph{destination} suffix is empty
20838 (@samp{.from:}).
20840 @cindex Separated Dependencies
20841 @dfn{Separated dependencies} simply refers to listing the prerequisite
20842 of a target, without defining a rule.  Usually one can list on the one
20843 hand side, the rules, and on the other hand side, the dependencies.
20845 Solaris @command{make} does not support separated dependencies for
20846 targets defined by single suffix rules:
20848 @example
20849 $ @kbd{cat Makefile}
20850 .SUFFIXES: .in
20851 foo: foo.in
20852 .in:
20853         cp $< $@@
20854 $ @kbd{touch foo.in}
20855 $ @kbd{make}
20856 $ @kbd{ls}
20857 Makefile  foo.in
20858 @end example
20860 @noindent
20861 while GNU Make does:
20863 @example
20864 $ @kbd{gmake}
20865 cp foo.in foo
20866 $ @kbd{ls}
20867 Makefile  foo       foo.in
20868 @end example
20870 Note it works without the @samp{foo: foo.in} dependency.
20872 @example
20873 $ @kbd{cat Makefile}
20874 .SUFFIXES: .in
20875 .in:
20876         cp $< $@@
20877 $ @kbd{make foo}
20878 cp foo.in foo
20879 @end example
20881 @noindent
20882 and it works with double suffix inference rules:
20884 @example
20885 $ @kbd{cat Makefile}
20886 foo.out: foo.in
20887 .SUFFIXES: .in .out
20888 .in.out:
20889         cp $< $@@
20890 $ @kbd{make}
20891 cp foo.in foo.out
20892 @end example
20894 As a result, in such a case, you have to write target rules.
20896 @node Timestamps and Make
20897 @section Timestamp Resolution and Make
20898 @cindex timestamp resolution
20899 Traditionally, file timestamps had 1-second resolution, and
20900 @command{make} used those timestamps to determine whether one file was
20901 newer than the other.  However, many modern file systems have
20902 timestamps with 1-nanosecond resolution.  Some @command{make}
20903 implementations look at the entire timestamp; others ignore the
20904 fractional part, which can lead to incorrect results.  Normally this
20905 is not a problem, but in some extreme cases you may need to use tricks
20906 like @samp{sleep 1} to work around timestamp truncation bugs.
20908 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
20909 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
20910 Tools}).  Hence you should be wary of rules like this:
20912 @example
20913 dest: src
20914         cp -p src dest
20915 @end example
20917 as @file{dest} often appears to be older than @file{src} after the
20918 timestamp is truncated, and this can cause @command{make} to do
20919 needless rework the next time it is invoked.  To work around this
20920 problem, you can use a timestamp file, e.g.:
20922 @example
20923 dest-stamp: src
20924         cp -p src dest
20925         date >dest-stamp
20926 @end example
20928 Apart from timestamp resolution, there are also differences in handling
20929 equal timestamps.  HP-UX @command{make} updates targets if it has the
20930 same time stamp as one of its prerequisites, in violation of Posix rules.
20932 This can cause spurious rebuilds for repeated runs of @command{make}.
20933 This in turn can cause @command{make} to fail if it tries to rebuild
20934 generated files in a possibly read-only source tree with tools not
20935 present on the end-user machine.  Use GNU @command{make} instead.
20939 @c ======================================== Portable C and C++ Programming
20941 @node Portable C and C++
20942 @chapter Portable C and C++ Programming
20943 @cindex Portable C and C++ programming
20945 C and C++ programs often use low-level features of the underlying
20946 system, and therefore are often more difficult to make portable to other
20947 platforms.
20949 Several standards have been developed to help make your programs more
20950 portable.  If you write programs with these standards in mind, you can
20951 have greater confidence that your programs work on a wide variety
20952 of systems.
20953 @ifhtml
20954 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
20955 Standards Supported by GCC}
20956 @end ifhtml
20957 @ifnothtml
20958 @xref{Standards, , Language Standards Supported by
20959 GCC, gcc, Using the GNU Compiler Collection
20960 (GCC)},
20961 @end ifnothtml
20962 for a list of C-related standards.  Many programs also assume the
20963 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
20965 Some old code is written to be portable to K&R C, which predates any C
20966 standard.  K&R C compilers are no longer of practical interest, though,
20967 and the rest of section assumes at least C89, the first C standard.
20969 Program portability is a huge topic, and this section can only briefly
20970 introduce common pitfalls.  @xref{System Portability, , Portability
20971 between System Types, standards, The GNU Coding Standards}, for
20972 more information.
20974 @menu
20975 * Varieties of Unportability::  How to make your programs unportable
20976 * Integer Overflow::            When integers get too large
20977 * Preprocessor Arithmetic::     @code{#if} expression problems
20978 * Null Pointers::               Properties of null pointers
20979 * Buffer Overruns::             Subscript errors and the like
20980 * Volatile Objects::            @code{volatile} and signals
20981 * Floating Point Portability::  Portable floating-point arithmetic
20982 * Exiting Portably::            Exiting and the exit status
20983 @end menu
20985 @node Varieties of Unportability
20986 @section Varieties of Unportability
20987 @cindex portability
20989 Autoconf tests and ordinary programs often need to test what is allowed
20990 on a system, and therefore they may need to deliberately exceed the
20991 boundaries of what the standards allow, if only to see whether an
20992 optional feature is present.  When you write such a program, you should
20993 keep in mind the difference between constraints, unspecified behavior,
20994 and undefined behavior.
20996 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
20997 example constraint is that C programs must not declare a bit-field with
20998 negative width.  Tests can therefore reliably assume that programs with
20999 negative-width bit-fields are rejected by a compiler that conforms
21000 to the standard.
21002 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21003 multiple possibilities.  For example, the order of evaluation of
21004 function arguments is unspecified.  Some unspecified behavior is
21005 @dfn{implementation-defined}, i.e., documented by the implementation,
21006 but since Autoconf tests cannot read the documentation they cannot
21007 distinguish between implementation-defined and other unspecified
21008 behavior.  It is common for Autoconf tests to probe implementations to
21009 determine otherwise-unspecified behavior.
21011 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21012 the implementation to do anything it pleases.  For example,
21013 dereferencing a null pointer leads to undefined behavior.  If possible,
21014 test programs should avoid undefined behavior, since a program with
21015 undefined behavior might succeed on a test that should fail.
21017 The above rules apply to programs that are intended to conform to the
21018 standard.  However, strictly-conforming programs are quite rare, since
21019 the standards are so limiting.  A major goal of Autoconf is to support
21020 programs that use implementation features not described by the standard,
21021 and it is fairly common for test programs to violate the above rules, if
21022 the programs work well enough in practice.
21024 @node Integer Overflow
21025 @section Integer Overflow
21026 @cindex integer overflow
21027 @cindex overflow, signed integer
21028 @cindex signed integer overflow
21029 @cindex wraparound arithmetic
21031 In practice many portable C programs assume that signed integer overflow wraps
21032 around reliably using two's complement arithmetic.  Yet the C standard
21033 says that program behavior is undefined on overflow, and in a few cases
21034 C programs do not work on some modern implementations because their
21035 overflows do not wrap around as their authors expected.  Conversely, in
21036 signed integer remainder, the C standard requires overflow
21037 behavior that is commonly not implemented.
21039 @menu
21040 * Integer Overflow Basics::     Why integer overflow is a problem
21041 * Signed Overflow Examples::    Examples of code assuming wraparound
21042 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21043 * Signed Overflow Advice::      Practical advice for signed overflow issues
21044 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21045 @end menu
21047 @node Integer Overflow Basics
21048 @subsection Basics of Integer Overflow
21049 @cindex integer overflow
21050 @cindex overflow, signed integer
21051 @cindex signed integer overflow
21052 @cindex wraparound arithmetic
21054 In languages like C, unsigned integer overflow reliably wraps around;
21055 e.g., @code{UINT_MAX + 1} yields zero.
21056 This is guaranteed by the C standard and is
21057 portable in practice, unless you specify aggressive,
21058 nonstandard optimization options
21059 suitable only for special applications.
21061 In contrast, the C standard says that signed integer overflow leads to
21062 undefined behavior where a program can do anything, including dumping
21063 core or overrunning a buffer.  The misbehavior can even precede the
21064 overflow.  Such an overflow can occur during addition, subtraction,
21065 multiplication, division, and left shift.
21067 Despite this requirement of the standard, many C programs and Autoconf
21068 tests assume that signed integer overflow silently wraps around modulo a
21069 power of two, using two's complement arithmetic, so long as you cast the
21070 resulting value to a signed integer type or store it into a signed
21071 integer variable.  If you use conservative optimization flags, such
21072 programs are generally portable to the vast majority of modern
21073 platforms, with a few exceptions discussed later.
21075 For historical reasons the C standard also allows implementations with
21076 ones' complement or signed magnitude arithmetic, but it is safe to
21077 assume two's complement nowadays.
21079 Also, overflow can occur when converting an out-of-range value to a
21080 signed integer type.  Here a standard implementation must define what
21081 happens, but this might include raising an exception.  In practice all
21082 known implementations support silent wraparound in this case, so you need
21083 not worry about other possibilities.
21085 @node Signed Overflow Examples
21086 @subsection Examples of Code Assuming Wraparound Overflow
21087 @cindex integer overflow
21088 @cindex overflow, signed integer
21089 @cindex signed integer overflow
21090 @cindex wraparound arithmetic
21092 There has long been a tension between what the C standard requires for
21093 signed integer overflow, and what C programs commonly assume.  The
21094 standard allows aggressive optimizations based on assumptions that
21095 overflow never occurs, but many practical C programs rely on overflow
21096 wrapping around.  These programs do not conform to the standard, but
21097 they commonly work in practice because compiler writers are
21098 understandably reluctant to implement optimizations that would break
21099 many programs, unless perhaps a user specifies aggressive optimization.
21101 The C Standard says that if a program has signed integer overflow its
21102 behavior is undefined, and the undefined behavior can even precede the
21103 overflow.  To take an extreme example:
21105 @c Inspired by Robert Dewar's example in
21106 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21107 @example
21108 if (password == expected_password)
21109   allow_superuser_privileges ();
21110 else if (counter++ == INT_MAX)
21111   abort ();
21112 else
21113   printf ("%d password mismatches\n", counter);
21114 @end example
21116 @noindent
21117 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21118 @code{counter++} must overflow and the behavior is undefined, so the C
21119 standard allows the compiler to optimize away the test against
21120 @code{INT_MAX} and the @code{abort} call.
21121 Worse, if an earlier bug in the program lets the compiler deduce that
21122 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21123 the C standard allows the compiler to optimize away the password test
21124 and generate code that allows superuser privileges unconditionally.
21126 Despite this requirement by the standard, it has long been common for C
21127 code to assume wraparound arithmetic after signed overflow, and all
21128 known practical C implementations support some C idioms that assume
21129 wraparound signed arithmetic, even if the idioms do not conform
21130 strictly to the standard.  If your code looks like the following
21131 examples it will almost surely work with real-world compilers.
21133 Here is an example derived from the 7th Edition Unix implementation of
21134 @code{atoi} (1979-01-10):
21136 @example
21137 char *p;
21138 int f, n;
21139 @dots{}
21140 while (*p >= '0' && *p <= '9')
21141   n = n * 10 + *p++ - '0';
21142 return (f ? -n : n);
21143 @end example
21145 @noindent
21146 Even if the input string is in range, on most modern machines this has
21147 signed overflow when computing the most negative integer (the @code{-n}
21148 overflows) or a value near an extreme integer (the first @code{+}
21149 overflows).
21151 Here is another example, derived from the 7th Edition implementation of
21152 @code{rand} (1979-01-10).  Here the programmer expects both
21153 multiplication and addition to wrap on overflow:
21155 @example
21156 static long int randx = 1;
21157 @dots{}
21158 randx = randx * 1103515245 + 12345;
21159 return (randx >> 16) & 077777;
21160 @end example
21162 In the following example, derived from the GNU C Library 2.5
21163 implementation of @code{mktime} (2006-09-09), the code assumes
21164 wraparound arithmetic in @code{+} to detect signed overflow:
21166 @example
21167 time_t t, t1, t2;
21168 int sec_requested, sec_adjustment;
21169 @dots{}
21170 t1 = t + sec_requested;
21171 t2 = t1 + sec_adjustment;
21172 if (((t1 < t) != (sec_requested < 0))
21173     | ((t2 < t1) != (sec_adjustment < 0)))
21174   return -1;
21175 @end example
21177 If your code looks like these examples, it is probably safe even though
21178 it does not strictly conform to the C standard.  This might lead one to
21179 believe that one can generally assume wraparound on overflow, but that
21180 is not always true, as can be seen in the next section.
21182 @node Optimization and Wraparound
21183 @subsection Optimizations That Break Wraparound Arithmetic
21184 @cindex loop induction
21186 Compilers sometimes generate code that is incompatible with wraparound
21187 integer arithmetic.  A simple example is an algebraic simplification: a
21188 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21189 because it assumes that @code{i * 2000} does not overflow.  The
21190 translation is not equivalent to the original when overflow occurs:
21191 e.g., in the typical case of 32-bit signed two's complement wraparound
21192 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21193 the original expression returns @minus{}2147483 but the optimized
21194 version returns the mathematically correct value 2147484.
21196 More subtly, loop induction optimizations often exploit the undefined
21197 behavior of signed overflow.  Consider the following contrived function
21198 @code{sumc}:
21200 @example
21202 sumc (int lo, int hi)
21204   int sum = 0;
21205   int i;
21206   for (i = lo; i <= hi; i++)
21207     sum ^= i * 53;
21208   return sum;
21210 @end example
21212 @noindent
21213 To avoid multiplying by 53 each time through the loop, an optimizing
21214 compiler might internally transform @code{sumc} to the equivalent of the
21215 following:
21217 @example
21219 transformed_sumc (int lo, int hi)
21221   int sum = 0;
21222   int hic = hi * 53;
21223   int ic;
21224   for (ic = lo * 53; ic <= hic; ic += 53)
21225     sum ^= ic;
21226   return sum;
21228 @end example
21230 @noindent
21231 This transformation is allowed by the C standard, but it is invalid for
21232 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21233 overflow in computing expressions like @code{hi * 53} can cause the
21234 expression @code{i <= hi} to yield a different value from the
21235 transformed expression @code{ic <= hic}.
21237 For this reason, compilers that use loop induction and similar
21238 techniques often do not support reliable wraparound arithmetic when a
21239 loop induction variable like @code{ic} is involved.  Since loop
21240 induction variables are generated by the compiler, and are not visible
21241 in the source code, it is not always trivial to say whether the problem
21242 affects your code.
21244 Hardly any code actually depends on wraparound arithmetic in cases like
21245 these, so in practice these loop induction optimizations are almost
21246 always useful.  However, edge cases in this area can cause problems.
21247 For example:
21249 @example
21250 int j;
21251 for (j = 1; 0 < j; j *= 2)
21252   test (j);
21253 @end example
21255 @noindent
21256 Here, the loop attempts to iterate through all powers of 2 that
21257 @code{int} can represent, but the C standard allows a compiler to
21258 optimize away the comparison and generate an infinite loop,
21259 under the argument that behavior is undefined on overflow.  As of this
21260 writing this optimization is not done by any production version of
21261 GCC with @option{-O2}, but it might be performed by other
21262 compilers, or by more aggressive GCC optimization options,
21263 and the GCC developers have not decided whether it will
21264 continue to work with GCC and @option{-O2}.
21266 @node Signed Overflow Advice
21267 @subsection Practical Advice for Signed Overflow Issues
21268 @cindex integer overflow
21269 @cindex overflow, signed integer
21270 @cindex signed integer overflow
21271 @cindex wraparound arithmetic
21273 Ideally the safest approach is to avoid signed integer overflow
21274 entirely.  For example, instead of multiplying two signed integers, you
21275 can convert them to unsigned integers, multiply the unsigned values,
21276 then test whether the result is in signed range.
21278 Rewriting code in this way will be inconvenient, though, particularly if
21279 the signed values might be negative.  Also, it may hurt
21280 performance.  Using unsigned arithmetic to check for overflow is
21281 particularly painful to do portably and efficiently when dealing with an
21282 integer type like @code{uid_t} whose width and signedness vary from
21283 platform to platform.
21285 Furthermore, many C applications pervasively assume wraparound behavior
21286 and typically it is not easy to find and remove all these assumptions.
21287 Hence it is often useful to maintain nonstandard code that assumes
21288 wraparound on overflow, instead of rewriting the code.  The rest of this
21289 section attempts to give practical advice for this situation.
21291 If your code wants to detect signed integer overflow in @code{sum = a +
21292 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21293 < 0)}.
21295 If your code uses a signed loop index, make sure that the index cannot
21296 overflow, along with all signed expressions derived from the index.
21297 Here is a contrived example of problematic code with two instances of
21298 overflow.
21300 @example
21301 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21302   if (i + 1 < 0)
21303     @{
21304       report_overflow ();
21305       break;
21306     @}
21307 @end example
21309 @noindent
21310 Because of the two overflows, a compiler might optimize away or
21311 transform the two comparisons in a way that is incompatible with the
21312 wraparound assumption.
21314 If your code uses an expression like @code{(i * 2000) / 1000} and you
21315 actually want the multiplication to wrap around on overflow, use
21316 unsigned arithmetic
21317 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21319 If your code assumes wraparound behavior and you want to insulate it
21320 against any GCC optimizations that would fail to support that
21321 behavior, you should use GCC's @option{-fwrapv} option, which
21322 causes signed overflow to wrap around reliably (except for division and
21323 remainder, as discussed in the next section).
21325 If you need to port to platforms where signed integer overflow does not
21326 reliably wrap around (e.g., due to hardware overflow checking, or to
21327 highly aggressive optimizations), you should consider debugging with
21328 GCC's @option{-ftrapv} option, which causes signed overflow to
21329 raise an exception.
21331 @node Signed Integer Division
21332 @subsection Signed Integer Division and Integer Overflow
21333 @cindex division, integer
21335 Overflow in signed
21336 integer division is not always harmless: for example, on CPUs of the
21337 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21338 which by default terminates the program.  Worse, taking the remainder
21339 of these two values typically yields the same signal on these CPUs,
21340 even though the C standard requires @code{INT_MIN % -1} to yield zero
21341 because the expression does not overflow.
21343 @node Preprocessor Arithmetic
21344 @section Preprocessor Arithmetic
21345 @cindex preprocessor arithmetic
21347 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
21348 be evaluated as if all signed values are of type @code{intmax_t} and all
21349 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21350 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21351 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21352 @code{long long int}.  Also, some older preprocessors mishandle
21353 constants ending in @code{LL}.  To work around these problems, you can
21354 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21355 @code{configure}-time rather than at @code{#if}-time.
21357 @node Null Pointers
21358 @section Properties of Null Pointers
21359 @cindex null pointers
21361 Most modern hosts reliably fail when you attempt to dereference a null
21362 pointer.
21364 On almost all modern hosts, null pointers use an all-bits-zero internal
21365 representation, so you can reliably use @code{memset} with 0 to set all
21366 the pointers in an array to null values.
21368 If @code{p} is a null pointer to an object type, the C expression
21369 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21370 the standard says that it has undefined behavior.
21372 @node Buffer Overruns
21373 @section Buffer Overruns and Subscript Errors
21374 @cindex buffer overruns
21376 Buffer overruns and subscript errors are the most common dangerous
21377 errors in C programs.  They result in undefined behavior because storing
21378 outside an array typically modifies storage that is used by some other
21379 object, and most modern systems lack runtime checks to catch these
21380 errors.  Programs should not rely on buffer overruns being caught.
21382 There is one exception to the usual rule that a portable program cannot
21383 address outside an array.  In C, it is valid to compute the address just
21384 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21385 so long as you do not dereference the resulting pointer.  But it is not
21386 valid to compute the address just before an object, e.g., @code{&a[-1]};
21387 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21388 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21389 reliable in general, and it is usually easy enough to avoid the
21390 potential portability problem, e.g., by allocating an extra unused array
21391 element at the start or end.
21393 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21395 users might also consider using the @option{-fmudflap} option to catch
21396 overruns.
21398 Buffer overruns are usually caused by off-by-one errors, but there are
21399 more subtle ways to get them.
21401 Using @code{int} values to index into an array or compute array sizes
21402 causes problems on typical 64-bit hosts where an array index might
21403 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21404 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21405 are signed, and are wide enough in practice.
21407 If you add or multiply two numbers to calculate an array size, e.g.,
21408 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21409 multiplication overflows.
21411 Many implementations of the @code{alloca} function silently misbehave
21412 and can generate buffer overflows if given sizes that are too large.
21413 The size limits are implementation dependent, but are at least 4000
21414 bytes on all platforms that we know about.
21416 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21417 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21418 portable code should not use them unless the inputs are known to be
21419 within certain limits.  The time-related functions can overflow their
21420 buffers if given timestamps out of range (e.g., a year less than -999
21421 or greater than 9999).  Time-related buffer overflows cannot happen with
21422 recent-enough versions of the GNU C library, but are possible
21423 with other
21424 implementations.  The @code{gets} function is the worst, since it almost
21425 invariably overflows its buffer when presented with an input line larger
21426 than the buffer.
21428 @node Volatile Objects
21429 @section Volatile Objects
21430 @cindex volatile objects
21432 The keyword @code{volatile} is often misunderstood in portable code.
21433 Its use inhibits some memory-access optimizations, but programmers often
21434 wish that it had a different meaning than it actually does.
21436 @code{volatile} was designed for code that accesses special objects like
21437 memory-mapped device registers whose contents spontaneously change.
21438 Such code is inherently low-level, and it is difficult to specify
21439 portably what @code{volatile} means in these cases.  The C standard
21440 says, ``What constitutes an access to an object that has
21441 volatile-qualified type is implementation-defined,'' so in theory each
21442 implementation is supposed to fill in the gap by documenting what
21443 @code{volatile} means for that implementation.  In practice, though,
21444 this documentation is usually absent or incomplete.
21446 One area of confusion is the distinction between objects defined with
21447 volatile types, and volatile lvalues.  From the C standard's point of
21448 view, an object defined with a volatile type has externally visible
21449 behavior.  You can think of such objects as having little oscilloscope
21450 probes attached to them, so that the user can observe some properties of
21451 accesses to them, just as the user can observe data written to output
21452 files.  However, the standard does not make it clear whether users can
21453 observe accesses by volatile lvalues to ordinary objects.  For example:
21455 @example
21456 /* Declare and access a volatile object.
21457    Accesses to X are "visible" to users.  */
21458 static int volatile x;
21459 x = 1;
21461 /* Access two ordinary objects via a volatile lvalue.
21462    It's not clear whether accesses to *P are "visible".  */
21463 int y;
21464 int *z = malloc (sizeof (int));
21465 int volatile *p;
21466 p = &y;
21467 *p = 1;
21468 p = z;
21469 *p = 1;
21470 @end example
21472 Programmers often wish that @code{volatile} meant ``Perform the memory
21473 access here and now, without merging several memory accesses, without
21474 changing the memory word size, and without reordering.''  But the C
21475 standard does not require this.  For objects defined with a volatile
21476 type, accesses must be done before the next sequence point; but
21477 otherwise merging, reordering, and word-size change is allowed.  Worse,
21478 it is not clear from the standard whether volatile lvalues provide more
21479 guarantees in general than nonvolatile lvalues, if the underlying
21480 objects are ordinary.
21482 Even when accessing objects defined with a volatile type,
21483 the C standard allows only
21484 extremely limited signal handlers: the behavior is undefined if a signal
21485 handler reads any nonlocal object, or writes to any nonlocal object
21486 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21487 library function other than @code{abort}, @code{signal}, and (if C99)
21488 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21489 disturbing ordinary computation, unless the computation accesses a
21490 @code{sig_atomic_t volatile} lvalue that is not a local variable.
21491 (There is an obscure exception for accesses via a pointer to a volatile
21492 character, since it may point into part of a @code{sig_atomic_t
21493 volatile} object.)  Posix
21494 adds to the list of library functions callable from a portable signal
21495 handler, but otherwise is like the C standard in this area.
21497 Some C implementations allow memory-access optimizations within each
21498 translation unit, such that actual behavior agrees with the behavior
21499 required by the standard only when calling a function in some other
21500 translation unit, and a signal handler acts like it was called from a
21501 different translation unit.  The C standard hints that in these
21502 implementations, objects referred to by signal handlers ``would require
21503 explicit specification of @code{volatile} storage, as well as other
21504 implementation-defined restrictions.''  But unfortunately even for this
21505 special case these other restrictions are often not documented well.
21506 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21507 GNU Compiler Collection (GCC)}, for some
21508 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21509 Defining Signal Handlers, libc, The GNU C Library}, for some
21510 restrictions imposed by the GNU C library.  Restrictions
21511 differ on other platforms.
21513 If possible, it is best to use a signal handler that fits within the
21514 limits imposed by the C and Posix standards.
21516 If this is not practical, you can try the following rules of thumb.  A
21517 signal handler should access only volatile lvalues, preferably lvalues
21518 that refer to objects defined with a volatile type, and should not
21519 assume that the accessed objects have an internally consistent state
21520 if they are larger than a machine word.  Furthermore, installers
21521 should employ compilers and compiler options that are commonly used
21522 for building operating system kernels, because kernels often need more
21523 from @code{volatile} than the C Standard requires, and installers who
21524 compile an application in a similar environment can sometimes benefit
21525 from the extra constraints imposed by kernels on compilers.
21526 Admittedly we are handwaving somewhat here, as there are few
21527 guarantees in this area; the rules of thumb may help to fix some bugs
21528 but there is a good chance that they will not fix them all.
21530 For @code{volatile}, C++ has the same problems that C does.
21531 Multithreaded applications have even more problems with @code{volatile},
21532 but they are beyond the scope of this section.
21534 The bottom line is that using @code{volatile} typically hurts
21535 performance but should not hurt correctness.  In some cases its use
21536 does help correctness, but these cases are often so poorly understood
21537 that all too often adding @code{volatile} to a data structure merely
21538 alleviates some symptoms of a bug while not fixing the bug in general.
21540 @node Floating Point Portability
21541 @section Floating Point Portability
21542 @cindex floating point
21544 Almost all modern systems use IEEE-754 floating point, and it is safe to
21545 assume IEEE-754 in most portable code these days.  For more information,
21546 please see David Goldberg's classic paper
21547 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21548 Scientist Should Know About Floating-Point Arithmetic}.
21550 @node Exiting Portably
21551 @section Exiting Portably
21552 @cindex exiting portably
21554 A C or C++ program can exit with status @var{N} by returning
21555 @var{N} from the @code{main} function.  Portable programs are supposed
21556 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21557 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21558 fail by exiting with status 1, and test programs that assume Posix can
21559 fail by exiting with status values from 1 through 255.  Programs on
21560 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21561 status when @code{main} returned nonzero, but ancient systems like these
21562 are no longer of practical concern.
21564 A program can also exit with status @var{N} by passing @var{N} to the
21565 @code{exit} function, and a program can fail by calling the @code{abort}
21566 function.  If a program is specialized to just some platforms, it can fail
21567 by calling functions specific to those platforms, e.g., @code{_exit}
21568 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
21569 function should be declared, typically by including a header.  For
21570 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21571 either directly or via the default includes (@pxref{Default Includes}).
21573 A program can fail due to undefined behavior such as dereferencing a null
21574 pointer, but this is not recommended as undefined behavior allows an
21575 implementation to do whatever it pleases and this includes exiting
21576 successfully.
21579 @c ================================================== Manual Configuration
21581 @node Manual Configuration
21582 @chapter Manual Configuration
21584 A few kinds of features can't be guessed automatically by running test
21585 programs.  For example, the details of the object-file format, or
21586 special options that need to be passed to the compiler or linker.  You
21587 can check for such features using ad-hoc means, such as having
21588 @command{configure} check the output of the @code{uname} program, or
21589 looking for libraries that are unique to particular systems.  However,
21590 Autoconf provides a uniform method for handling unguessable features.
21592 @menu
21593 * Specifying Target Triplets::  Specifying target triplets
21594 * Canonicalizing::              Getting the canonical system type
21595 * Using System Type::           What to do with the system type
21596 @end menu
21598 @node Specifying Target Triplets
21599 @section Specifying target triplets
21600 @cindex System type
21601 @cindex Target triplet
21602 @c This node used to be named Specifying Names.  The @anchor allows old
21603 @c links to still work.
21604 @anchor{Specifying Names}
21606 Autoconf-generated
21607 @command{configure} scripts can make decisions based on a canonical name
21608 for the system type, or @dfn{target triplet}, which has the form:
21609 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21610 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21612 @command{configure} can usually guess the canonical name for the type of
21613 system it's running on.  To do so it runs a script called
21614 @command{config.guess}, which infers the name using the @code{uname}
21615 command or symbols predefined by the C preprocessor.
21617 Alternately, the user can specify the system type with command line
21618 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21619 necessary when
21620 cross-compiling.  In the most complex case of cross-compiling, three
21621 system types are involved.  The options to specify them are:
21623 @table @option
21624 @item --build=@var{build-type}
21625 the type of system on which the package is being configured and
21626 compiled.  It defaults to the result of running @command{config.guess}.
21628 @item --host=@var{host-type}
21629 the type of system on which the package runs.  By default it is the
21630 same as the build machine.  Specifying it enables the cross-compilation
21631 mode.
21633 @item --target=@var{target-type}
21634 the type of system for which any compiler tools in the package
21635 produce code (rarely needed).  By default, it is the same as host.
21636 @end table
21638 If you mean to override the result of @command{config.guess}, use
21639 @option{--build}, not @option{--host}, since the latter enables
21640 cross-compilation.  For historical reasons,
21641 whenever you specify @option{--host},
21642 be sure to specify @option{--build} too; this will be fixed in the
21643 future.  So, to enter cross-compilation mode, use a command like this
21645 @example
21646 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21647 @end example
21649 @noindent
21650 Note that if you do not specify @option{--host}, @command{configure}
21651 fails if it can't run the code generated by the specified compiler.  For
21652 example, configuring as follows fails:
21654 @example
21655 ./configure CC=m68k-coff-gcc
21656 @end example
21658 When cross-compiling, @command{configure} will warn about any tools
21659 (compilers, linkers, assemblers) whose name is not prefixed with the
21660 host type.  This is an aid to users performing cross-compilation.
21661 Continuing the example above, if a cross-compiler named @command{cc} is
21662 used with a native @command{pkg-config}, then libraries found by
21663 @command{pkg-config} will likely cause subtle build failures; but using
21664 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21665 avoids any confusion.  Avoiding the warning is as simple as creating the
21666 correct symlinks naming the cross tools.
21668 @cindex @command{config.sub}
21669 @command{configure} recognizes short aliases for many system types; for
21670 example, @samp{decstation} can be used instead of
21671 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21672 @command{config.sub} to canonicalize system type aliases.
21674 This section deliberately omits the description of the obsolete
21675 interface; see @ref{Hosts and Cross-Compilation}.
21678 @node Canonicalizing
21679 @section Getting the Canonical System Type
21680 @cindex System type
21681 @cindex Canonical system type
21683 The following macros make the system type available to @command{configure}
21684 scripts.
21686 @ovindex build_alias
21687 @ovindex host_alias
21688 @ovindex target_alias
21690 The variables @samp{build_alias}, @samp{host_alias}, and
21691 @samp{target_alias} are always exactly the arguments of @option{--build},
21692 @option{--host}, and @option{--target}; in particular, they are left empty
21693 if the user did not use them, even if the corresponding
21694 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21695 variables anywhere.  These are the variables that should be used when in
21696 interaction with the user.
21698 If you need to recognize some special environments based on their system
21699 type, run the following macros to get canonical system names.  These
21700 variables are not set before the macro call.
21702 If you use these macros, you must distribute @command{config.guess} and
21703 @command{config.sub} along with your source code.  @xref{Output}, for
21704 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21705 to control in which directory @command{configure} looks for those scripts.
21708 @defmac AC_CANONICAL_BUILD
21709 @acindex{CANONICAL_BUILD}
21710 @ovindex build
21711 @ovindex build_cpu
21712 @ovindex build_vendor
21713 @ovindex build_os
21714 Compute the canonical build-system type variable, @code{build}, and its
21715 three individual parts @code{build_cpu}, @code{build_vendor}, and
21716 @code{build_os}.
21718 If @option{--build} was specified, then @code{build} is the
21719 canonicalization of @code{build_alias} by @command{config.sub},
21720 otherwise it is determined by the shell script @command{config.guess}.
21721 @end defmac
21723 @defmac AC_CANONICAL_HOST
21724 @acindex{CANONICAL_HOST}
21725 @ovindex host
21726 @ovindex host_cpu
21727 @ovindex host_vendor
21728 @ovindex host_os
21729 Compute the canonical host-system type variable, @code{host}, and its
21730 three individual parts @code{host_cpu}, @code{host_vendor}, and
21731 @code{host_os}.
21733 If @option{--host} was specified, then @code{host} is the
21734 canonicalization of @code{host_alias} by @command{config.sub},
21735 otherwise it defaults to @code{build}.
21736 @end defmac
21738 @defmac AC_CANONICAL_TARGET
21739 @acindex{CANONICAL_TARGET}
21740 @ovindex target
21741 @ovindex target_cpu
21742 @ovindex target_vendor
21743 @ovindex target_os
21744 Compute the canonical target-system type variable, @code{target}, and its
21745 three individual parts @code{target_cpu}, @code{target_vendor}, and
21746 @code{target_os}.
21748 If @option{--target} was specified, then @code{target} is the
21749 canonicalization of @code{target_alias} by @command{config.sub},
21750 otherwise it defaults to @code{host}.
21751 @end defmac
21753 Note that there can be artifacts due to the backward compatibility
21754 code.  @xref{Hosts and Cross-Compilation}, for more.
21756 @node Using System Type
21757 @section Using the System Type
21759 In @file{configure.ac} the system type is generally used by one or more
21760 @code{case} statements to select system-specifics.  Shell wildcards can
21761 be used to match a group of system types.
21763 For example, an extra assembler code object file could be chosen, giving
21764 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
21765 following would be used in a makefile to add the object to a
21766 program or library.
21768 @example
21769 AS_CASE([$host],
21770   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
21771   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
21772   [CYCLE_OBJ=""]
21774 AC_SUBST([CYCLE_OBJ])
21775 @end example
21777 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
21778 to select variant source files, for example optimized code for some
21779 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
21780 so some runtime capability checks may be necessary too.
21782 @example
21783 case $host in
21784   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
21785   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
21786   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
21787 esac
21788 @end example
21790 The host system type can also be used to find cross-compilation tools
21791 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
21793 The above examples all show @samp{$host}, since this is where the code
21794 is going to run.  Only rarely is it necessary to test @samp{$build}
21795 (which is where the build is being done).
21797 Whenever you're tempted to use @samp{$host} it's worth considering
21798 whether some sort of probe would be better.  New system types come along
21799 periodically or previously missing features are added.  Well-written
21800 probes can adapt themselves to such things, but hard-coded lists of
21801 names can't.  Here are some guidelines,
21803 @itemize @bullet
21804 @item
21805 Availability of libraries and library functions should always be checked
21806 by probing.
21807 @item
21808 Variant behavior of system calls is best identified with runtime tests
21809 if possible, but bug workarounds or obscure difficulties might have to
21810 be driven from @samp{$host}.
21811 @item
21812 Assembler code is inevitably highly CPU-specific and is best selected
21813 according to @samp{$host_cpu}.
21814 @item
21815 Assembler variations like underscore prefix on globals or ELF versus
21816 COFF type directives are however best determined by probing, perhaps
21817 even examining the compiler output.
21818 @end itemize
21820 @samp{$target} is for use by a package creating a compiler or similar.
21821 For ordinary packages it's meaningless and should not be used.  It
21822 indicates what the created compiler should generate code for, if it can
21823 cross-compile.  @samp{$target} generally selects various hard-coded CPU
21824 and system conventions, since usually the compiler or tools under
21825 construction themselves determine how the target works.
21828 @c ===================================================== Site Configuration.
21830 @node Site Configuration
21831 @chapter Site Configuration
21833 @command{configure} scripts support several kinds of local configuration
21834 decisions.  There are ways for users to specify where external software
21835 packages are, include or exclude optional features, install programs
21836 under modified names, and set default values for @command{configure}
21837 options.
21839 @menu
21840 * Help Formatting::             Customizing @samp{configure --help}
21841 * External Software::           Working with other optional software
21842 * Package Options::             Selecting optional features
21843 * Pretty Help Strings::         Formatting help string
21844 * Option Checking::             Controlling checking of @command{configure} options
21845 * Site Details::                Configuring site details
21846 * Transforming Names::          Changing program names when installing
21847 * Site Defaults::               Giving @command{configure} local defaults
21848 @end menu
21850 @node Help Formatting
21851 @section Controlling Help Output
21853 Users consult @samp{configure --help} to learn of configuration
21854 decisions specific to your package.  By default, @command{configure}
21855 breaks this output into sections for each type of option; within each
21856 section, help strings appear in the order @file{configure.ac} defines
21857 them:
21859 @example
21860 Optional Features:
21861   @dots{}
21862   --enable-bar            include bar
21864 Optional Packages:
21865   @dots{}
21866   --with-foo              use foo
21867 @end example
21869 @defmac AC_PRESERVE_HELP_ORDER
21870 @acindex{PRESERVE_HELP_ORDER}
21872 Request an alternate @option{--help} format, in which options of all
21873 types appear together, in the order defined.  Call this macro before any
21874 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
21876 @example
21877 Optional Features and Packages:
21878   @dots{}
21879   --enable-bar            include bar
21880   --with-foo              use foo
21881 @end example
21883 @end defmac
21885 @node External Software
21886 @section Working With External Software
21887 @cindex External software
21889 Some packages require, or can optionally use, other software packages
21890 that are already installed.  The user can give @command{configure}
21891 command line options to specify which such external software to use.
21892 The options have one of these forms:
21894 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21895 @c awful.
21896 @example
21897 --with-@var{package}@r{[}=@var{arg}@r{]}
21898 --without-@var{package}
21899 @end example
21901 For example, @option{--with-gnu-ld} means work with the GNU linker
21902 instead of some other linker.  @option{--with-x} means work with The X
21903 Window System.
21905 The user can give an argument by following the package name with
21906 @samp{=} and the argument.  Giving an argument of @samp{no} is for
21907 packages that are used by default; it says to @emph{not} use the
21908 package.  An argument that is neither @samp{yes} nor @samp{no} could
21909 include a name or number of a version of the other package, to specify
21910 more precisely which other package this program is supposed to work
21911 with.  If no argument is given, it defaults to @samp{yes}.
21912 @option{--without-@var{package}} is equivalent to
21913 @option{--with-@var{package}=no}.
21915 Normally @command{configure} scripts complain about
21916 @option{--with-@var{package}} options that they do not support.
21917 @xref{Option Checking}, for details, and for how to override the
21918 defaults.
21920 For each external software package that may be used, @file{configure.ac}
21921 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
21922 user asked to use it.  Whether each package is used or not by default,
21923 and which arguments are valid, is up to you.
21925 @anchor{AC_ARG_WITH}
21926 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
21927   @ovar{action-if-given}, @ovar{action-if-not-given})
21928 @acindex{ARG_WITH}
21929 If the user gave @command{configure} the option @option{--with-@var{package}}
21930 or @option{--without-@var{package}}, run shell commands
21931 @var{action-if-given}.  If neither option was given, run shell commands
21932 @var{action-if-not-given}.  The name @var{package} indicates another
21933 software package that this program should work with.  It should consist
21934 only of alphanumeric characters, dashes, plus signs, and dots.
21936 The option's argument is available to the shell commands
21937 @var{action-if-given} in the shell variable @code{withval}, which is
21938 actually just the value of the shell variable named
21939 @code{with_@var{package}}, with any non-alphanumeric characters in
21940 @var{package} changed into @samp{_}.  You may use that variable instead,
21941 if you wish.
21943 The argument @var{help-string} is a description of the option that
21944 looks like this:
21945 @example
21946   --with-readline         support fancy command line editing
21947 @end example
21949 @noindent
21950 @var{help-string} may be more than one line long, if more detail is
21951 needed.  Just make sure the columns line up in @samp{configure
21952 --help}.  Avoid tabs in the help string.  The easiest way to provide the
21953 proper leading whitespace is to format your @var{help-string} with the macro
21954 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21956 The following example shows how to use the @code{AC_ARG_WITH} macro in
21957 a common situation.  You want to let the user decide whether to enable
21958 support for an external library (e.g., the readline library); if the user
21959 specified neither @option{--with-readline} nor @option{--without-readline},
21960 you want to enable support for readline only if the library is available
21961 on the system.
21963 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21964 @example
21965 AC_ARG_WITH([readline],
21966   [AS_HELP_STRING([--with-readline],
21967     [support fancy command line editing @@<:@@default=check@@:>@@])],
21968   [],
21969   [with_readline=check])
21971 LIBREADLINE=
21972 AS_IF([test "x$with_readline" != xno],
21973   [AC_CHECK_LIB([readline], [main],
21974     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21975      AC_DEFINE([HAVE_LIBREADLINE], [1],
21976                [Define if you have libreadline])
21977     ],
21978     [if test "x$with_readline" != xcheck; then
21979        AC_MSG_FAILURE(
21980          [--with-readline was given, but test for readline failed])
21981      fi
21982     ], -lncurses)])
21983 @end example
21985 The next example shows how to use @code{AC_ARG_WITH} to give the user the
21986 possibility to enable support for the readline library, in case it is still
21987 experimental and not well tested, and is therefore disabled by default.
21989 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21990 @example
21991 AC_ARG_WITH([readline],
21992   [AS_HELP_STRING([--with-readline],
21993     [enable experimental support for readline])],
21994   [],
21995   [with_readline=no])
21997 LIBREADLINE=
21998 AS_IF([test "x$with_readline" != xno],
21999   [AC_CHECK_LIB([readline], [main],
22000     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22001      AC_DEFINE([HAVE_LIBREADLINE], [1],
22002                [Define if you have libreadline])
22003     ],
22004     [AC_MSG_FAILURE(
22005        [--with-readline was given, but test for readline failed])],
22006     [-lncurses])])
22007 @end example
22009 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22010 possibility to disable support for the readline library, given that it is
22011 an important feature and that it should be enabled by default.
22013 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22014 @example
22015 AC_ARG_WITH([readline],
22016   [AS_HELP_STRING([--without-readline],
22017     [disable support for readline])],
22018   [],
22019   [with_readline=yes])
22021 LIBREADLINE=
22022 AS_IF([test "x$with_readline" != xno],
22023   [AC_CHECK_LIB([readline], [main],
22024     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22025      AC_DEFINE([HAVE_LIBREADLINE], [1],
22026                [Define if you have libreadline])
22027     ],
22028     [AC_MSG_FAILURE(
22029        [readline test failed (--without-readline to disable)])],
22030     [-lncurses])])
22031 @end example
22033 These three examples can be easily adapted to the case where
22034 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22035 @ref{Package Options}).
22036 @end defmac
22038 @node Package Options
22039 @section Choosing Package Options
22040 @cindex Package options
22041 @cindex Options, package
22043 If a software package has optional compile-time features, the user can
22044 give @command{configure} command line options to specify whether to
22045 compile them.  The options have one of these forms:
22047 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22048 @c awful.
22049 @example
22050 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22051 --disable-@var{feature}
22052 @end example
22054 These options allow users to choose which optional features to build and
22055 install.  @option{--enable-@var{feature}} options should never make a
22056 feature behave differently or cause one feature to replace another.
22057 They should only cause parts of the program to be built rather than left
22058 out.
22060 The user can give an argument by following the feature name with
22061 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22062 that the feature @emph{not} be made available.  A feature with an
22063 argument looks like @option{--enable-debug=stabs}.  If no argument is
22064 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22065 equivalent to @option{--enable-@var{feature}=no}.
22067 Normally @command{configure} scripts complain about
22068 @option{--enable-@var{package}} options that they do not support.
22069 @xref{Option Checking}, for details, and for how to override the
22070 defaults.
22072 For each optional feature, @file{configure.ac} should call
22073 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22074 to include it.  Whether each feature is included or not by default, and
22075 which arguments are valid, is up to you.
22077 @anchor{AC_ARG_ENABLE}
22078 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22079   @ovar{action-if-given}, @ovar{action-if-not-given})
22080 @acindex{ARG_ENABLE}
22081 If the user gave @command{configure} the option
22082 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22083 shell commands @var{action-if-given}.  If neither option was given, run
22084 shell commands @var{action-if-not-given}.  The name @var{feature}
22085 indicates an optional user-level facility.  It should consist only of
22086 alphanumeric characters, dashes, plus signs, and dots.
22088 The option's argument is available to the shell commands
22089 @var{action-if-given} in the shell variable @code{enableval}, which is
22090 actually just the value of the shell variable named
22091 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22092 @var{feature} changed into @samp{_}.  You may use that variable instead,
22093 if you wish.  The @var{help-string} argument is like that of
22094 @code{AC_ARG_WITH} (@pxref{External Software}).
22096 You should format your @var{help-string} with the macro
22097 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22099 See the examples suggested with the definition of @code{AC_ARG_WITH}
22100 (@pxref{External Software}) to get an idea of possible applications of
22101 @code{AC_ARG_ENABLE}.
22102 @end defmac
22104 @node Pretty Help Strings
22105 @section Making Your Help Strings Look Pretty
22106 @cindex Help strings
22108 Properly formatting the @samp{help strings} which are used in
22109 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22110 (@pxref{Package Options}) can be challenging.  Specifically, you want
22111 your own @samp{help strings} to line up in the appropriate columns of
22112 @samp{configure --help} just like the standard Autoconf @samp{help
22113 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22115 @anchor{AS_HELP_STRING}
22116 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22117   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22118 @asindex{HELP_STRING}
22120 Expands into a help string that looks pretty when the user executes
22121 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22122 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22123 Options}).  The following example makes this clearer.
22125 @example
22126 AC_ARG_WITH([foo],
22127   [AS_HELP_STRING([--with-foo],
22128      [use foo (default is no)])],
22129   [use_foo=$withval],
22130   [use_foo=no])
22131 @end example
22133 Then the last few lines of @samp{configure --help} appear like
22134 this:
22136 @example
22137 --enable and --with options recognized:
22138   --with-foo              use foo (default is no)
22139 @end example
22141 Macro expansion is performed on the first argument.  However, the second
22142 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22143 list of text to be reformatted, and is not subject to macro expansion.
22144 Since it is not expanded, it should not be double quoted.
22145 @xref{Autoconf Language}, for a more detailed explanation.
22147 The @code{AS_HELP_STRING} macro is particularly helpful when the
22148 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22149 arguments, as shown in the following example.  Be aware that
22150 @var{left-hand-side} may not expand to unbalanced quotes,
22151 although quadrigraphs can be used.
22153 @example
22154 AC_DEFUN([MY_ARG_WITH],
22155   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22156      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22157                      [use $1 (default is $2)])],
22158      [use_[]$1=$withval],
22159      [use_[]$1=$2])])
22160 MY_ARG_WITH([a_b], [no])
22161 @end example
22162 @noindent
22163 Here, the last few lines of @samp{configure --help} will include:
22165 @example
22166 --enable and --with options recognized:
22167   --with-a-b              use a_b (default is no)
22168 @end example
22170 The parameters @var{indent-column} and @var{wrap-column} were introduced
22171 in Autoconf 2.62.  Generally, they should not be specified; they exist
22172 for fine-tuning of the wrapping.
22173 @example
22174 AS_HELP_STRING([--option], [description of option])
22175 @result{}  --option                description of option
22176 AS_HELP_STRING([--option], [description of option], [15], [30])
22177 @result{}  --option     description of
22178 @result{}               option
22179 @end example
22180 @end defmac
22183 @node Option Checking
22184 @section Controlling Checking of @command{configure} Options
22185 @cindex Options, Package
22187 The @command{configure} script checks its command-line options against a
22188 list of known options, like @option{--help} or @option{--config-cache}.
22189 An unknown option ordinarily indicates a mistake by the user and
22190 @command{configure} halts with an error.  However, by default unknown
22191 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22192 options elicit only a warning, to support configuring entire source
22193 trees.
22195 Source trees often contain multiple packages with a top-level
22196 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22197 (@pxref{Subdirectories}).  Because the packages generally support
22198 different @option{--with-@var{package}} and
22199 @option{--enable-@var{feature}} options, the GNU Coding
22200 Standards say they must accept unrecognized options without halting.
22201 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22202 automatically disables the warnings.
22204 This default behavior may be modified in two ways.  First, the installer
22205 can invoke @code{configure --disable-option-checking} to disable
22206 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22207 options to turn them into fatal errors, respectively.  Second, the
22208 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22210 @defmac AC_DISABLE_OPTION_CHECKING
22211 @acindex{DISABLE_OPTION_CHECKING}
22213 By default, disable warnings related to any unrecognized
22214 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22215 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22217 The installer can override this behavior by passing
22218 @option{--enable-option-checking} (enable warnings) or
22219 @option{--enable-option-checking=fatal} (enable errors) to
22220 @command{configure}.
22221 @end defmac
22224 @node Site Details
22225 @section Configuring Site Details
22226 @cindex Site details
22228 Some software packages require complex site-specific information.  Some
22229 examples are host names to use for certain services, company names, and
22230 email addresses to contact.  Since some configuration scripts generated
22231 by Metaconfig ask for such information interactively, people sometimes
22232 wonder how to get that information in Autoconf-generated configuration
22233 scripts, which aren't interactive.
22235 Such site configuration information should be put in a file that is
22236 edited @emph{only by users}, not by programs.  The location of the file
22237 can either be based on the @code{prefix} variable, or be a standard
22238 location such as the user's home directory.  It could even be specified
22239 by an environment variable.  The programs should examine that file at
22240 runtime, rather than at compile time.  Runtime configuration is more
22241 convenient for users and makes the configuration process simpler than
22242 getting the information while configuring.  @xref{Directory Variables, ,
22243 Variables for Installation Directories, standards, The GNU Coding
22244 Standards}, for more information on where to put data files.
22246 @node Transforming Names
22247 @section Transforming Program Names When Installing
22248 @cindex Transforming program names
22249 @cindex Program names, transforming
22251 Autoconf supports changing the names of programs when installing them.
22252 In order to use these transformations, @file{configure.ac} must call the
22253 macro @code{AC_ARG_PROGRAM}.
22255 @defmac AC_ARG_PROGRAM
22256 @acindex{ARG_PROGRAM}
22257 @ovindex program_transform_name
22258 Place in output variable @code{program_transform_name} a sequence of
22259 @code{sed} commands for changing the names of installed programs.
22261 If any of the options described below are given to @command{configure},
22262 program names are transformed accordingly.  Otherwise, if
22263 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22264 is given, the target type followed by a dash is used as a prefix.
22265 Otherwise, no program name transformation is done.
22266 @end defmac
22268 @menu
22269 * Transformation Options::      @command{configure} options to transform names
22270 * Transformation Examples::     Sample uses of transforming names
22271 * Transformation Rules::        Makefile uses of transforming names
22272 @end menu
22274 @node Transformation Options
22275 @subsection Transformation Options
22277 You can specify name transformations by giving @command{configure} these
22278 command line options:
22280 @table @option
22281 @item --program-prefix=@var{prefix}
22282 prepend @var{prefix} to the names;
22284 @item --program-suffix=@var{suffix}
22285 append @var{suffix} to the names;
22287 @item --program-transform-name=@var{expression}
22288 perform @code{sed} substitution @var{expression} on the names.
22289 @end table
22291 @node Transformation Examples
22292 @subsection Transformation Examples
22294 These transformations are useful with programs that can be part of a
22295 cross-compilation development environment.  For example, a
22296 cross-assembler running on a Sun 4 configured with
22297 @option{--target=i960-vxworks} is normally installed as
22298 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22299 with a native Sun 4 assembler.
22301 You can force a program name to begin with @file{g}, if you don't want
22302 GNU programs installed on your system to shadow other programs with
22303 the same name.  For example, if you configure GNU @code{diff} with
22304 @option{--program-prefix=g}, then when you run @samp{make install} it is
22305 installed as @file{/usr/local/bin/gdiff}.
22307 As a more sophisticated example, you could use
22309 @example
22310 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22311 @end example
22312 @noindent
22314 to prepend @samp{g} to most of the program names in a source tree,
22315 excepting those like @code{gdb} that already have one and those like
22316 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22317 assuming that you have a source tree containing those programs that is
22318 set up to use this feature.)
22320 One way to install multiple versions of some programs simultaneously is
22321 to append a version number to the name of one or both.  For example, if
22322 you want to keep Autoconf version 1 around for awhile, you can configure
22323 Autoconf version 2 using @option{--program-suffix=2} to install the
22324 programs as @file{/usr/local/bin/autoconf2},
22325 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22326 that only the binaries are renamed, therefore you'd have problems with
22327 the library files which might overlap.
22329 @node Transformation Rules
22330 @subsection Transformation Rules
22332 Here is how to use the variable @code{program_transform_name} in a
22333 @file{Makefile.in}:
22335 @example
22336 PROGRAMS = cp ls rm
22337 transform = @@program_transform_name@@
22338 install:
22339         for p in $(PROGRAMS); do \
22340           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22341                                               sed '$(transform)'`; \
22342         done
22344 uninstall:
22345         for p in $(PROGRAMS); do \
22346           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22347 @c $$ restore font-lock
22348         done
22349 @end example
22351 It is guaranteed that @code{program_transform_name} is never empty, and
22352 that there are no useless separators.  Therefore you may safely embed
22353 @code{program_transform_name} within a sed program using @samp{;}:
22355 @example
22356 transform = @@program_transform_name@@
22357 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22358 @end example
22360 Whether to do the transformations on documentation files (Texinfo or
22361 @code{man}) is a tricky question; there seems to be no perfect answer,
22362 due to the several reasons for name transforming.  Documentation is not
22363 usually particular to a specific architecture, and Texinfo files do not
22364 conflict with system documentation.  But they might conflict with
22365 earlier versions of the same files, and @code{man} pages sometimes do
22366 conflict with system documentation.  As a compromise, it is probably
22367 best to do name transformations on @code{man} pages but not on Texinfo
22368 manuals.
22370 @node Site Defaults
22371 @section Setting Site Defaults
22372 @cindex Site defaults
22373 @cindex config.site
22375 Autoconf-generated @command{configure} scripts allow your site to provide
22376 default values for some configuration values.  You do this by creating
22377 site- and system-wide initialization files.
22379 @evindex CONFIG_SITE
22380 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22381 uses its value as the name of a shell script to read; it is recommended
22382 that this be an absolute file name.  Otherwise, it
22383 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22384 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22385 settings in machine-specific files override those in machine-independent
22386 ones in case of conflict.
22388 Site files can be arbitrary shell scripts, but only certain kinds of
22389 code are really appropriate to be in them.  Because @command{configure}
22390 reads any cache file after it has read any site files, a site file can
22391 define a default cache file to be shared between all Autoconf-generated
22392 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22393 you set a default cache file in a site file, it is a good idea to also
22394 set the output variable @code{CC} in that site file, because the cache
22395 file is only valid for a particular compiler, but many systems have
22396 several available.
22398 You can examine or override the value set by a command line option to
22399 @command{configure} in a site file; options set shell variables that have
22400 the same names as the options, with any dashes turned into underscores.
22401 The exceptions are that @option{--without-} and @option{--disable-} options
22402 are like giving the corresponding @option{--with-} or @option{--enable-}
22403 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22404 sets the variable @code{cache_file} to the value @samp{localcache};
22405 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22406 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22407 variable @code{prefix} to the value @samp{/usr}; etc.
22409 Site files are also good places to set default values for other output
22410 variables, such as @code{CFLAGS}, if you need to give them non-default
22411 values: anything you would normally do, repetitively, on the command
22412 line.  If you use non-default values for @var{prefix} or
22413 @var{exec_prefix} (wherever you locate the site file), you can set them
22414 in the site file if you specify it with the @code{CONFIG_SITE}
22415 environment variable.
22417 You can set some cache values in the site file itself.  Doing this is
22418 useful if you are cross-compiling, where it is impossible to check features
22419 that require running a test program.  You could ``prime the cache'' by
22420 setting those values correctly for that system in
22421 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22422 variables you need to set, see the documentation of the respective
22423 Autoconf macro.  If the variables or their semantics are undocumented,
22424 you may need to look for shell variables with @samp{_cv_} in their names
22425 in the affected @command{configure} scripts, or in the Autoconf M4
22426 source code for those macros; but in that case, their name or semantics
22427 may change in a future Autoconf version.
22429 The cache file is careful to not override any variables set in the site
22430 files.  Similarly, you should not override command-line options in the
22431 site files.  Your code should check that variables such as @code{prefix}
22432 and @code{cache_file} have their default values (as set near the top of
22433 @command{configure}) before changing them.
22435 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22436 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22437 file (if @code{CONFIG_SITE} is not set to a different file).
22439 @example
22440 # /usr/share/local/gnu/share/config.site for configure
22442 # Change some defaults.
22443 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22444 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22445 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22446 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22448 # Give Autoconf 2.x generated configure scripts a shared default
22449 # cache file for feature test results, architecture-specific.
22450 if test "$cache_file" = /dev/null; then
22451   cache_file="$prefix/var/config.cache"
22452   # A cache file is only valid for one C compiler.
22453   CC=gcc
22455 @end example
22457 @cindex Filesystem Hierarchy Standard
22458 @cindex FHS
22460 Another use of @file{config.site} is for priming the directory variables
22461 in a manner consistent with the Filesystem Hierarchy Standard
22462 (FHS).  Once the following file is installed at
22463 @file{/usr/share/config.site}, a user can execute simply
22464 @code{./configure --prefix=/usr} to get all the directories chosen in
22465 the locations recommended by FHS.
22467 @example
22468 # /usr/share/config.site for FHS defaults when installing below /usr,
22469 # and the respective settings were not changed on the command line.
22470 if test "$prefix" = /usr; then
22471   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22472   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22473   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22475 @end example
22477 @cindex @file{lib64}
22478 @cindex 64-bit libraries
22479 Likewise, on platforms where 64-bit libraries are built by default, then
22480 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22481 it is appropriate to install @file{/usr/local/@/share/config.site}:
22483 @example
22484 # /usr/local/share/config.site for platforms that prefer
22485 # the directory /usr/local/lib64 over /usr/local/lib.
22486 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22487 @end example
22490 @c ============================================== Running configure Scripts.
22492 @node Running configure Scripts
22493 @chapter Running @command{configure} Scripts
22494 @cindex @command{configure}
22496 Below are instructions on how to configure a package that uses a
22497 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22498 file in the package.  A plain-text version of @file{INSTALL} which you
22499 may use comes with Autoconf.
22501 @menu
22502 * Basic Installation::          Instructions for typical cases
22503 * Compilers and Options::       Selecting compilers and optimization
22504 * Multiple Architectures::      Compiling for multiple architectures at once
22505 * Installation Names::          Installing in different directories
22506 * Optional Features::           Selecting optional features
22507 * Particular Systems::          Particular systems
22508 * System Type::                 Specifying the system type
22509 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22510 * Defining Variables::          Specifying the compiler etc.
22511 * configure Invocation::        Changing how @command{configure} runs
22512 @end menu
22514 @set autoconf
22515 @include install.texi
22518 @c ============================================== config.status Invocation
22520 @node config.status Invocation
22521 @chapter config.status Invocation
22522 @cindex @command{config.status}
22524 The @command{configure} script creates a file named @file{config.status},
22525 which actually configures, @dfn{instantiates}, the template files.  It
22526 also records the configuration options that were specified when the
22527 package was last configured in case reconfiguring is needed.
22529 Synopsis:
22530 @example
22531 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22532 @end example
22534 It configures each @var{tag}; if none are specified, all the templates
22535 are instantiated.  A @var{tag} refers to a file or other tag associated
22536 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22537 macro (@pxref{Configuration Actions}).  The files must be specified
22538 without their dependencies, as in
22540 @example
22541 ./config.status foobar
22542 @end example
22544 @noindent
22547 @example
22548 ./config.status foobar:foo.in:bar.in
22549 @end example
22551 The supported options are:
22553 @table @option
22554 @item --help
22555 @itemx -h
22556 Print a summary of the command line options, the list of the template
22557 files, and exit.
22559 @item --version
22560 @itemx -V
22561 Print the version number of Autoconf and the configuration settings,
22562 and exit.
22564 @item --config
22565 Print the configuration settings in reusable way, quoted for the shell,
22566 and exit.  For example, for a debugging build that otherwise reuses the
22567 configuration from a different build directory @var{build-dir} of a
22568 package in @var{src-dir}, you could use the following:
22570 @example
22571 args=`@var{build-dir}/config.status --config`
22572 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22573 @end example
22575 @noindent
22576 Note that it may be necessary to override a @option{--srcdir} setting
22577 that was saved in the configuration, if the arguments are used in a
22578 different build directory.
22580 @item --silent
22581 @itemx --quiet
22582 @itemx -q
22583 Do not print progress messages.
22585 @item --debug
22586 @itemx -d
22587 Don't remove the temporary files.
22589 @item --file=@var{file}[:@var{template}]
22590 Require that @var{file} be instantiated as if
22591 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22592 @var{file} and @var{template} may be @samp{-} in which case the standard
22593 output and/or standard input, respectively, is used.  If a
22594 @var{template} file name is relative, it is first looked for in the build
22595 tree, and then in the source tree.  @xref{Configuration Actions}, for
22596 more details.
22598 This option and the following ones provide one way for separately
22599 distributed packages to share the values computed by @command{configure}.
22600 Doing so can be useful if some of the packages need a superset of the
22601 features that one of them, perhaps a common library, does.  These
22602 options allow a @file{config.status} file to create files other than the
22603 ones that its @file{configure.ac} specifies, so it can be used for a
22604 different package, or for extracting a subset of values.  For example,
22606 @example
22607 echo '@@CC@@' | ./config.status --file=-
22608 @end example
22610 @noindent
22611 provides the value of @code{@@CC@@} on standard output.
22613 @item --header=@var{file}[:@var{template}]
22614 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22616 @item --recheck
22617 Ask @file{config.status} to update itself and exit (no instantiation).
22618 This option is useful if you change @command{configure}, so that the
22619 results of some tests might be different from the previous run.  The
22620 @option{--recheck} option reruns @command{configure} with the same arguments
22621 you used before, plus the @option{--no-create} option, which prevents
22622 @command{configure} from running @file{config.status} and creating
22623 @file{Makefile} and other files, and the @option{--no-recursion} option,
22624 which prevents @command{configure} from running other @command{configure}
22625 scripts in subdirectories.  (This is so other Make rules can
22626 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22627 for an example).
22628 @end table
22630 @file{config.status} checks several optional environment variables that
22631 can alter its behavior:
22633 @anchor{CONFIG_SHELL}
22634 @defvar CONFIG_SHELL
22635 @evindex CONFIG_SHELL
22636 The shell with which to run @command{configure} for the @option{--recheck}
22637 option.  It must be Bourne-compatible.  The default is a shell that
22638 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
22639 Invoking @command{configure} by hand bypasses this setting, so you may
22640 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
22641 to insure that the same shell is used everywhere.  The absolute name of the
22642 shell should be passed.
22643 @end defvar
22645 @defvar CONFIG_STATUS
22646 @evindex CONFIG_STATUS
22647 The file name to use for the shell script that records the
22648 configuration.  The default is @file{./config.status}.  This variable is
22649 useful when one package uses parts of another and the @command{configure}
22650 scripts shouldn't be merged because they are maintained separately.
22651 @end defvar
22653 You can use @file{./config.status} in your makefiles.  For example, in
22654 the dependencies given above (@pxref{Automatic Remaking}),
22655 @file{config.status} is run twice when @file{configure.ac} has changed.
22656 If that bothers you, you can make each run only regenerate the files for
22657 that rule:
22658 @example
22659 @group
22660 config.h: stamp-h
22661 stamp-h: config.h.in config.status
22662         ./config.status config.h
22663         echo > stamp-h
22665 Makefile: Makefile.in config.status
22666         ./config.status Makefile
22667 @end group
22668 @end example
22670 The calling convention of @file{config.status} has changed; see
22671 @ref{Obsolete config.status Use}, for details.
22674 @c =================================================== Obsolete Constructs
22676 @node Obsolete Constructs
22677 @chapter Obsolete Constructs
22678 @cindex Obsolete constructs
22680 Autoconf changes, and throughout the years some constructs have been
22681 obsoleted.  Most of the changes involve the macros, but in some cases
22682 the tools themselves, or even some concepts, are now considered
22683 obsolete.
22685 You may completely skip this chapter if you are new to Autoconf.  Its
22686 intention is mainly to help maintainers updating their packages by
22687 understanding how to move to more modern constructs.
22689 @menu
22690 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
22691 * acconfig Header::             Additional entries in @file{config.h.in}
22692 * autoupdate Invocation::       Automatic update of @file{configure.ac}
22693 * Obsolete Macros::             Backward compatibility macros
22694 * Autoconf 1::                  Tips for upgrading your files
22695 * Autoconf 2.13::               Some fresher tips
22696 @end menu
22698 @node Obsolete config.status Use
22699 @section Obsolete @file{config.status} Invocation
22701 @file{config.status} now supports arguments to specify the files to
22702 instantiate; see @ref{config.status Invocation}, for more details.
22703 Before, environment variables had to be used.
22705 @defvar CONFIG_COMMANDS
22706 @evindex CONFIG_COMMANDS
22707 The tags of the commands to execute.  The default is the arguments given
22708 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
22709 @file{configure.ac}.
22710 @end defvar
22712 @defvar CONFIG_FILES
22713 @evindex CONFIG_FILES
22714 The files in which to perform @samp{@@@var{variable}@@} substitutions.
22715 The default is the arguments given to @code{AC_OUTPUT} and
22716 @code{AC_CONFIG_FILES} in @file{configure.ac}.
22717 @end defvar
22719 @defvar CONFIG_HEADERS
22720 @evindex CONFIG_HEADERS
22721 The files in which to substitute C @code{#define} statements.  The
22722 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
22723 macro was not called, @file{config.status} ignores this variable.
22724 @end defvar
22726 @defvar CONFIG_LINKS
22727 @evindex CONFIG_LINKS
22728 The symbolic links to establish.  The default is the arguments given to
22729 @code{AC_CONFIG_LINKS}; if that macro was not called,
22730 @file{config.status} ignores this variable.
22731 @end defvar
22733 In @ref{config.status Invocation}, using this old interface, the example
22734 would be:
22736 @example
22737 @group
22738 config.h: stamp-h
22739 stamp-h: config.h.in config.status
22740         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
22741           CONFIG_HEADERS=config.h ./config.status
22742         echo > stamp-h
22744 Makefile: Makefile.in config.status
22745         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
22746           CONFIG_FILES=Makefile ./config.status
22747 @end group
22748 @end example
22750 @noindent
22751 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
22752 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
22753 for @code{CONFIG_COMMANDS}, etc.)
22756 @node acconfig Header
22757 @section @file{acconfig.h}
22759 @cindex @file{acconfig.h}
22760 @cindex @file{config.h.top}
22761 @cindex @file{config.h.bot}
22763 In order to produce @file{config.h.in}, @command{autoheader} needs to
22764 build or to find templates for each symbol.  Modern releases of Autoconf
22765 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
22766 Macros}), but in older releases a file, @file{acconfig.h}, contained the
22767 list of needed templates.  @command{autoheader} copied comments and
22768 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
22769 the current directory, if present.  This file used to be mandatory if
22770 you @code{AC_DEFINE} any additional symbols.
22772 Modern releases of Autoconf also provide @code{AH_TOP} and
22773 @code{AH_BOTTOM} if you need to prepend/append some information to
22774 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
22775 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
22776 @command{autoheader} copies the lines before the line containing
22777 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
22778 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
22779 @command{autoheader} copies the lines after that line to the end of the
22780 file it generates.  Either or both of those strings may be omitted.  An
22781 even older alternate way to produce the same effect in ancient versions
22782 of Autoconf is to create the files @file{@var{file}.top} (typically
22783 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
22784 directory.  If they exist, @command{autoheader} copies them to the
22785 beginning and end, respectively, of its output.
22787 In former versions of Autoconf, the files used in preparing a software
22788 package for distribution were:
22789 @example
22790 @group
22791 configure.ac --.   .------> autoconf* -----> configure
22792                +---+
22793 [aclocal.m4] --+   `---.
22794 [acsite.m4] ---'       |
22795                        +--> [autoheader*] -> [config.h.in]
22796 [acconfig.h] ----.     |
22797                  +-----'
22798 [config.h.top] --+
22799 [config.h.bot] --'
22800 @end group
22801 @end example
22803 Using only the @code{AH_} macros, @file{configure.ac} should be
22804 self-contained, and should not depend upon @file{acconfig.h} etc.
22807 @node autoupdate Invocation
22808 @section Using @command{autoupdate} to Modernize @file{configure.ac}
22809 @cindex @command{autoupdate}
22811 The @command{autoupdate} program updates a @file{configure.ac} file that
22812 calls Autoconf macros by their old names to use the current macro names.
22813 In version 2 of Autoconf, most of the macros were renamed to use a more
22814 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
22815 description of the new scheme.  Although the old names still work
22816 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
22817 new names), you can make your @file{configure.ac} files more readable
22818 and make it easier to use the current Autoconf documentation if you
22819 update them to use the new macro names.
22821 @evindex SIMPLE_BACKUP_SUFFIX
22822 If given no arguments, @command{autoupdate} updates @file{configure.ac},
22823 backing up the original version with the suffix @file{~} (or the value
22824 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
22825 set).  If you give @command{autoupdate} an argument, it reads that file
22826 instead of @file{configure.ac} and writes the updated file to the
22827 standard output.
22829 @noindent
22830 @command{autoupdate} accepts the following options:
22832 @table @option
22833 @item --help
22834 @itemx -h
22835 Print a summary of the command line options and exit.
22837 @item --version
22838 @itemx -V
22839 Print the version number of Autoconf and exit.
22841 @item --verbose
22842 @itemx -v
22843 Report processing steps.
22845 @item --debug
22846 @itemx -d
22847 Don't remove the temporary files.
22849 @item --force
22850 @itemx -f
22851 Force the update even if the file has not changed.  Disregard the cache.
22853 @item --include=@var{dir}
22854 @itemx -I @var{dir}
22855 Also look for input files in @var{dir}.  Multiple invocations accumulate.
22856 Directories are browsed from last to first.
22858 @item --prepend-include=@var{dir}
22859 @itemx -B @var{dir}
22860 Prepend directory @var{dir} to the search path.  This is used to include
22861 the language-specific files before any third-party macros.
22862 @end table
22864 @node Obsolete Macros
22865 @section Obsolete Macros
22867 Several macros are obsoleted in Autoconf, for various reasons (typically
22868 they failed to quote properly, couldn't be extended for more recent
22869 issues, etc.).  They are still supported, but deprecated: their use
22870 should be avoided.
22872 During the jump from Autoconf version 1 to version 2, most of the
22873 macros were renamed to use a more uniform and descriptive naming scheme,
22874 but their signature did not change.  @xref{Macro Names}, for a
22875 description of the new naming scheme.  Below, if there is just the mapping
22876 from old names to new names for these macros, the reader is invited to
22877 refer to the definition of the new macro for the signature and the
22878 description.
22880 @defmac AC_AIX
22881 @acindex{AIX}
22882 @cvindex _ALL_SOURCE
22883 This macro is a platform-specific subset of
22884 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22885 @end defmac
22887 @defmac AC_ALLOCA
22888 @acindex{ALLOCA}
22889 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
22890 @end defmac
22892 @defmac AC_ARG_ARRAY
22893 @acindex{ARG_ARRAY}
22894 Removed because of limited usefulness.
22895 @end defmac
22897 @defmac AC_C_CROSS
22898 @acindex{C_CROSS}
22899 This macro is obsolete; it does nothing.
22900 @end defmac
22902 @defmac AC_C_LONG_DOUBLE
22903 @acindex{C_LONG_DOUBLE}
22904 @cvindex HAVE_LONG_DOUBLE
22905 If the C compiler supports a working @code{long double} type with more
22906 range or precision than the @code{double} type, define
22907 @code{HAVE_LONG_DOUBLE}.
22909 You should use @code{AC_TYPE_LONG_DOUBLE} or
22910 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22911 @end defmac
22913 @defmac AC_CANONICAL_SYSTEM
22914 @acindex{CANONICAL_SYSTEM}
22915 Determine the system type and set output variables to the names of the
22916 canonical system types.  @xref{Canonicalizing}, for details about the
22917 variables this macro sets.
22919 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
22920 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
22921 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
22922 other macros (@pxref{Canonicalizing}).
22923 @end defmac
22925 @defmac AC_CHAR_UNSIGNED
22926 @acindex{CHAR_UNSIGNED}
22927 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
22928 @end defmac
22930 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
22931 @acindex{CHECK_TYPE}
22932 Autoconf, up to 2.13, used to provide this version of
22933 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
22934 it is a member of the @code{CHECK} clan, it does
22935 more than just checking.  Secondly, missing types are defined
22936 using @code{#define}, not @code{typedef}, and this can lead to
22937 problems in the case of pointer types.
22939 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
22940 @ref{Generic Types}, for the description of the current macro.
22942 If the type @var{type} is not defined, define it to be the C (or C++)
22943 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
22945 This macro is equivalent to:
22947 @example
22948 AC_CHECK_TYPE([@var{type}], [],
22949   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
22950      [Define to `@var{default}'
22951       if <sys/types.h> does not define.])])
22952 @end example
22954 In order to keep backward compatibility, the two versions of
22955 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
22957 @enumerate
22958 @item
22959 If there are three or four arguments, the modern version is used.
22961 @item
22962 If the second argument appears to be a C or C++ type, then the
22963 obsolete version is used.  This happens if the argument is a C or C++
22964 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
22965 followed by one of @samp{[(* } and then by a string of zero or more
22966 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
22968 @item
22969 If the second argument is spelled with the alphabet of valid C and C++
22970 types, the user is warned and the modern version is used.
22972 @item
22973 Otherwise, the modern version is used.
22974 @end enumerate
22976 @noindent
22977 You are encouraged either to use a valid builtin type, or to use the
22978 equivalent modern code (see above), or better yet, to use
22979 @code{AC_CHECK_TYPES} together with
22981 @example
22982 #ifndef HAVE_LOFF_T
22983 typedef loff_t off_t;
22984 #endif
22985 @end example
22986 @end defmac
22987 @c end of AC_CHECK_TYPE
22989 @defmac AC_CHECKING (@var{feature-description})
22990 @acindex{CHECKING}
22991 Same as
22993 @example
22994 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
22995 @end example
22997 @noindent
22998 @xref{AC_MSG_NOTICE}.
22999 @end defmac
23001 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23002   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23003 @acindex{COMPILE_CHECK}
23004 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23005 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23006 addition that it prints @samp{checking for @var{echo-text}} to the
23007 standard output first, if @var{echo-text} is non-empty.  Use
23008 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23009 messages (@pxref{Printing Messages}).
23010 @end defmac
23012 @defmac AC_CONST
23013 @acindex{CONST}
23014 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23015 @end defmac
23017 @defmac AC_CROSS_CHECK
23018 @acindex{CROSS_CHECK}
23019 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23020 @code{:-)}.
23021 @end defmac
23023 @defmac AC_CYGWIN
23024 @acindex{CYGWIN}
23025 @evindex CYGWIN
23026 Check for the Cygwin environment in which case the shell variable
23027 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23028 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23029 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23031 @example
23032 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23033 case $host_os in
23034   *cygwin* ) CYGWIN=yes;;
23035          * ) CYGWIN=no;;
23036 esac
23037 @end example
23039 Beware that the variable @env{CYGWIN} has a special meaning when
23040 running Cygwin, and should not be changed.  That's yet another reason
23041 not to use this macro.
23042 @end defmac
23044 @defmac AC_DECL_SYS_SIGLIST
23045 @acindex{DECL_SYS_SIGLIST}
23046 @cvindex SYS_SIGLIST_DECLARED
23047 Same as:
23049 @example
23050 AC_CHECK_DECLS([sys_siglist], [], [],
23051 [#include <signal.h>
23052 /* NetBSD declares sys_siglist in unistd.h.  */
23053 #ifdef HAVE_UNISTD_H
23054 # include <unistd.h>
23055 #endif
23057 @end example
23059 @noindent
23060 @xref{AC_CHECK_DECLS}.
23061 @end defmac
23063 @defmac AC_DECL_YYTEXT
23064 @acindex{DECL_YYTEXT}
23065 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23066 @end defmac
23068 @defmac AC_DIR_HEADER
23069 @acindex{DIR_HEADER}
23070 @cvindex DIRENT
23071 @cvindex SYSNDIR
23072 @cvindex SYSDIR
23073 @cvindex NDIR
23074 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23075 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23076 (@pxref{AC_HEADER_DIRENT}),
23077 but defines a different set of C preprocessor macros to indicate which
23078 header file is found:
23080 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23081 @item Header            @tab Old Symbol     @tab New Symbol
23082 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23083 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23084 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23085 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23086 @end multitable
23087 @end defmac
23089 @defmac AC_DYNIX_SEQ
23090 @acindex{DYNIX_SEQ}
23091 If on DYNIX/ptx, add @option{-lseq} to output variable
23092 @code{LIBS}.  This macro used to be defined as
23094 @example
23095 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23096 @end example
23098 @noindent
23099 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23100 @end defmac
23102 @defmac AC_EXEEXT
23103 @acindex{EXEEXT}
23104 @ovindex EXEEXT
23105 Defined the output variable @code{EXEEXT} based on the output of the
23106 compiler, which is now done automatically.  Typically set to empty
23107 string if Posix and @samp{.exe} if a DOS variant.
23108 @end defmac
23110 @defmac AC_EMXOS2
23111 @acindex{EMXOS2}
23112 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23113 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23114 check the nature of the host is using @code{AC_CANONICAL_HOST}
23115 (@pxref{Canonicalizing}).
23116 @end defmac
23118 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23119   @ovar{action-if-not-given})
23120 @acindex{ENABLE}
23121 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23122 support providing a help string (@pxref{AC_ARG_ENABLE}).
23123 @end defmac
23125 @defmac AC_ERROR
23126 @acindex{ERROR}
23127 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23128 @end defmac
23130 @defmac AC_FIND_X
23131 @acindex{FIND_X}
23132 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23133 @end defmac
23135 @defmac AC_FIND_XTRA
23136 @acindex{FIND_XTRA}
23137 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23138 @end defmac
23140 @defmac AC_FOREACH
23141 @acindex{FOREACH}
23142 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23143 @end defmac
23145 @defmac AC_FUNC_CHECK
23146 @acindex{FUNC_CHECK}
23147 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23148 @end defmac
23150 @anchor{AC_FUNC_SETVBUF_REVERSED}
23151 @defmac AC_FUNC_SETVBUF_REVERSED
23152 @acindex{FUNC_SETVBUF_REVERSED}
23153 @cvindex SETVBUF_REVERSED
23154 @c @fuindex setvbuf
23155 @prindex @code{setvbuf}
23156 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23157 the buffering type as its second argument and the buffer pointer as the
23158 third, instead of the other way around, and defined
23159 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23160 were those based on SVR2, which became obsolete in 1987, and the macro
23161 is no longer needed.
23162 @end defmac
23164 @defmac AC_FUNC_WAIT3
23165 @acindex{FUNC_WAIT3}
23166 @cvindex HAVE_WAIT3
23167 @c @fuindex wait3
23168 @prindex @code{wait3}
23169 If @code{wait3} is found and fills in the contents of its third argument
23170 (a @samp{struct rusage *}), which HP-UX does not do, define
23171 @code{HAVE_WAIT3}.
23173 These days portable programs should use @code{waitpid}, not
23174 @code{wait3}, as @code{wait3} has been removed from Posix.
23175 @end defmac
23177 @defmac AC_GCC_TRADITIONAL
23178 @acindex{GCC_TRADITIONAL}
23179 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23180 @end defmac
23182 @defmac AC_GETGROUPS_T
23183 @acindex{GETGROUPS_T}
23184 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23185 @end defmac
23187 @defmac AC_GETLOADAVG
23188 @acindex{GETLOADAVG}
23189 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23190 @end defmac
23192 @defmac AC_GNU_SOURCE
23193 @acindex{GNU_SOURCE}
23194 @cvindex _GNU_SOURCE
23195 This macro is a platform-specific subset of
23196 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23197 @end defmac
23199 @defmac AC_HAVE_FUNCS
23200 @acindex{HAVE_FUNCS}
23201 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23202 @end defmac
23204 @defmac AC_HAVE_HEADERS
23205 @acindex{HAVE_HEADERS}
23206 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23207 @end defmac
23209 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23210   @ovar{action-if-not-found}, @ovar{other-libraries})
23211 @acindex{HAVE_LIBRARY}
23212 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23213 @var{function} argument of @code{main}.  In addition, @var{library} can
23214 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23215 all of those cases, the compiler is passed @option{-lfoo}.  However,
23216 @var{library} cannot be a shell variable; it must be a literal name.
23217 @xref{AC_CHECK_LIB}.
23218 @end defmac
23220 @defmac AC_HAVE_POUNDBANG
23221 @acindex{HAVE_POUNDBANG}
23222 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23223 @end defmac
23225 @defmac AC_HEADER_CHECK
23226 @acindex{HEADER_CHECK}
23227 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23228 @end defmac
23230 @defmac AC_HEADER_EGREP
23231 @acindex{HEADER_EGREP}
23232 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23233 @end defmac
23235 @defmac AC_HELP_STRING
23236 @acindex{HELP_STRING}
23237 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23238 @end defmac
23240 @defmac AC_INIT (@var{unique-file-in-source-dir})
23241 @acindex{INIT}
23242 Formerly @code{AC_INIT} used to have a single argument, and was
23243 equivalent to:
23245 @example
23246 AC_INIT
23247 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23248 @end example
23249 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23250 @end defmac
23252 @defmac AC_INLINE
23253 @acindex{INLINE}
23254 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23255 @end defmac
23257 @defmac AC_INT_16_BITS
23258 @acindex{INT_16_BITS}
23259 @cvindex INT_16_BITS
23260 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23261 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23262 @end defmac
23264 @defmac AC_IRIX_SUN
23265 @acindex{IRIX_SUN}
23266 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23267 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23268 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23269 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23270 getpwnam)}.  Up to Autoconf 2.13, it used to be
23272 @example
23273 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23274 @end example
23276 @noindent
23277 now it is defined as
23279 @example
23280 AC_FUNC_GETMNTENT
23281 AC_CHECK_LIB([sun], [getpwnam])
23282 @end example
23284 @noindent
23285 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23286 @end defmac
23288 @defmac AC_ISC_POSIX
23289 @acindex{ISC_POSIX}
23290 @ovindex LIBS
23291 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23292 necessary for Posix facilities.  Sun dropped support for the obsolete
23293 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23294 need not use this macro.  It is implemented as
23295 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23296 @end defmac
23298 @defmac AC_LANG_C
23299 @acindex{LANG_C}
23300 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23301 @end defmac
23303 @defmac AC_LANG_CPLUSPLUS
23304 @acindex{LANG_CPLUSPLUS}
23305 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23306 @end defmac
23308 @defmac AC_LANG_FORTRAN77
23309 @acindex{LANG_FORTRAN77}
23310 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23311 @end defmac
23313 @defmac AC_LANG_RESTORE
23314 @acindex{LANG_RESTORE}
23315 Select the @var{language} that is saved on the top of the stack, as set
23316 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23317 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23318 preferred way to change languages.
23319 @end defmac
23321 @defmac AC_LANG_SAVE
23322 @acindex{LANG_SAVE}
23323 Remember the current language (as set by @code{AC_LANG}) on a stack.
23324 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23325 (@pxref{AC_LANG_PUSH}).
23326 @end defmac
23328 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23329 @acindex{LINK_FILES}
23330 This is an obsolete version of @code{AC_CONFIG_LINKS}
23331 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23333 @example
23334 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23335               host.h            object.h)
23336 @end example
23338 @noindent
23341 @example
23342 AC_CONFIG_LINKS([host.h:config/$machine.h
23343                 object.h:config/$obj_format.h])
23344 @end example
23345 @end defmac
23347 @defmac AC_LN_S
23348 @acindex{LN_S}
23349 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23350 @end defmac
23352 @defmac AC_LONG_64_BITS
23353 @acindex{LONG_64_BITS}
23354 @cvindex LONG_64_BITS
23355 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23356 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23357 (@pxref{AC_CHECK_SIZEOF}).
23358 @end defmac
23360 @defmac AC_LONG_DOUBLE
23361 @acindex{LONG_DOUBLE}
23362 If the C compiler supports a working @code{long double} type with more
23363 range or precision than the @code{double} type, define
23364 @code{HAVE_LONG_DOUBLE}.
23366 You should use @code{AC_TYPE_LONG_DOUBLE} or
23367 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23368 @end defmac
23370 @defmac AC_LONG_FILE_NAMES
23371 @acindex{LONG_FILE_NAMES}
23372 Replaced by
23373 @example
23374 AC_SYS_LONG_FILE_NAMES
23375 @end example
23376 @noindent
23377 @xref{AC_SYS_LONG_FILE_NAMES}.
23378 @end defmac
23380 @defmac AC_MAJOR_HEADER
23381 @acindex{MAJOR_HEADER}
23382 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23383 @end defmac
23385 @defmac AC_MEMORY_H
23386 @acindex{MEMORY_H}
23387 @cvindex NEED_MEMORY_H
23388 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23389 defined in @file{memory.h}.  Today it is equivalent to
23390 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23391 your code to depend upon
23392 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
23393 Symbols}.
23394 @end defmac
23396 @defmac AC_MINGW32
23397 @acindex{MINGW32}
23398 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23399 environment and sets @code{MINGW32}.  Don't use this macro, the
23400 dignified means to check the nature of the host is using
23401 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23402 @end defmac
23404 @defmac AC_MINIX
23405 @acindex{MINIX}
23406 @cvindex _MINIX
23407 @cvindex _POSIX_SOURCE
23408 @cvindex _POSIX_1_SOURCE
23409 This macro is a platform-specific subset of
23410 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23411 @end defmac
23413 @defmac AC_MINUS_C_MINUS_O
23414 @acindex{MINUS_C_MINUS_O}
23415 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23416 @end defmac
23418 @defmac AC_MMAP
23419 @acindex{MMAP}
23420 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23421 @end defmac
23423 @defmac AC_MODE_T
23424 @acindex{MODE_T}
23425 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23426 @end defmac
23428 @defmac AC_OBJEXT
23429 @acindex{OBJEXT}
23430 @ovindex OBJEXT
23431 Defined the output variable @code{OBJEXT} based on the output of the
23432 compiler, after .c files have been excluded.  Typically set to @samp{o}
23433 if Posix, @samp{obj} if a DOS variant.
23434 Now the compiler checking macros handle
23435 this automatically.
23436 @end defmac
23438 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23439 @acindex{OBSOLETE}
23440 Make M4 print a message to the standard error output warning that
23441 @var{this-macro-name} is obsolete, and giving the file and line number
23442 where it was called.  @var{this-macro-name} should be the name of the
23443 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23444 it is printed at the end of the warning message; for example, it can be
23445 a suggestion for what to use instead of @var{this-macro-name}.
23447 For instance
23449 @example
23450 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23451 @end example
23453 @noindent
23454 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23455 services to the user (@pxref{AU_DEFUN}).
23456 @end defmac
23458 @defmac AC_OFF_T
23459 @acindex{OFF_T}
23460 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23461 @end defmac
23463 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23464 @acindex{OUTPUT}
23465 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23466 interface is equivalent to:
23468 @example
23469 @group
23470 AC_CONFIG_FILES(@var{file}@dots{})
23471 AC_CONFIG_COMMANDS([default],
23472                    @var{extra-cmds}, @var{init-cmds})
23473 AC_OUTPUT
23474 @end group
23475 @end example
23477 @noindent
23478 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23479 @end defmac
23481 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23482 @acindex{OUTPUT_COMMANDS}
23483 Specify additional shell commands to run at the end of
23484 @file{config.status}, and shell commands to initialize any variables
23485 from @command{configure}.  This macro may be called multiple times.  It is
23486 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23488 Here is an unrealistic example:
23490 @example
23491 fubar=27
23492 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23493                    [fubar=$fubar])
23494 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23495                    [echo init bit])
23496 @end example
23498 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23499 additional key, an important difference is that
23500 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23501 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23502 can safely be given macro calls as arguments:
23504 @example
23505 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23506 @end example
23508 @noindent
23509 Conversely, where one level of quoting was enough for literal strings
23510 with @code{AC_OUTPUT_COMMANDS}, you need two with
23511 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23513 @example
23514 @group
23515 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23516 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23517 @end group
23518 @end example
23519 @end defmac
23521 @defmac AC_PID_T
23522 @acindex{PID_T}
23523 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23524 @end defmac
23526 @defmac AC_PREFIX
23527 @acindex{PREFIX}
23528 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23529 @end defmac
23531 @defmac AC_PROGRAMS_CHECK
23532 @acindex{PROGRAMS_CHECK}
23533 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23534 @end defmac
23536 @defmac AC_PROGRAMS_PATH
23537 @acindex{PROGRAMS_PATH}
23538 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23539 @end defmac
23541 @defmac AC_PROGRAM_CHECK
23542 @acindex{PROGRAM_CHECK}
23543 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23544 @end defmac
23546 @defmac AC_PROGRAM_EGREP
23547 @acindex{PROGRAM_EGREP}
23548 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23549 @end defmac
23551 @defmac AC_PROGRAM_PATH
23552 @acindex{PROGRAM_PATH}
23553 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23554 @end defmac
23556 @defmac AC_REMOTE_TAPE
23557 @acindex{REMOTE_TAPE}
23558 Removed because of limited usefulness.
23559 @end defmac
23561 @defmac AC_RESTARTABLE_SYSCALLS
23562 @acindex{RESTARTABLE_SYSCALLS}
23563 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23564 these days portable programs should use @code{sigaction} with
23565 @code{SA_RESTART} if they want restartable system calls.  They should
23566 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23567 system call is restartable is a dynamic issue, not a configuration-time
23568 issue.
23569 @end defmac
23571 @defmac AC_RETSIGTYPE
23572 @acindex{RETSIGTYPE}
23573 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23574 is obsolete when assuming C89 or better.
23575 @end defmac
23577 @defmac AC_RSH
23578 @acindex{RSH}
23579 Removed because of limited usefulness.
23580 @end defmac
23582 @defmac AC_SCO_INTL
23583 @acindex{SCO_INTL}
23584 @ovindex LIBS
23585 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23586 macro used to do this:
23588 @example
23589 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23590 @end example
23592 @noindent
23593 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23594 @end defmac
23596 @defmac AC_SETVBUF_REVERSED
23597 @acindex{SETVBUF_REVERSED}
23598 Replaced by
23599 @example
23600 AC_FUNC_SETVBUF_REVERSED
23601 @end example
23602 @noindent
23603 @xref{AC_FUNC_SETVBUF_REVERSED}.
23604 @end defmac
23606 @defmac AC_SET_MAKE
23607 @acindex{SET_MAKE}
23608 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23609 @end defmac
23611 @defmac AC_SIZEOF_TYPE
23612 @acindex{SIZEOF_TYPE}
23613 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23614 @end defmac
23616 @defmac AC_SIZE_T
23617 @acindex{SIZE_T}
23618 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23619 @end defmac
23621 @defmac AC_STAT_MACROS_BROKEN
23622 @acindex{STAT_MACROS_BROKEN}
23623 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23624 @end defmac
23626 @defmac AC_STDC_HEADERS
23627 @acindex{STDC_HEADERS}
23628 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
23629 @end defmac
23631 @defmac AC_STRCOLL
23632 @acindex{STRCOLL}
23633 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23634 @end defmac
23636 @defmac AC_STRUCT_ST_BLKSIZE
23637 @acindex{STRUCT_ST_BLKSIZE}
23638 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23639 @cvindex HAVE_ST_BLKSIZE
23640 If @code{struct stat} contains an @code{st_blksize} member, define
23641 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23642 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23643 the future.  This macro is obsoleted, and should be replaced by
23645 @example
23646 AC_CHECK_MEMBERS([struct stat.st_blksize])
23647 @end example
23648 @noindent
23649 @xref{AC_CHECK_MEMBERS}.
23650 @end defmac
23652 @defmac AC_STRUCT_ST_RDEV
23653 @acindex{STRUCT_ST_RDEV}
23654 @cvindex HAVE_ST_RDEV
23655 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23656 If @code{struct stat} contains an @code{st_rdev} member, define
23657 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23658 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23659 in the future.  Actually, even the new macro is obsolete and should be
23660 replaced by:
23661 @example
23662 AC_CHECK_MEMBERS([struct stat.st_rdev])
23663 @end example
23664 @noindent
23665 @xref{AC_CHECK_MEMBERS}.
23666 @end defmac
23668 @defmac AC_ST_BLKSIZE
23669 @acindex{ST_BLKSIZE}
23670 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23671 @end defmac
23673 @defmac AC_ST_BLOCKS
23674 @acindex{ST_BLOCKS}
23675 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
23676 @end defmac
23678 @defmac AC_ST_RDEV
23679 @acindex{ST_RDEV}
23680 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23681 @end defmac
23683 @defmac AC_SYS_RESTARTABLE_SYSCALLS
23684 @acindex{SYS_RESTARTABLE_SYSCALLS}
23685 @cvindex HAVE_RESTARTABLE_SYSCALLS
23686 If the system automatically restarts a system call that is interrupted
23687 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
23688 not check whether system calls are restarted in general---it checks whether a
23689 signal handler installed with @code{signal} (but not @code{sigaction})
23690 causes system calls to be restarted.  It does not check whether system calls
23691 can be restarted when interrupted by signals that have no handler.
23693 These days portable programs should use @code{sigaction} with
23694 @code{SA_RESTART} if they want restartable system calls.  They should
23695 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23696 system call is restartable is a dynamic issue, not a configuration-time
23697 issue.
23698 @end defmac
23700 @defmac AC_SYS_SIGLIST_DECLARED
23701 @acindex{SYS_SIGLIST_DECLARED}
23702 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
23703 name is obsolete, as the same functionality is now acheived via
23704 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
23705 @end defmac
23707 @defmac AC_TEST_CPP
23708 @acindex{TEST_CPP}
23709 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
23710 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
23711 @end defmac
23713 @defmac AC_TEST_PROGRAM
23714 @acindex{TEST_PROGRAM}
23715 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
23716 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
23717 @end defmac
23719 @defmac AC_TIMEZONE
23720 @acindex{TIMEZONE}
23721 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
23722 @end defmac
23724 @defmac AC_TIME_WITH_SYS_TIME
23725 @acindex{TIME_WITH_SYS_TIME}
23726 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
23727 @end defmac
23729 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
23730   @ovar{action-if-true}, @ovar{action-if-false})
23731 @acindex{TRY_COMPILE}
23732 Same as:
23734 @example
23735 AC_COMPILE_IFELSE(
23736   [AC_LANG_PROGRAM([[@var{includes}]],
23737      [[@var{function-body}]])],
23738   [@var{action-if-true}],
23739   [@var{action-if-false}])
23740 @end example
23742 @noindent
23743 @xref{Running the Compiler}.
23745 This macro double quotes both @var{includes} and @var{function-body}.
23747 For C and C++, @var{includes} is any @code{#include} statements needed
23748 by the code in @var{function-body} (@var{includes} is ignored if
23749 the currently selected language is Fortran or Fortran 77).  The compiler
23750 and compilation flags are determined by the current language
23751 (@pxref{Language Choice}).
23752 @end defmac
23754 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
23755 @acindex{TRY_CPP}
23756 Same as:
23758 @example
23759 AC_PREPROC_IFELSE(
23760   [AC_LANG_SOURCE([[@var{input}]])],
23761   [@var{action-if-true}],
23762   [@var{action-if-false}])
23763 @end example
23765 @noindent
23766 @xref{Running the Preprocessor}.
23768 This macro double quotes the @var{input}.
23769 @end defmac
23771 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
23772   @ovar{action-if-true}, @ovar{action-if-false})
23773 @acindex{TRY_LINK}
23774 Same as:
23776 @example
23777 AC_LINK_IFELSE(
23778   [AC_LANG_PROGRAM([[@var{includes}]],
23779      [[@var{function-body}]])],
23780   [@var{action-if-true}],
23781   [@var{action-if-false}])
23782 @end example
23784 @noindent
23785 @xref{Running the Compiler}.
23787 This macro double quotes both @var{includes} and @var{function-body}.
23789 Depending on the current language (@pxref{Language Choice}), create a
23790 test program to see whether a function whose body consists of
23791 @var{function-body} can be compiled and linked.  If the file compiles
23792 and links successfully, run shell commands @var{action-if-found},
23793 otherwise run @var{action-if-not-found}.
23795 This macro double quotes both @var{includes} and @var{function-body}.
23797 For C and C++, @var{includes} is any @code{#include} statements needed
23798 by the code in @var{function-body} (@var{includes} is ignored if
23799 the currently selected language is Fortran or Fortran 77).  The compiler
23800 and compilation flags are determined by the current language
23801 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
23802 @code{LIBS} are used for linking.
23803 @end defmac
23805 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
23806   @ovar{action-if-not-found})
23807 @acindex{TRY_LINK_FUNC}
23808 This macro is equivalent to
23809 @example
23810 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
23811   [@var{action-if-found}], [@var{action-if-not-found}])
23812 @end example
23813 @noindent
23814 @xref{AC_LINK_IFELSE}.
23815 @end defmac
23817 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
23818   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
23819 @acindex{TRY_RUN}
23820 Same as:
23822 @example
23823 AC_RUN_IFELSE(
23824   [AC_LANG_SOURCE([[@var{program}]])],
23825   [@var{action-if-true}],
23826   [@var{action-if-false}],
23827   [@var{action-if-cross-compiling}])
23828 @end example
23830 @noindent
23831 @xref{Runtime}.
23832 @end defmac
23834 @anchor{AC_TYPE_SIGNAL}
23835 @defmac AC_TYPE_SIGNAL
23836 @acindex{TYPE_SIGNAL}
23837 @cvindex RETSIGTYPE
23838 @hdrindex{signal.h}
23839 If @file{signal.h} declares @code{signal} as returning a pointer to a
23840 function returning @code{void}, define @code{RETSIGTYPE} to be
23841 @code{void}; otherwise, define it to be @code{int}.  These days, it is
23842 portable to assume C89, and that signal handlers return @code{void},
23843 without needing to use this macro or @code{RETSIGTYPE}.
23845 When targetting older K&R C, it is possible to define signal handlers as
23846 returning type @code{RETSIGTYPE}, and omit a return statement:
23848 @example
23849 @group
23850 RETSIGTYPE
23851 hup_handler ()
23853 @dots{}
23855 @end group
23856 @end example
23857 @end defmac
23859 @defmac AC_UID_T
23860 @acindex{UID_T}
23861 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23862 @end defmac
23864 @defmac AC_UNISTD_H
23865 @acindex{UNISTD_H}
23866 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
23867 @end defmac
23869 @defmac AC_USG
23870 @acindex{USG}
23871 @cvindex USG
23872 Define @code{USG} if the BSD string functions are defined in
23873 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
23874 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
23875 @end defmac
23877 @defmac AC_UTIME_NULL
23878 @acindex{UTIME_NULL}
23879 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
23880 @end defmac
23882 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
23883 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
23884 If the cache file is inconsistent with the current host, target and
23885 build system types, it used to execute @var{cmd} or print a default
23886 error message.  This is now handled by default.
23887 @end defmac
23889 @defmac AC_VERBOSE (@var{result-description})
23890 @acindex{VERBOSE}
23891 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
23892 @end defmac
23894 @defmac AC_VFORK
23895 @acindex{VFORK}
23896 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
23897 @end defmac
23899 @defmac AC_VPRINTF
23900 @acindex{VPRINTF}
23901 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
23902 @end defmac
23904 @defmac AC_WAIT3
23905 @acindex{WAIT3}
23906 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
23907 portable programs should use @code{waitpid}, not @code{wait3}, as
23908 @code{wait3} has been removed from Posix.
23909 @end defmac
23911 @defmac AC_WARN
23912 @acindex{WARN}
23913 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
23914 @end defmac
23916 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
23917   @ovar{action-if-not-given})
23918 @acindex{WITH}
23919 This is an obsolete version of @code{AC_ARG_WITH} that does not
23920 support providing a help string (@pxref{AC_ARG_WITH}).
23921 @end defmac
23923 @defmac AC_WORDS_BIGENDIAN
23924 @acindex{WORDS_BIGENDIAN}
23925 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
23926 @end defmac
23928 @defmac AC_XENIX_DIR
23929 @acindex{XENIX_DIR}
23930 @ovindex LIBS
23931 This macro used to add @option{-lx} to output variable @code{LIBS} if on
23932 Xenix.  Also, if @file{dirent.h} is being checked for, added
23933 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
23934 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
23935 running XENIX on which you should not depend:
23937 @example
23938 AC_MSG_CHECKING([for Xenix])
23939 AC_EGREP_CPP([yes],
23940 [#if defined M_XENIX && !defined M_UNIX
23941   yes
23942 #endif],
23943              [AC_MSG_RESULT([yes]); XENIX=yes],
23944              [AC_MSG_RESULT([no]); XENIX=])
23945 @end example
23946 @noindent
23947 Don't use this macro, the dignified means to check the nature of the
23948 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23949 @end defmac
23951 @defmac AC_YYTEXT_POINTER
23952 @acindex{YYTEXT_POINTER}
23953 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
23954 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23955 @end defmac
23957 @node Autoconf 1
23958 @section Upgrading From Version 1
23959 @cindex Upgrading autoconf
23960 @cindex Autoconf upgrading
23962 Autoconf version 2 is mostly backward compatible with version 1.
23963 However, it introduces better ways to do some things, and doesn't
23964 support some of the ugly things in version 1.  So, depending on how
23965 sophisticated your @file{configure.ac} files are, you might have to do
23966 some manual work in order to upgrade to version 2.  This chapter points
23967 out some problems to watch for when upgrading.  Also, perhaps your
23968 @command{configure} scripts could benefit from some of the new features in
23969 version 2; the changes are summarized in the file @file{NEWS} in the
23970 Autoconf distribution.
23972 @menu
23973 * Changed File Names::          Files you might rename
23974 * Changed Makefiles::           New things to put in @file{Makefile.in}
23975 * Changed Macros::              Macro calls you might replace
23976 * Changed Results::             Changes in how to check test results
23977 * Changed Macro Writing::       Better ways to write your own macros
23978 @end menu
23980 @node Changed File Names
23981 @subsection Changed File Names
23983 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
23984 in a particular package's source directory), you must rename it to
23985 @file{acsite.m4}.  @xref{autoconf Invocation}.
23987 If you distribute @file{install.sh} with your package, rename it to
23988 @file{install-sh} so @command{make} builtin rules don't inadvertently
23989 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
23990 looks for the script under both names, but it is best to use the new name.
23992 If you were using @file{config.h.top}, @file{config.h.bot}, or
23993 @file{acconfig.h}, you still can, but you have less clutter if you
23994 use the @code{AH_} macros.  @xref{Autoheader Macros}.
23996 @node Changed Makefiles
23997 @subsection Changed Makefiles
23999 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24000 your @file{Makefile.in} files, so they can take advantage of the values
24001 of those variables in the environment when @command{configure} is run.
24002 Doing this isn't necessary, but it's a convenience for users.
24004 Also add @samp{@@configure_input@@} in a comment to each input file for
24005 @code{AC_OUTPUT}, so that the output files contain a comment saying
24006 they were produced by @command{configure}.  Automatically selecting the
24007 right comment syntax for all the kinds of files that people call
24008 @code{AC_OUTPUT} on became too much work.
24010 Add @file{config.log} and @file{config.cache} to the list of files you
24011 remove in @code{distclean} targets.
24013 If you have the following in @file{Makefile.in}:
24015 @example
24016 prefix = /usr/local
24017 exec_prefix = $(prefix)
24018 @end example
24020 @noindent
24021 you must change it to:
24023 @example
24024 prefix = @@prefix@@
24025 exec_prefix = @@exec_prefix@@
24026 @end example
24028 @noindent
24029 The old behavior of replacing those variables without @samp{@@}
24030 characters around them has been removed.
24032 @node Changed Macros
24033 @subsection Changed Macros
24035 Many of the macros were renamed in Autoconf version 2.  You can still
24036 use the old names, but the new ones are clearer, and it's easier to find
24037 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24038 new names for the old macros.  Use the @command{autoupdate} program to
24039 convert your @file{configure.ac} to using the new macro names.
24040 @xref{autoupdate Invocation}.
24042 Some macros have been superseded by similar ones that do the job better,
24043 but are not call-compatible.  If you get warnings about calling obsolete
24044 macros while running @command{autoconf}, you may safely ignore them, but
24045 your @command{configure} script generally works better if you follow
24046 the advice that is printed about what to replace the obsolete macros with.  In
24047 particular, the mechanism for reporting the results of tests has
24048 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24049 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24050 looks better if you switch to @code{AC_MSG_CHECKING} and
24051 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24052 in conjunction with cache variables.  @xref{Caching Results}.
24056 @node Changed Results
24057 @subsection Changed Results
24059 If you were checking the results of previous tests by examining the
24060 shell variable @code{DEFS}, you need to switch to checking the values of
24061 the cache variables for those tests.  @code{DEFS} no longer exists while
24062 @command{configure} is running; it is only created when generating output
24063 files.  This difference from version 1 is because properly quoting the
24064 contents of that variable turned out to be too cumbersome and
24065 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24066 Variable Names}.
24068 For example, here is a @file{configure.ac} fragment written for Autoconf
24069 version 1:
24071 @example
24072 AC_HAVE_FUNCS(syslog)
24073 case "$DEFS" in
24074 *-DHAVE_SYSLOG*) ;;
24075 *) # syslog is not in the default libraries.  See if it's in some other.
24076   saved_LIBS="$LIBS"
24077   for lib in bsd socket inet; do
24078     AC_CHECKING(for syslog in -l$lib)
24079     LIBS="-l$lib $saved_LIBS"
24080     AC_HAVE_FUNCS(syslog)
24081     case "$DEFS" in
24082     *-DHAVE_SYSLOG*) break ;;
24083     *) ;;
24084     esac
24085     LIBS="$saved_LIBS"
24086   done ;;
24087 esac
24088 @end example
24090 Here is a way to write it for version 2:
24092 @example
24093 AC_CHECK_FUNCS([syslog])
24094 if test "x$ac_cv_func_syslog" = xno; then
24095   # syslog is not in the default libraries.  See if it's in some other.
24096   for lib in bsd socket inet; do
24097     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24098       LIBS="-l$lib $LIBS"; break])
24099   done
24101 @end example
24103 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24104 backslashes before quotes, you need to remove them.  It now works
24105 predictably, and does not treat quotes (except back quotes) specially.
24106 @xref{Setting Output Variables}.
24108 All of the Boolean shell variables set by Autoconf macros now use
24109 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24110 though for backward compatibility some use the empty string instead.  If
24111 you were relying on a shell variable being set to something like 1 or
24112 @samp{t} for true, you need to change your tests.
24114 @node Changed Macro Writing
24115 @subsection Changed Macro Writing
24117 When defining your own macros, you should now use @code{AC_DEFUN}
24118 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24119 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24120 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24121 messages on the screen.  There's no actual harm in continuing to use the
24122 older way, but it's less convenient and attractive.  @xref{Macro
24123 Definitions}.
24125 You probably looked at the macros that came with Autoconf as a guide for
24126 how to do things.  It would be a good idea to take a look at the new
24127 versions of them, as the style is somewhat improved and they take
24128 advantage of some new features.
24130 If you were doing tricky things with undocumented Autoconf internals
24131 (macros, variables, diversions), check whether you need to change
24132 anything to account for changes that have been made.  Perhaps you can
24133 even use an officially supported technique in version 2 instead of
24134 kludging.  Or perhaps not.
24136 To speed up your locally written feature tests, add caching to them.
24137 See whether any of your tests are of general enough usefulness to
24138 encapsulate them into macros that you can share.
24141 @node Autoconf 2.13
24142 @section Upgrading From Version 2.13
24143 @cindex Upgrading autoconf
24144 @cindex Autoconf upgrading
24146 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24147 suits this section@enddots{}
24149 @quotation
24150 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24151 However, it introduces better ways to do some things, and doesn't
24152 support some of the ugly things in version 2.13.  So, depending on how
24153 sophisticated your @file{configure.ac} files are, you might have to do
24154 some manual work in order to upgrade to version 2.50.  This chapter
24155 points out some problems to watch for when upgrading.  Also, perhaps
24156 your @command{configure} scripts could benefit from some of the new
24157 features in version 2.50; the changes are summarized in the file
24158 @file{NEWS} in the Autoconf distribution.
24159 @end quotation
24161 @menu
24162 * Changed Quotation::           Broken code which used to work
24163 * New Macros::                  Interaction with foreign macros
24164 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24165 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24166 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24167 @end menu
24169 @node Changed Quotation
24170 @subsection Changed Quotation
24172 The most important changes are invisible to you: the implementation of
24173 most macros have completely changed.  This allowed more factorization of
24174 the code, better error messages, a higher uniformity of the user's
24175 interface etc.  Unfortunately, as a side effect, some construct which
24176 used to (miraculously) work might break starting with Autoconf 2.50.
24177 The most common culprit is bad quotation.
24179 For instance, in the following example, the message is not properly
24180 quoted:
24182 @example
24183 AC_INIT
24184 AC_CHECK_HEADERS(foo.h, ,
24185   AC_MSG_ERROR(cannot find foo.h, bailing out))
24186 AC_OUTPUT
24187 @end example
24189 @noindent
24190 Autoconf 2.13 simply ignores it:
24192 @example
24193 $ @kbd{autoconf-2.13; ./configure --silent}
24194 creating cache ./config.cache
24195 configure: error: cannot find foo.h
24197 @end example
24199 @noindent
24200 while Autoconf 2.50 produces a broken @file{configure}:
24202 @example
24203 $ @kbd{autoconf-2.50; ./configure --silent}
24204 configure: error: cannot find foo.h
24205 ./configure: exit: bad non-numeric arg `bailing'
24206 ./configure: exit: bad non-numeric arg `bailing'
24208 @end example
24210 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24211 too!
24213 @example
24214 AC_INIT([Example], [1.0], [bug-example@@example.org])
24215 AC_CHECK_HEADERS([foo.h], [],
24216   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24217 AC_OUTPUT
24218 @end example
24220 Many many (and many more) Autoconf macros were lacking proper quotation,
24221 including no less than@dots{} @code{AC_DEFUN} itself!
24223 @example
24224 $ @kbd{cat configure.in}
24225 AC_DEFUN([AC_PROG_INSTALL],
24226 [# My own much better version
24228 AC_INIT
24229 AC_PROG_INSTALL
24230 AC_OUTPUT
24231 $ @kbd{autoconf-2.13}
24232 autoconf: Undefined macros:
24233 ***BUG in Autoconf--please report*** AC_FD_MSG
24234 ***BUG in Autoconf--please report*** AC_EPI
24235 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24236 configure.in:5:AC_PROG_INSTALL
24237 $ @kbd{autoconf-2.50}
24239 @end example
24242 @node New Macros
24243 @subsection New Macros
24245 @cindex undefined macro
24246 @cindex @code{_m4_divert_diversion}
24248 While Autoconf was relatively dormant in the late 1990s, Automake
24249 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24250 in 2001, Autoconf provided
24251 versions of these macros, integrated in the @code{AC_} namespace,
24252 instead of @code{AM_}.  But in order to ease the upgrading via
24253 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24255 Unfortunately older versions of Automake (e.g., Automake 1.4)
24256 did not quote the names of these macros.
24257 Therefore, when @command{m4} finds something like
24258 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24259 @code{AM_TYPE_PTRDIFF_T} is
24260 expanded, replaced with its Autoconf definition.
24262 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24263 complains, in its own words:
24265 @example
24266 $ @kbd{cat configure.ac}
24267 AC_INIT([Example], [1.0], [bug-example@@example.org])
24268 AM_TYPE_PTRDIFF_T
24269 $ @kbd{aclocal-1.4}
24270 $ @kbd{autoconf}
24271 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24272 aclocal.m4:17: the top level
24273 autom4te: m4 failed with exit status: 1
24275 @end example
24277 Modern versions of Automake no longer define most of these
24278 macros, and properly quote the names of the remaining macros.
24279 If you must use an old Automake, do not depend upon macros from Automake
24280 as it is simply not its job
24281 to provide macros (but the one it requires itself):
24283 @example
24284 $ @kbd{cat configure.ac}
24285 AC_INIT([Example], [1.0], [bug-example@@example.org])
24286 AM_TYPE_PTRDIFF_T
24287 $ @kbd{rm aclocal.m4}
24288 $ @kbd{autoupdate}
24289 autoupdate: `configure.ac' is updated
24290 $ @kbd{cat configure.ac}
24291 AC_INIT([Example], [1.0], [bug-example@@example.org])
24292 AC_CHECK_TYPES([ptrdiff_t])
24293 $ @kbd{aclocal-1.4}
24294 $ @kbd{autoconf}
24296 @end example
24299 @node Hosts and Cross-Compilation
24300 @subsection Hosts and Cross-Compilation
24301 @cindex Cross compilation
24303 Based on the experience of compiler writers, and after long public
24304 debates, many aspects of the cross-compilation chain have changed:
24306 @itemize @minus
24307 @item
24308 the relationship between the build, host, and target architecture types,
24310 @item
24311 the command line interface for specifying them to @command{configure},
24313 @item
24314 the variables defined in @command{configure},
24316 @item
24317 the enabling of cross-compilation mode.
24318 @end itemize
24320 @sp 1
24322 The relationship between build, host, and target have been cleaned up:
24323 the chain of default is now simply: target defaults to host, host to
24324 build, and build to the result of @command{config.guess}.  Nevertheless,
24325 in order to ease the transition from 2.13 to 2.50, the following
24326 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24327 be completely disabled in a couple of releases (we cannot keep it, as it
24328 proves to cause more problems than it cures).
24330 They all default to the result of running @command{config.guess}, unless
24331 you specify either @option{--build} or @option{--host}.  In this case,
24332 the default becomes the system type you specified.  If you specify both,
24333 and they're different, @command{configure} enters cross compilation
24334 mode, so it doesn't run any tests that require execution.
24336 Hint: if you mean to override the result of @command{config.guess},
24337 prefer @option{--build} over @option{--host}.  In the future,
24338 @option{--host} will not override the name of the build system type.
24339 Whenever you specify @option{--host}, be sure to specify @option{--build}
24340 too.
24342 @sp 1
24344 For backward compatibility, @command{configure} accepts a system
24345 type as an option by itself.  Such an option overrides the
24346 defaults for build, host, and target system types.  The following
24347 configure statement configures a cross toolchain that runs on
24348 NetBSD/alpha but generates code for GNU Hurd/sparc,
24349 which is also the build platform.
24351 @example
24352 ./configure --host=alpha-netbsd sparc-gnu
24353 @end example
24355 @sp 1
24357 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24358 and @code{target} had a different semantics before and after the
24359 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24360 @option{--build} is strictly copied into @code{build_alias}, and is left
24361 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24362 set to the canonicalized build type.  To ease the transition, before,
24363 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24364 rely on this broken feature.
24366 For consistency with the backward compatibility scheme exposed above,
24367 when @option{--host} is specified but @option{--build} isn't, the build
24368 system is assumed to be the same as @option{--host}, and
24369 @samp{build_alias} is set to that value.  Eventually, this
24370 historically incorrect behavior will go away.
24372 @sp 1
24374 The former scheme to enable cross-compilation proved to cause more harm
24375 than good, in particular, it used to be triggered too easily, leaving
24376 regular end users puzzled in front of cryptic error messages.
24377 @command{configure} could even enter cross-compilation mode only
24378 because the compiler was not functional.  This is mainly because
24379 @command{configure} used to try to detect cross-compilation, instead of
24380 waiting for an explicit flag from the user.
24382 Now, @command{configure} enters cross-compilation mode if and only if
24383 @option{--host} is passed.
24385 That's the short documentation.  To ease the transition between 2.13 and
24386 its successors, a more complicated scheme is implemented.  @emph{Do not
24387 rely on the following}, as it will be removed in the near future.
24389 If you specify @option{--host}, but not @option{--build}, when
24390 @command{configure} performs the first compiler test it tries to run
24391 an executable produced by the compiler.  If the execution fails, it
24392 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24393 the compiler test is performed, it may be too late to modify the
24394 build-system type: other tests may have already been performed.
24395 Therefore, whenever you specify @option{--host}, be sure to specify
24396 @option{--build} too.
24398 @example
24399 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24400 @end example
24402 @noindent
24403 enters cross-compilation mode.  The former interface, which
24404 consisted in setting the compiler to a cross-compiler without informing
24405 @command{configure} is obsolete.  For instance, @command{configure}
24406 fails if it can't run the code generated by the specified compiler if you
24407 configure as follows:
24409 @example
24410 ./configure CC=m68k-coff-gcc
24411 @end example
24414 @node AC_LIBOBJ vs LIBOBJS
24415 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24417 Up to Autoconf 2.13, the replacement of functions was triggered via the
24418 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24419 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24420 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24422 This change is mandated by the unification of the GNU Build System
24423 components.  In particular, the various fragile techniques used to parse
24424 a @file{configure.ac} are all replaced with the use of traces.  As a
24425 consequence, any action must be traceable, which obsoletes critical
24426 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24427 and it can even be handled gracefully (read, ``without your having to
24428 change something'').
24430 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24431 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24433 @sp 1
24435 As for function replacement, the fix is immediate: use
24436 @code{AC_LIBOBJ}.  For instance:
24438 @example
24439 LIBOBJS="$LIBOBJS fnmatch.o"
24440 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24441 @end example
24443 @noindent
24444 should be replaced with:
24446 @example
24447 AC_LIBOBJ([fnmatch])
24448 AC_LIBOBJ([malloc])
24449 @end example
24451 @sp 1
24453 @ovindex LIBOBJDIR
24454 When used with Automake 1.10 or newer, a suitable value for
24455 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24456 can be referenced from any @file{Makefile.am}.  Even without Automake,
24457 arranging for @code{LIBOBJDIR} to be set correctly enables
24458 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24459 The @code{LIBOBJDIR} feature is experimental.
24462 @node AC_ACT_IFELSE vs AC_TRY_ACT
24463 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24464 @c the anchor keeps the old node name, to try to avoid breaking links
24465 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24467 @acindex{@var{ACT}_IFELSE}
24468 @acindex{TRY_@var{ACT}}
24469 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24470 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24471 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24472 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24473 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24474 @code{AC_TRY_RUN}.  The motivations where:
24475 @itemize @minus
24476 @item
24477 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24478 quoting their arguments;
24480 @item
24481 the combinatoric explosion is solved by decomposing on the one hand the
24482 generation of sources, and on the other hand executing the program;
24484 @item
24485 this scheme helps supporting more languages than plain C and C++.
24486 @end itemize
24488 In addition to the change of syntax, the philosophy has changed too:
24489 while emphasis was put on speed at the expense of accuracy, today's
24490 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24491 expense of speed.
24494 As a perfect example of what is @emph{not} to be done, here is how to
24495 find out whether a header file contains a particular declaration, such
24496 as a typedef, a structure, a structure member, or a function.  Use
24497 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24498 header file; on some systems the symbol might be defined in another
24499 header file that the file you are checking includes.
24501 As a (bad) example, here is how you should not check for C preprocessor
24502 symbols, either defined by header files or predefined by the C
24503 preprocessor: using @code{AC_EGREP_CPP}:
24505 @example
24506 @group
24507 AC_EGREP_CPP(yes,
24508 [#ifdef _AIX
24509   yes
24510 #endif
24511 ], is_aix=yes, is_aix=no)
24512 @end group
24513 @end example
24515 The above example, properly written would (i) use
24516 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24518 @example
24519 @group
24520 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24521 [[#ifndef _AIX
24522  error: This isn't AIX!
24523 #endif
24524 ]])],
24525                    [is_aix=yes],
24526                    [is_aix=no])
24527 @end group
24528 @end example
24531 @c ============================= Generating Test Suites with Autotest
24533 @node Using Autotest
24534 @chapter Generating Test Suites with Autotest
24536 @cindex Autotest
24538 @display
24539 @strong{N.B.: This section describes a feature which is still
24540 stabilizing.  Although we believe that Autotest is useful as-is, this
24541 documentation describes an interface which might change in the future:
24542 do not depend upon Autotest without subscribing to the Autoconf mailing
24543 lists.}
24544 @end display
24546 It is paradoxical that portable projects depend on nonportable tools
24547 to run their test suite.  Autoconf by itself is the paragon of this
24548 problem: although it aims at perfectly portability, up to 2.13 its
24549 test suite was using DejaGNU, a rich and complex testing
24550 framework, but which is far from being standard on Posix systems.
24551 Worse yet, it was likely to be missing on the most fragile platforms,
24552 the very platforms that are most likely to torture Autoconf and
24553 exhibit deficiencies.
24555 To circumvent this problem, many package maintainers have developed their
24556 own testing framework, based on simple shell scripts whose sole outputs
24557 are exit status values describing whether the test succeeded.  Most of
24558 these tests share common patterns, and this can result in lots of
24559 duplicated code and tedious maintenance.
24561 Following exactly the same reasoning that yielded to the inception of
24562 Autoconf, Autotest provides a test suite generation framework, based on
24563 M4 macros building a portable shell script.  The suite itself is
24564 equipped with automatic logging and tracing facilities which greatly
24565 diminish the interaction with bug reporters, and simple timing reports.
24567 Autoconf itself has been using Autotest for years, and we do attest that
24568 it has considerably improved the strength of the test suite and the
24569 quality of bug reports.  Other projects are known to use some generation
24570 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
24571 them with different needs, and this usage has validated Autotest as a general
24572 testing framework.
24574 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24575 interactive tool testing, which is probably its main limitation.
24577 @menu
24578 * Using an Autotest Test Suite::  Autotest and the user
24579 * Writing Testsuites::          Autotest macros
24580 * testsuite Invocation::        Running @command{testsuite} scripts
24581 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24582 @end menu
24584 @node Using an Autotest Test Suite
24585 @section Using an Autotest Test Suite
24587 @menu
24588 * testsuite Scripts::           The concepts of Autotest
24589 * Autotest Logs::               Their contents
24590 @end menu
24592 @node testsuite Scripts
24593 @subsection @command{testsuite} Scripts
24595 @cindex @command{testsuite}
24597 Generating testing or validation suites using Autotest is rather easy.
24598 The whole validation suite is held in a file to be processed through
24599 @command{autom4te}, itself using GNU M4 under the hood, to
24600 produce a stand-alone Bourne shell script which then gets distributed.
24601 Neither @command{autom4te} nor GNU M4 are needed at
24602 the installer's end.
24604 @cindex test group
24605 Each test of the validation suite should be part of some test group.  A
24606 @dfn{test group} is a sequence of interwoven tests that ought to be
24607 executed together, usually because one test in the group creates data
24608 files that a later test in the same group needs to read.  Complex test
24609 groups make later debugging more tedious.  It is much better to
24610 keep only a few tests per test group.  Ideally there is only one test
24611 per test group.
24613 For all but the simplest packages, some file such as @file{testsuite.at}
24614 does not fully hold all test sources, as these are often easier to
24615 maintain in separate files.  Each of these separate files holds a single
24616 test group, or a sequence of test groups all addressing some common
24617 functionality in the package.  In such cases, @file{testsuite.at}
24618 merely initializes the validation suite, and sometimes does elementary
24619 health checking, before listing include statements for all other test
24620 files.  The special file @file{package.m4}, containing the
24621 identification of the package, is automatically included if found.
24623 A convenient alternative consists in moving all the global issues
24624 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24625 invocation) into the file @code{local.at}, and making
24626 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24627 suites.  In such case, generating the whole test suite or pieces of it
24628 is only a matter of choosing the @command{autom4te} command line
24629 arguments.
24631 The validation scripts that Autotest produces are by convention called
24632 @command{testsuite}.  When run, @command{testsuite} executes each test
24633 group in turn, producing only one summary line per test to say if that
24634 particular test succeeded or failed.  At end of all tests, summarizing
24635 counters get printed.  One debugging directory is left for each test
24636 group which failed, if any: such directories are named
24637 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24638 the test group, and they include:
24640 @itemize @bullet
24641 @item a debugging script named @file{run} which reruns the test in
24642 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24643 of debugging scripts has the purpose of easing the chase for bugs.
24645 @item all the files created with @code{AT_DATA}
24647 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24649 @item a log of the run, named @file{testsuite.log}
24650 @end itemize
24652 In the ideal situation, none of the tests fail, and consequently no
24653 debugging directory is left behind for validation.
24655 It often happens in practice that individual tests in the validation
24656 suite need to get information coming out of the configuration process.
24657 Some of this information, common for all validation suites, is provided
24658 through the file @file{atconfig}, automatically created by
24659 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
24660 testing environment specifically needs, you might prepare an optional
24661 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24662 The configuration process produces @file{atconfig} and @file{atlocal}
24663 out of these two input files, and these two produced files are
24664 automatically read by the @file{testsuite} script.
24666 Here is a diagram showing the relationship between files.
24668 @noindent
24669 Files used in preparing a software package for distribution:
24671 @example
24672                 [package.m4] -->.
24673                                  \
24674 subfile-1.at ->.  [local.at] ---->+
24675     ...         \                  \
24676 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
24677     ...         /
24678 subfile-n.at ->'
24679 @end example
24681 @noindent
24682 Files used in configuring a software package:
24684 @example
24685                                      .--> atconfig
24686                                     /
24687 [atlocal.in] -->  config.status* --<
24688                                     \
24689                                      `--> [atlocal]
24690 @end example
24692 @noindent
24693 Files created during test suite execution:
24695 @example
24696 atconfig -->.                    .--> testsuite.log
24697              \                  /
24698               >-- testsuite* --<
24699              /                  \
24700 [atlocal] ->'                    `--> [testsuite.dir]
24701 @end example
24704 @node Autotest Logs
24705 @subsection Autotest Logs
24707 When run, the test suite creates a log file named after itself, e.g., a
24708 test suite named @command{testsuite} creates @file{testsuite.log}.  It
24709 contains a lot of information, usually more than maintainers actually
24710 need, but therefore most of the time it contains all that is needed:
24712 @table @asis
24713 @item command line arguments
24714 A bad but unfortunately widespread habit consists of
24715 setting environment variables before the command, such as in
24716 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
24717 know this change, hence (i) it cannot report it to you, and (ii)
24718 it cannot preserve the value of @code{CC} for subsequent runs.
24719 Autoconf faced exactly the same problem, and solved it by asking
24720 users to pass the variable definitions as command line arguments.
24721 Autotest requires this rule, too, but has no means to enforce it; the log
24722 then contains a trace of the variables that were changed by the user.
24724 @item @file{ChangeLog} excerpts
24725 The topmost lines of all the @file{ChangeLog} files found in the source
24726 hierarchy.  This is especially useful when bugs are reported against
24727 development versions of the package, since the version string does not
24728 provide sufficient information to know the exact state of the sources
24729 the user compiled.  Of course, this relies on the use of a
24730 @file{ChangeLog}.
24732 @item build machine
24733 Running a test suite in a cross-compile environment is not an easy task,
24734 since it would mean having the test suite run on a machine @var{build},
24735 while running programs on a machine @var{host}.  It is much simpler to
24736 run both the test suite and the programs on @var{host}, but then, from
24737 the point of view of the test suite, there remains a single environment,
24738 @var{host} = @var{build}.  The log contains relevant information on the
24739 state of the @var{build} machine, including some important environment
24740 variables.
24741 @c FIXME: How about having an M4sh macro to say `hey, log the value
24742 @c of `@dots{}'?  This would help both Autoconf and Autotest.
24744 @item tested programs
24745 The absolute file name and answers to @option{--version} of the tested
24746 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
24748 @item configuration log
24749 The contents of @file{config.log}, as created by @command{configure},
24750 are appended.  It contains the configuration flags and a detailed report
24751 on the configuration itself.
24752 @end table
24755 @node Writing Testsuites
24756 @section Writing @file{testsuite.at}
24758 The @file{testsuite.at} is a Bourne shell script making use of special
24759 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
24760 its beginning followed by one call to @code{m4_include} per source file
24761 for tests.  Each such included file, or the remainder of
24762 @file{testsuite.at} if include files are not used, contain a sequence of
24763 test groups.  Each test group begins with a call to @code{AT_SETUP},
24764 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
24765 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
24766 groups can be categorized by a call to @code{AT_BANNER}.
24768 All of the public Autotest macros have all-uppercase names in the
24769 namespace @samp{^AT_} to prevent them from accidentally conflicting with
24770 other text; Autoconf also reserves the namespace @samp{^_AT_} for
24771 internal macros.  All shell variables used in the testsuite for internal
24772 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
24773 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
24774 makes use of the file system namespace @samp{^at-}.
24776 Since Autoconf is built on top of M4sugar (@pxref{Programming in
24777 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
24778 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
24779 @emph{should not use} the namespace of a package that does not own the
24780 macro or shell code you are writing.
24782 @defmac AT_INIT (@ovar{name})
24783 @atindex{INIT}
24784 @c FIXME: Not clear, plus duplication of the information.
24785 Initialize Autotest.  Giving a @var{name} to the test suite is
24786 encouraged if your package includes several test suites.  Before this
24787 macro is called, @code{AT_PACKAGE_STRING} and
24788 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
24789 information about the testsuite to the user.  Typically, these macros
24790 are provided by a file @file{package.m4} built by @command{make}
24791 (@pxref{Making testsuite Scripts}), in order to inherit the package
24792 name, version, and bug reporting address from @file{configure.ac}.
24793 @end defmac
24795 @defmac AT_COPYRIGHT (@var{copyright-notice})
24796 @atindex{COPYRIGHT}
24797 @cindex Copyright Notice
24798 State that, in addition to the Free Software Foundation's copyright on
24799 the Autotest macros, parts of your test suite are covered by
24800 @var{copyright-notice}.
24802 The @var{copyright-notice} shows up in both the head of
24803 @command{testsuite} and in @samp{testsuite --version}.
24804 @end defmac
24806 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
24807   @ovar{action-if-given}, @ovar{action-if-not-given})
24808 @atindex{ARG_OPTION}
24809 @vrindex at_arg_@var{option}
24810 Accept options from the space-separated list @var{options}, a list that
24811 has leading dashes removed from the options.  Long options will be
24812 prefixed with @samp{--}, single-character options with @samp{-}.  The
24813 first word in this list is the primary @var{option}, any others are
24814 assumed to be short-hand aliases.  The variable associated with it
24815 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
24816 with underscores.
24818 If the user passes @option{--@var{option}} to the @command{testsuite},
24819 the variable will be set to @samp{:}.  If the user does not pass the
24820 option, or passes @option{--no-@var{option}}, then the variable will be
24821 set to @samp{false}.
24823 @vrindex at_optarg
24824 @vrindex at_optarg_@var{option}
24825 @var{action-if-given} is run each time the option is encountered; here,
24826 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
24827 appropriate.  @code{at_optarg} is actually just a copy of
24828 @code{at_arg_@var{option}}.
24830 @var{action-if-not-given} will be run once after option parsing is
24831 complete and if no option from @var{options} was used.
24833 @var{help-text} is added to the end of the list of options shown in
24834 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24836 It it recommended that you use a package-specific prefix to @var{options}
24837 names in order to avoid clashes with future Autotest built-in options.
24838 @end defmac
24840 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
24841   @ovar{action-if-given}, @ovar{action-if-not-given})
24842 @atindex{ARG_OPTION_ARG}
24843 @vrindex at_arg_@var{option}
24844 Accept options with arguments from the space-separated list
24845 @var{options}, a list that has leading dashes removed from the options.
24846 Long options will be prefixed with @samp{--}, single-character options
24847 with @samp{-}.  The first word in this list is the primary @var{option},
24848 any others are assumed to be short-hand aliases.  The variable associated
24849 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24850 replaced with underscores.
24852 If the user passes @option{--@var{option}=@var{arg}} or
24853 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
24854 variable will be set to @samp{@var{arg}}.
24856 @vrindex at_optarg
24857 @var{action-if-given} is run each time the option is encountered; here,
24858 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24859 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24861 @var{action-if-not-given} will be run once after option parsing is
24862 complete and if no option from @var{options} was used.
24864 @var{help-text} is added to the end of the list of options shown in
24865 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24867 It it recommended that you use a package-specific prefix to @var{options}
24868 names in order to avoid clashes with future Autotest built-in options.
24869 @end defmac
24871 @defmac AT_COLOR_TESTS
24872 @atindex{COLOR_TESTS}
24873 Enable colored test results by default when the output is connected to
24874 a terminal.
24875 @end defmac
24877 @defmac AT_TESTED (@var{executables})
24878 @atindex{TESTED}
24879 Log the file name and answer to @option{--version} of each program in
24880 space-separated list @var{executables}.  Several invocations register
24881 new executables, in other words, don't fear registering one program
24882 several times.
24884 Autotest test suites rely on @env{PATH} to find the tested program.
24885 This avoids the need to generate absolute names of the various tools, and
24886 makes it possible to test installed programs.  Therefore, knowing which
24887 programs are being exercised is crucial to understanding problems in
24888 the test suite itself, or its occasional misuses.  It is a good idea to
24889 also subscribe foreign programs you depend upon, to avoid incompatible
24890 diagnostics.
24891 @end defmac
24893 @sp 1
24895 @defmac AT_BANNER (@var{test-category-name})
24896 @atindex{BANNER}
24897 This macro identifies the start of a category of related test groups.
24898 When the resulting @file{testsuite} is invoked with more than one test
24899 group to run, its output will include a banner containing
24900 @var{test-category-name} prior to any tests run from that category.  The
24901 banner should be no more than about 40 or 50 characters.  A blank banner
24902 indicates uncategorized tests; an empty line will be inserted after
24903 tests from an earlier category, effectively ending that category.
24904 @end defmac
24906 @defmac AT_SETUP (@var{test-group-name})
24907 @atindex{SETUP}
24908 This macro starts a group of related tests, all to be executed in the
24909 same subshell.  It accepts a single argument, which holds a few words
24910 (no more than about 30 or 40 characters) quickly describing the purpose
24911 of the test group being started.  @var{test-group-name} must not expand
24912 to unbalanced quotes, although quadrigraphs can be used.
24913 @end defmac
24915 @defmac AT_KEYWORDS (@var{keywords})
24916 @atindex{KEYWORDS}
24917 Associate the space-separated list of @var{keywords} to the enclosing
24918 test group.  This makes it possible to run ``slices'' of the test suite.
24919 For instance, if some of your test groups exercise some @samp{foo}
24920 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
24921 @samp{./testsuite -k foo} to run exclusively these test groups.  The
24922 @var{test-group-name} of the test group is automatically recorded to
24923 @code{AT_KEYWORDS}.
24925 Several invocations within a test group accumulate new keywords.  In
24926 other words, don't fear registering the same keyword several times in a
24927 test group.
24928 @end defmac
24930 @defmac AT_CAPTURE_FILE (@var{file})
24931 @atindex{CAPTURE_FILE}
24932 If the current test group fails, log the contents of @var{file}.
24933 Several identical calls within one test group have no additional effect.
24934 @end defmac
24936 @defmac AT_FAIL_IF (@var{shell-condition})
24937 @atindex{FAIL_IF}
24938 Make the test group fail and skip the rest of its execution, if
24939 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
24940 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
24941 will be executed and may still cause the test group to be skipped.
24942 You can instantiate this macro many times from within the same test group.
24944 You should use this macro only for very simple failure conditions.  If the
24945 @var{shell-condition} could emit any kind of output you should instead
24946 use @command{AT_CHECK} like
24947 @example
24948 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
24949 @end example
24950 @noindent
24951 so that such output is properly recorded in the @file{testsuite.log}
24952 file.
24953 @end defmac
24955 @defmac AT_SKIP_IF (@var{shell-condition})
24956 @atindex{SKIP_IF}
24957 Determine whether the test should be skipped because it requires
24958 features that are unsupported on the machine under test.
24959 @var{shell-condition} is a shell expression such as a @code{test}
24960 command.  Tests before @command{AT_SKIP_IF} will be executed
24961 and may still cause the test group to fail.  You can instantiate this
24962 macro many times from within the same test group.
24964 You should use this macro only for very simple skip conditions.  If the
24965 @var{shell-condition} could emit any kind of output you should instead
24966 use @command{AT_CHECK} like
24967 @example
24968 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
24969 @end example
24970 @noindent
24971 so that such output is properly recorded in the @file{testsuite.log}
24972 file.
24973 @end defmac
24975 @defmac AT_XFAIL_IF (@var{shell-condition})
24976 @atindex{XFAIL_IF}
24977 Determine whether the test is expected to fail because it is a known
24978 bug (for unsupported features, you should skip the test).
24979 @var{shell-condition} is a shell expression such as a @code{test}
24980 command; you can instantiate this macro many times from within the
24981 same test group, and one of the conditions is enough to turn
24982 the test into an expected failure.
24983 @end defmac
24985 @defmac AT_CLEANUP
24986 @atindex{CLEANUP}
24987 End the current test group.
24988 @end defmac
24990 @sp 1
24992 @defmac AT_DATA (@var{file}, @var{contents})
24993 @atindex{DATA}
24994 Initialize an input data @var{file} with given @var{contents}.  Of
24995 course, the @var{contents} have to be properly quoted between square
24996 brackets to protect against included commas or spurious M4
24997 expansion.  @var{contents} must be empty or end with a newline.
24998 @var{file} must
24999 be a single shell word that expands into a single file name.
25000 @end defmac
25002 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25003   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25004 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25005   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25006 @atindex{CHECK}
25007 @atindex{CHECK_UNQUOTED}
25008 @vrindex at_status
25009 Execute a test by performing given shell @var{commands} in a subshell.
25010 @var{commands} is output as-is, so shell expansions are honored.  These
25011 commands should normally exit with @var{status}, while producing expected
25012 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25013 unexpected status 77, then the rest of the test group is skipped.  If
25014 @var{commands} exit with unexpected status 99, then the test group is
25015 immediately failed.  Otherwise, if this test fails, run shell commands
25016 @var{run-if-fail} or, if this test passes, run shell commands
25017 @var{run-if-pass}, both inside the current shell execution environment.
25018 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25019 @var{commands} is available in the @code{at_status} shell variable.
25021 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25023 If @var{status} is the literal @samp{ignore}, then the corresponding
25024 exit status is not checked, except for the special cases of 77 (skip)
25025 and 99 (hard failure).  The existence of hard failures allows one to
25026 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25027 feature has not yet been implemented, but to still distinguish between
25028 gracefully handling the missing feature and dumping core.  A hard
25029 failure also inhibits post-test actions in @var{run-if-fail}.
25031 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25032 literals in the following table, then the test treats the output
25033 according to the rules of that literal.  Otherwise, the value of the
25034 parameter is treated as text that must exactly match the output given by
25035 @var{commands} on standard output and standard error (including an empty
25036 parameter for no output); any differences are captured in the testsuite
25037 log and the test is failed (unless an unexpected exit status of 77
25038 skipped the test instead).  The difference between @code{AT_CHECK} and
25039 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25040 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25041 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25042 @var{stderr} arguments; if the text includes a trailing newline, this
25043 would be the same as if it were specified via an unquoted
25044 here-document.  (However, there is no difference in the interpretation
25045 of @var{commands}).
25047 @table @samp
25048 @item ignore
25049 The content of the output is ignored, but still captured in the test
25050 group log (if the testsuite is run with option @option{-v}, the test
25051 group log is displayed as the test is run; if the test group later
25052 fails, the test group log is also copied into the overall testsuite
25053 log).  This action is valid for both @var{stdout} and @var{stderr}.
25055 @item ignore-nolog
25056 The content of the output is ignored, and nothing is captured in the log
25057 files.  If @var{commands} are likely to produce binary output (including
25058 long lines) or large amounts of output, then logging the output can make
25059 it harder to locate details related to subsequent tests within the
25060 group, and could potentially corrupt terminal display of a user running
25061 @command{testsuite -v}.
25063 @item stdout
25064 For the @var{stdout} parameter, capture the content of standard output
25065 to both the file @file{stdout} and the test group log.  Subsequent
25066 commands in the test group can then post-process the file.  This action
25067 is often used when it is desired to use @command{grep} to look for a
25068 substring in the output, or when the output must be post-processed to
25069 normalize error messages into a common form.
25071 @item stderr
25072 Like @samp{stdout}, except that it only works for the @var{stderr}
25073 parameter, and the standard error capture file will be named
25074 @file{stderr}.
25076 @item stdout-nolog
25077 @itemx stderr-nolog
25078 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25079 not duplicated into the test group log.  This action is particularly
25080 useful for an intermediate check that produces large amounts of data,
25081 which will be followed by another check that filters down to the
25082 relevant data, as it makes it easier to locate details in the log.
25084 @item expout
25085 For the @var{stdout} parameter, compare standard output contents with
25086 the previously created file @file{expout}, and list any differences in
25087 the testsuite log.
25089 @item experr
25090 Like @samp{expout}, except that it only works for the @var{stderr}
25091 parameter, and the standard error contents are compared with
25092 @file{experr}.
25093 @end table
25094 @end defmac
25096 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25097   @ovar{run-if-fail}, @ovar{run-if-pass})
25098 @atindex{CHECK_EUNIT}
25099 Initialize and execute an Erlang module named @var{module} that performs
25100 tests following the @var{test-spec} EUnit test specification.
25101 @var{test-spec} must be a valid EUnit test specification, as defined in
25102 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25103 Reference Manual}.  @var{erlflags} are optional command-line options
25104 passed to the Erlang interpreter to execute the test Erlang module.
25105 Typically, @var{erlflags} defines at least the paths to directories
25106 containing the compiled Erlang modules under test, as @samp{-pa path1
25107 path2 ...}.
25109 For example, the unit tests associated with Erlang module @samp{testme},
25110 which compiled code is in subdirectory @file{src}, can be performed
25111 with:
25113 @example
25114 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25115                [-pa "$@{abs_top_builddir@}/src"])
25116 @end example
25118 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25120 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25121 must be defined as the path of the Erlang interpreter, the path of the
25122 Erlang compiler, and the command-line flags to pass to the compiler,
25123 respectively.  Those variables should be configured in
25124 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25125 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25126 variables are automatically defined in the testsuite.  If @code{ERL} or
25127 @code{ERLC} is not defined, the test group is skipped.
25129 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25130 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25131 an invalid EUnit test specification, the test group fails.  Otherwise,
25132 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25133 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25134 executed and the test group fails.
25136 Only the generated test Erlang module is automatically compiled and
25137 executed.  If @var{test-spec} involves testing other Erlang modules,
25138 e.g. module @samp{testme} in the example above, those modules must be
25139 already compiled.
25141 If the testsuite is run in verbose mode, with option @option{--verbose},
25142 EUnit is also run in verbose mode to output more details about
25143 individual unit tests.
25144 @end defmac
25147 @node testsuite Invocation
25148 @section Running @command{testsuite} Scripts
25149 @cindex @command{testsuite}
25151 Autotest test suites support the following options:
25153 @table @option
25154 @item --help
25155 @itemx -h
25156 Display the list of options and exit successfully.
25158 @item --version
25159 @itemx -V
25160 Display the version of the test suite and exit successfully.
25162 @item --directory=@var{dir}
25163 @itemx -C @var{dir}
25164 Change the current directory to @var{dir} before creating any files.
25165 Useful for running the testsuite in a subdirectory from a top-level
25166 Makefile.
25168 @item --jobs@r{[}=@var{n}@r{]}
25169 @itemx -j@ovar{n}
25170 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25171 run all given tests in parallel.  Note that there should be no space
25172 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25173 the separate arguments @option{-j} and @option{@var{number}}, see below.
25175 In parallel mode, the standard input device of the testsuite script is
25176 not available to commands inside a test group.  Furthermore, banner
25177 lines are not printed, and the summary line for each test group is
25178 output after the test group completes.  Summary lines may appear
25179 unordered.  If verbose and trace output are enabled (see below), they
25180 may appear intermixed from concurrently running tests.
25182 Parallel mode requires the @command{mkfifo} command to work, and will be
25183 silently disabled otherwise.
25185 @item --clean
25186 @itemx -c
25187 Remove all the files the test suite might have created and exit.  Meant
25188 for @code{clean} Make targets.
25190 @item --list
25191 @itemx -l
25192 List all the tests (or only the selection), including their possible
25193 keywords.
25194 @end table
25196 @sp 1
25198 By default all tests are performed (or described with @option{--list})
25199 silently in the default environment, but the environment, set of tests,
25200 and verbosity level can be tuned:
25202 @table @samp
25203 @item @var{variable}=@var{value}
25204 Set the environment @var{variable} to @var{value}.  Use this rather
25205 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25206 different environment.
25208 @cindex @code{AUTOTEST_PATH}
25209 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25210 to @env{PATH}.  Relative directory names (not starting with
25211 @samp{/}) are considered to be relative to the top level of the
25212 package being built.  All directories are made absolute, first
25213 starting from the top level @emph{build} tree, then from the
25214 @emph{source} tree.  For instance @samp{./testsuite
25215 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25216 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25217 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25218 @env{PATH}.
25220 @item @var{number}
25221 @itemx @var{number}-@var{number}
25222 @itemx @var{number}-
25223 @itemx -@var{number}
25224 Add the corresponding test groups, with obvious semantics, to the
25225 selection.
25227 @item --keywords=@var{keywords}
25228 @itemx -k @var{keywords}
25229 Add to the selection the test groups with title or keywords (arguments
25230 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25231 of the comma separated list @var{keywords}, case-insensitively.  Use
25232 @samp{!} immediately before the keyword to invert the selection for this
25233 keyword.  By default, the keywords match whole words; enclose them in
25234 @samp{.*} to also match parts of words.
25236 For example, running
25238 @example
25239 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25240 @end example
25242 @noindent
25243 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25244 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25245 etc.), while
25247 @example
25248 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25249 @end example
25251 @noindent
25252 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25253 containing @samp{FUNC}.
25255 @item --errexit
25256 @itemx -e
25257 If any test fails, immediately abort testing.  This implies
25258 @option{--debug}: post test group clean up, and top-level logging
25259 are inhibited.  This option is meant for the full test
25260 suite, it is not really useful for generated debugging scripts.
25261 If the testsuite is run in parallel mode using @option{--jobs},
25262 then concurrently running tests will finish before exiting.
25264 @item --verbose
25265 @itemx -v
25266 Force more verbosity in the detailed output of what is being done.  This
25267 is the default for debugging scripts.
25269 @item --color
25270 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25271 Enable colored test results.  Without an argument, or with @samp{always},
25272 test results will be colored.  With @samp{never}, color mode is turned
25273 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25274 the testsuite author, or the argument @samp{auto} is given, then test
25275 results are colored if standard output is connected to a terminal.
25277 @item --debug
25278 @itemx -d
25279 Do not remove the files after a test group was performed---but they are
25280 still removed @emph{before}, therefore using this option is sane when
25281 running several test groups.  Create debugging scripts.  Do not
25282 overwrite the top-level
25283 log (in order to preserve a supposedly existing full log file).  This is
25284 the default for debugging scripts, but it can also be useful to debug
25285 the testsuite itself.
25287 @item --recheck
25288 Add to the selection all test groups that failed or passed unexpectedly
25289 during the last non-debugging test run.
25291 @item --trace
25292 @itemx -x
25293 Trigger shell tracing of the test groups.
25294 @end table
25296 Besides these options accepted by every Autotest testsuite, the
25297 testsuite author might have added package-specific options
25298 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25299 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25300 the package documentation for details.
25303 @node Making testsuite Scripts
25304 @section Making @command{testsuite} Scripts
25306 For putting Autotest into movement, you need some configuration and
25307 makefile machinery.  We recommend, at least if your package uses deep or
25308 shallow hierarchies, that you use @file{tests/} as the name of the
25309 directory holding all your tests and their makefile.  Here is a
25310 check list of things to do.
25312 @itemize @minus
25314 @item
25315 @cindex @file{package.m4}
25316 @atindex{PACKAGE_STRING}
25317 @atindex{PACKAGE_BUGREPORT}
25318 @atindex{PACKAGE_NAME}
25319 @atindex{PACKAGE_TARNAME}
25320 @atindex{PACKAGE_VERSION}
25321 @atindex{PACKAGE_URL}
25322 Make sure to create the file @file{package.m4}, which defines the
25323 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25324 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25325 address to which bug reports should be sent.  For sake of completeness,
25326 we suggest that you also define @code{AT_PACKAGE_NAME},
25327 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25328 @code{AT_PACKAGE_URL}.
25329 @xref{Initializing configure}, for a description of these variables.
25330 Be sure to distribute @file{package.m4} and to put it into the source
25331 hierarchy: the test suite ought to be shipped!  See below for an example
25332 @file{Makefile} excerpt.
25334 @item
25335 Invoke @code{AC_CONFIG_TESTDIR}.
25337 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
25338 @acindex{CONFIG_TESTDIR}
25339 An Autotest test suite is to be configured in @var{directory}.  This
25340 macro causes @file{@var{directory}/atconfig} to be created by
25341 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25342 @var{test-path} (@pxref{testsuite Invocation}).
25343 @end defmac
25345 @item
25346 Still within @file{configure.ac}, as appropriate, ensure that some
25347 @code{AC_CONFIG_FILES} command includes substitution for
25348 @file{tests/atlocal}.
25350 @item
25351 The appropriate @file{Makefile} should be modified so the validation in
25352 your package is triggered by @samp{make check}.  An example is provided
25353 below.
25354 @end itemize
25356 With Automake, here is a minimal example for inclusion in
25357 @file{tests/Makefile.am}, in order to link @samp{make check} with a
25358 validation suite.
25360 @example
25361 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
25362 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25363         :;@{ \
25364           echo '# Signature of the current package.' && \
25365           echo 'm4_define([AT_PACKAGE_NAME],' && \
25366           echo '  [$(PACKAGE_NAME)])' && \
25367           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25368           echo '  [$(PACKAGE_TARNAME)])' && \
25369           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25370           echo '  [$(PACKAGE_VERSION)])' && \
25371           echo 'm4_define([AT_PACKAGE_STRING],' && \
25372           echo '  [$(PACKAGE_STRING)])' && \
25373           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25374           echo '  [$(PACKAGE_BUGREPORT)])'; \
25375           echo 'm4_define([AT_PACKAGE_URL],' && \
25376           echo '  [$(PACKAGE_URL)])'; \
25377         @} >'$(srcdir)/package.m4'
25379 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25380 TESTSUITE = $(srcdir)/testsuite
25382 check-local: atconfig atlocal $(TESTSUITE)
25383         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25385 installcheck-local: atconfig atlocal $(TESTSUITE)
25386         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25387           $(TESTSUITEFLAGS)
25389 clean-local:
25390         test ! -f '$(TESTSUITE)' || \
25391          $(SHELL) '$(TESTSUITE)' --clean
25393 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
25394 AUTOTEST = $(AUTOM4TE) --language=autotest
25395 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25396         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25397         mv $@@.tmp $@@
25398 @end example
25400 Note that the built testsuite is distributed; this is necessary because
25401 users might not have Autoconf installed, and thus would not be able to
25402 rebuild it.  Likewise, the use of @file{missing} provides the user with
25403 a nicer error message if they modify a source file to the testsuite, and
25404 accidentally trigger the rebuild rules.
25406 You might want to list explicitly the dependencies, i.e., the list of
25407 the files @file{testsuite.at} includes.
25409 If you don't use Automake, you should include the above example in
25410 @file{tests/@/Makefile.in}, along with additional lines inspired from
25411 the following:
25413 @example
25414 subdir = tests
25415 PACKAGE_NAME = @@PACKAGE_NAME@@
25416 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25417 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25418 PACKAGE_STRING = @@PACKAGE_STRING@@
25419 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25420 PACKAGE_URL = @@PACKAGE_URL@@
25422 atconfig: $(top_builddir)/config.status
25423         cd $(top_builddir) && \
25424            $(SHELL) ./config.status $(subdir)/$@@
25426 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25427         cd $(top_builddir) && \
25428            $(SHELL) ./config.status $(subdir)/$@@
25429 @end example
25431 @noindent
25432 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
25433 to distribute the file @file{build-aux/@/missing} from the Automake
25434 project; a copy of this file resides in the Autoconf source tree.
25436 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
25437 within your makefile, you can fine-tune test suite execution with this
25438 variable, for example:
25440 @example
25441 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25442 @end example
25446 @c =============================== Frequent Autoconf Questions, with answers
25448 @node FAQ
25449 @chapter Frequent Autoconf Questions, with answers
25451 Several questions about Autoconf come up occasionally.  Here some of them
25452 are addressed.
25454 @menu
25455 * Distributing::                Distributing @command{configure} scripts
25456 * Why GNU M4::                  Why not use the standard M4?
25457 * Bootstrapping::               Autoconf and GNU M4 require each other?
25458 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25459 * Defining Directories::        Passing @code{datadir} to program
25460 * Autom4te Cache::              What is it?  Can I remove it?
25461 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25462 * Expanded Before Required::    Expanded Before Required
25463 * Debugging::                   Debugging @command{configure} scripts
25464 @end menu
25466 @node Distributing
25467 @section Distributing @command{configure} Scripts
25468 @cindex License
25470 @display
25471 What are the restrictions on distributing @command{configure}
25472 scripts that Autoconf generates?  How does that affect my
25473 programs that use them?
25474 @end display
25476 There are no restrictions on how the configuration scripts that Autoconf
25477 produces may be distributed or used.  In Autoconf version 1, they were
25478 covered by the GNU General Public License.  We still encourage
25479 software authors to distribute their work under terms like those of the
25480 GPL, but doing so is not required to use Autoconf.
25482 Of the other files that might be used with @command{configure},
25483 @file{config.h.in} is under whatever copyright you use for your
25484 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25485 exception to the GPL when they are used with an Autoconf-generated
25486 @command{configure} script, which permits you to distribute them under the
25487 same terms as the rest of your package.  @file{install-sh} is from the X
25488 Consortium and is not copyrighted.
25490 @node Why GNU M4
25491 @section Why Require GNU M4?
25493 @display
25494 Why does Autoconf require GNU M4?
25495 @end display
25497 Many M4 implementations have hard-coded limitations on the size and
25498 number of macros that Autoconf exceeds.  They also lack several
25499 builtin macros that it would be difficult to get along without in a
25500 sophisticated application like Autoconf, including:
25502 @example
25503 m4_builtin
25504 m4_indir
25505 m4_bpatsubst
25506 __file__
25507 __line__
25508 @end example
25510 Autoconf requires version 1.4.6 or later of GNU M4.
25512 Since only software maintainers need to use Autoconf, and since GNU
25513 M4 is simple to configure and install, it seems reasonable to require
25514 GNU M4 to be installed also.  Many maintainers of GNU and
25515 other free software already have most of the GNU utilities
25516 installed, since they prefer them.
25518 @node Bootstrapping
25519 @section How Can I Bootstrap?
25520 @cindex Bootstrap
25522 @display
25523 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25524 @command{configure} script, how do I bootstrap?  It seems like a chicken
25525 and egg problem!
25526 @end display
25528 This is a misunderstanding.  Although GNU M4 does come with a
25529 @command{configure} script produced by Autoconf, Autoconf is not required
25530 in order to run the script and install GNU M4.  Autoconf is only
25531 required if you want to change the M4 @command{configure} script, which few
25532 people have to do (mainly its maintainer).
25534 @node Why Not Imake
25535 @section Why Not Imake?
25536 @cindex Imake
25538 @display
25539 Why not use Imake instead of @command{configure} scripts?
25540 @end display
25542 Several people have written addressing this question, so
25543 adaptations of their explanations are included here.
25545 The following answer is based on one written by Richard Pixley:
25547 @quotation
25548 Autoconf generated scripts frequently work on machines that it has
25549 never been set up to handle before.  That is, it does a good job of
25550 inferring a configuration for a new system.  Imake cannot do this.
25552 Imake uses a common database of host specific data.  For X11, this makes
25553 sense because the distribution is made as a collection of tools, by one
25554 central authority who has control over the database.
25556 GNU tools are not released this way.  Each GNU tool has a
25557 maintainer; these maintainers are scattered across the world.  Using a
25558 common database would be a maintenance nightmare.  Autoconf may appear
25559 to be this kind of database, but in fact it is not.  Instead of listing
25560 host dependencies, it lists program requirements.
25562 If you view the GNU suite as a collection of native tools, then the
25563 problems are similar.  But the GNU development tools can be
25564 configured as cross tools in almost any host+target permutation.  All of
25565 these configurations can be installed concurrently.  They can even be
25566 configured to share host independent files across hosts.  Imake doesn't
25567 address these issues.
25569 Imake templates are a form of standardization.  The GNU coding
25570 standards address the same issues without necessarily imposing the same
25571 restrictions.
25572 @end quotation
25575 Here is some further explanation, written by Per Bothner:
25577 @quotation
25578 One of the advantages of Imake is that it is easy to generate large
25579 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25580 However, @code{cpp} is not programmable: it has limited conditional
25581 facilities, and no looping.  And @code{cpp} cannot inspect its
25582 environment.
25584 All of these problems are solved by using @code{sh} instead of
25585 @code{cpp}.  The shell is fully programmable, has macro substitution,
25586 can execute (or source) other shell scripts, and can inspect its
25587 environment.
25588 @end quotation
25591 Paul Eggert elaborates more:
25593 @quotation
25594 With Autoconf, installers need not assume that Imake itself is already
25595 installed and working well.  This may not seem like much of an advantage
25596 to people who are accustomed to Imake.  But on many hosts Imake is not
25597 installed or the default installation is not working well, and requiring
25598 Imake to install a package hinders the acceptance of that package on
25599 those hosts.  For example, the Imake template and configuration files
25600 might not be installed properly on a host, or the Imake build procedure
25601 might wrongly assume that all source files are in one big directory
25602 tree, or the Imake configuration might assume one compiler whereas the
25603 package or the installer needs to use another, or there might be a
25604 version mismatch between the Imake expected by the package and the Imake
25605 supported by the host.  These problems are much rarer with Autoconf,
25606 where each package comes with its own independent configuration
25607 processor.
25609 Also, Imake often suffers from unexpected interactions between
25610 @command{make} and the installer's C preprocessor.  The fundamental problem
25611 here is that the C preprocessor was designed to preprocess C programs,
25612 not makefiles.  This is much less of a problem with Autoconf,
25613 which uses the general-purpose preprocessor M4, and where the
25614 package's author (rather than the installer) does the preprocessing in a
25615 standard way.
25616 @end quotation
25619 Finally, Mark Eichin notes:
25621 @quotation
25622 Imake isn't all that extensible, either.  In order to add new features to
25623 Imake, you need to provide your own project template, and duplicate most
25624 of the features of the existing one.  This means that for a sophisticated
25625 project, using the vendor-provided Imake templates fails to provide any
25626 leverage---since they don't cover anything that your own project needs
25627 (unless it is an X11 program).
25629 On the other side, though:
25631 The one advantage that Imake has over @command{configure}:
25632 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
25633 than @file{Makefile.in} files.  There is a fix to this, however---at least
25634 for the Kerberos V5 tree, we've modified things to call in common
25635 @file{post.in} and @file{pre.in} makefile fragments for the
25636 entire tree.  This means that a lot of common things don't have to be
25637 duplicated, even though they normally are in @command{configure} setups.
25638 @end quotation
25641 @node Defining Directories
25642 @section How Do I @code{#define} Installation Directories?
25644 @display
25645 My program needs library files, installed in @code{datadir} and
25646 similar.  If I use
25648 @example
25649 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
25650   [Define to the read-only architecture-independent
25651    data directory.])
25652 @end example
25654 @noindent
25655 I get
25657 @example
25658 #define DATADIR "$@{prefix@}/share"
25659 @end example
25660 @end display
25662 As already explained, this behavior is on purpose, mandated by the
25663 GNU Coding Standards, see @ref{Installation Directory
25664 Variables}.  There are several means to achieve a similar goal:
25666 @itemize @minus
25667 @item
25668 Do not use @code{AC_DEFINE} but use your makefile to pass the
25669 actual value of @code{datadir} via compilation flags.
25670 @xref{Installation Directory Variables}, for the details.
25672 @item
25673 This solution can be simplified when compiling a program: you may either
25674 extend the @code{CPPFLAGS}:
25676 @example
25677 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
25678 @end example
25680 @noindent
25681 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
25683 @example
25684 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
25685 @end example
25687 @noindent
25688 Alternatively, create a dedicated header file:
25690 @example
25691 DISTCLEANFILES = myprog-paths.h
25692 myprog-paths.h: Makefile
25693         echo '#define DATADIR "$(datadir)"' >$@@
25694 @end example
25696 @noindent
25697 The gnulib module @samp{configmake} provides such a header with all the
25698 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
25699 Gnulib}.
25701 @item
25702 Use @code{AC_DEFINE} but have @command{configure} compute the literal
25703 value of @code{datadir} and others.  Many people have wrapped macros to
25704 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
25705 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
25706 Archive}.
25708 This solution does not conform to the GNU Coding Standards.
25710 @item
25711 Note that all the previous solutions hard wire the absolute name of
25712 these directories in the executables, which is not a good property.  You
25713 may try to compute the names relative to @code{prefix}, and try to
25714 find @code{prefix} at runtime, this way your package is relocatable.
25715 @end itemize
25718 @node Autom4te Cache
25719 @section What is @file{autom4te.cache}?
25721 @display
25722 What is this directory @file{autom4te.cache}?  Can I safely remove it?
25723 @end display
25725 In the GNU Build System, @file{configure.ac} plays a central
25726 role and is read by many tools: @command{autoconf} to create
25727 @file{configure}, @command{autoheader} to create @file{config.h.in},
25728 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
25729 check the completeness of @file{configure.ac}, @command{autoreconf} to
25730 check the GNU Build System components that are used.  To
25731 ``read @file{configure.ac}'' actually means to compile it with M4,
25732 which can be a long process for complex @file{configure.ac}.
25734 This is why all these tools, instead of running directly M4, invoke
25735 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
25736 a specific demand, stores additional information in
25737 @file{autom4te.cache} for future runs.  For instance, if you run
25738 @command{autoconf}, behind the scenes, @command{autom4te} also
25739 stores information for the other tools, so that when you invoke
25740 @command{autoheader} or @command{automake} etc., reprocessing
25741 @file{configure.ac} is not needed.  The speed up is frequently 30%,
25742 and is increasing with the size of @file{configure.ac}.
25744 But it is and remains being simply a cache: you can safely remove it.
25746 @sp 1
25748 @display
25749 Can I permanently get rid of it?
25750 @end display
25752 The creation of this cache can be disabled from
25753 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
25754 details.  You should be aware that disabling the cache slows down the
25755 Autoconf test suite by 40%.  The more GNU Build System
25756 components are used, the more the cache is useful; for instance
25757 running @samp{autoreconf -f} on the Core Utilities is twice slower without
25758 the cache @emph{although @option{--force} implies that the cache is
25759 not fully exploited}, and eight times slower than without
25760 @option{--force}.
25763 @node Present But Cannot Be Compiled
25764 @section Header Present But Cannot Be Compiled
25766 The most important guideline to bear in mind when checking for
25767 features is to mimic as much as possible the intended use.
25768 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
25769 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
25770 the preprocessor, instead of the compiler, to check for headers.  As a
25771 result, incompatibilities between headers went unnoticed during
25772 configuration, and maintainers finally had to deal with this issue
25773 elsewhere.
25775 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
25776 checks are performed, and @command{configure} complains loudly if the
25777 compiler and the preprocessor do not agree.  However, only the compiler
25778 result is considered.
25780 Consider the following example:
25782 @smallexample
25783 $ @kbd{cat number.h}
25784 typedef int number;
25785 $ @kbd{cat pi.h}
25786 const number pi = 3;
25787 $ @kbd{cat configure.ac}
25788 AC_INIT([Example], [1.0], [bug-example@@example.org])
25789 AC_CHECK_HEADERS([pi.h])
25790 $ @kbd{autoconf -Wall}
25791 $ @kbd{./configure}
25792 checking for gcc... gcc
25793 checking for C compiler default output file name... a.out
25794 checking whether the C compiler works... yes
25795 checking whether we are cross compiling... no
25796 checking for suffix of executables...
25797 checking for suffix of object files... o
25798 checking whether we are using the GNU C compiler... yes
25799 checking whether gcc accepts -g... yes
25800 checking for gcc option to accept ISO C89... none needed
25801 checking how to run the C preprocessor... gcc -E
25802 checking for grep that handles long lines and -e... grep
25803 checking for egrep... grep -E
25804 checking for ANSI C header files... yes
25805 checking for sys/types.h... yes
25806 checking for sys/stat.h... yes
25807 checking for stdlib.h... yes
25808 checking for string.h... yes
25809 checking for memory.h... yes
25810 checking for strings.h... yes
25811 checking for inttypes.h... yes
25812 checking for stdint.h... yes
25813 checking for unistd.h... yes
25814 checking pi.h usability... no
25815 checking pi.h presence... yes
25816 configure: WARNING: pi.h: present but cannot be compiled
25817 configure: WARNING: pi.h:     check for missing prerequisite headers?
25818 configure: WARNING: pi.h: see the Autoconf documentation
25819 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
25820 configure: WARNING: pi.h: proceeding with the compiler's result
25821 configure: WARNING:     ## -------------------------------------- ##
25822 configure: WARNING:     ## Report this to bug-example@@example.org ##
25823 configure: WARNING:     ## -------------------------------------- ##
25824 checking for pi.h... yes
25825 @end smallexample
25827 @noindent
25828 The proper way the handle this case is using the fourth argument
25829 (@pxref{Generic Headers}):
25831 @example
25832 $ @kbd{cat configure.ac}
25833 AC_INIT([Example], [1.0], [bug-example@@example.org])
25834 AC_CHECK_HEADERS([number.h pi.h], [], [],
25835 [[#ifdef HAVE_NUMBER_H
25836 # include <number.h>
25837 #endif
25839 $ @kbd{autoconf -Wall}
25840 $ @kbd{./configure}
25841 checking for gcc... gcc
25842 checking for C compiler default output... a.out
25843 checking whether the C compiler works... yes
25844 checking whether we are cross compiling... no
25845 checking for suffix of executables...
25846 checking for suffix of object files... o
25847 checking whether we are using the GNU C compiler... yes
25848 checking whether gcc accepts -g... yes
25849 checking for gcc option to accept ANSI C... none needed
25850 checking for number.h... yes
25851 checking for pi.h... yes
25852 @end example
25854 See @ref{Particular Headers}, for a list of headers with their
25855 prerequisites.
25857 @node Expanded Before Required
25858 @section Expanded Before Required
25860 @cindex expanded before required
25861 Older versions of Autoconf silently built files with incorrect ordering
25862 between dependent macros if an outer macro first expanded, then later
25863 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
25864 situation no longer generates out-of-order code, but results in
25865 duplicate output and a syntax warning:
25867 @example
25868 $ @kbd{cat configure.ac}
25869 @result{}AC_DEFUN([TESTA], [[echo in A
25870 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
25871 @result{}SEEN_A=:]])
25872 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
25873 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
25874 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
25875 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
25876 @result{}TESTA
25877 @result{}TESTC])
25878 @result{}AC_INIT
25879 @result{}OUTER
25880 @result{}AC_OUTPUT
25881 $ @kbd{autoconf}
25882 @result{}configure.ac:11: warning: AC_REQUIRE:
25883 @result{} `TESTA' was expanded before it was required
25884 @result{}configure.ac:4: TESTB is expanded from...
25885 @result{}configure.ac:6: TESTC is expanded from...
25886 @result{}configure.ac:7: OUTER is expanded from...
25887 @result{}configure.ac:11: the top level
25888 @end example
25890 @noindent
25891 To avoid this warning, decide what purpose the macro in question serves.
25892 If it only needs to be expanded once (for example, if it provides
25893 initialization text used by later macros), then the simplest fix is to
25894 change the macro to be declared with @code{AC_DEFUN_ONCE}
25895 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
25896 newer.  A more portable fix is to change all
25897 instances of direct calls to instead go through @code{AC_REQUIRE}
25898 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
25899 by arguments or by the current definition of other macros in the m4
25900 environment, then the macro should always be directly expanded instead
25901 of required.
25903 For another case study, consider this example trimmed down from an
25904 actual package.  Originally, the package contained shell code and
25905 multiple macro invocations at the top level of @file{configure.ac}:
25907 @example
25908 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25909 foobar=
25910 AC_PROG_CC
25912 @end example
25914 @noindent
25915 but that was getting complex, so the author wanted to offload some of
25916 the text into a new macro in another file included via
25917 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
25918 macro:
25920 @example
25921 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25922 AC_DEFUN([BAR], [
25923 foobar=
25924 AC_PROG_CC
25928 @end example
25930 @noindent
25931 With older versions of Autoconf, the setting of @samp{foobar=} occurs
25932 before the single compiler check, as the author intended.  But with
25933 Autoconf 2.64, this issues the ``expanded before it was required''
25934 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
25935 check, one before @samp{foobar=}, and one after.  To understand why this
25936 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
25937 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
25938 the documented semantics of @code{AC_REQUIRE}, this means that
25939 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
25940 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
25941 use of @samp{foobar=}.  The older versions of Autoconf were broken with
25942 regards to the rules of @code{AC_REQUIRE}, which explains why the code
25943 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
25944 autoconf.  In other words, the author was unknowingly relying on a bug
25945 exploit to get the desired results, and that exploit broke once the bug
25946 was fixed.
25948 So, what recourse does the author have, to restore their intended
25949 semantics of setting @samp{foobar=} prior to a single compiler check,
25950 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
25951 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
25952 there is always the possibility of using the lower-level
25953 @code{m4_define}:
25955 @example
25956 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25957 m4_define([BAR], [
25958 foobar=
25959 AC_PROG_CC
25963 @end example
25965 @noindent
25966 This works great if everything is in the same file.  However, it does
25967 not help in the case where the author wants to have @command{aclocal}
25968 find the definition of @code{BAR} from its own file, since
25969 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
25970 better fix is to recognize that if @code{BAR} also uses
25971 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
25972 to a subsequent require.  Then, by creating yet another helper macro,
25973 the author can once again guarantee a single invocation of
25974 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
25975 author can also use @code{AC_BEFORE} to make sure no other macro
25976 appearing before @code{BAR} has triggered an unwanted expansion of
25977 @code{AC_PROG_CC}.
25979 @example
25980 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25981 AC_DEFUN([BEFORE_CC], [
25982 foobar=
25984 AC_DEFUN([BAR], [
25985 AC_BEFORE([$0], [AC_PROG_CC])dnl
25986 AC_REQUIRE([BEFORE_CC])dnl
25987 AC_REQUIRE([AC_PROG_CC])dnl
25991 @end example
25994 @node Debugging
25995 @section Debugging @command{configure} scripts
25997 While in general, @command{configure} scripts generated by Autoconf
25998 strive to be fairly portable to various systems, compilers, shells, and
25999 other tools, it may still be necessary to debug a failing test, broken
26000 script or makefile, or fix or override an incomplete, faulty, or erroneous
26001 test, especially during macro development.  Failures can occur at all levels,
26002 in M4 syntax or semantics, shell script issues, or due to bugs in the
26003 test or the tools invoked by @command{configure}.  Together with the
26004 rather arcane error message that @command{m4} and @command{make} may
26005 produce when their input contains syntax errors, this can make debugging
26006 rather painful.
26008 Nevertheless, here is a list of hints and strategies that may help:
26010 @itemize
26011 @item
26012 When @command{autoconf} fails, common causes for error include:
26014 @itemize
26015 @item
26016 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26017 Parentheses}),
26019 @item under- or overquoted macro arguments (@pxref{Autoconf
26020 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26021 Macros}),
26023 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26024 Language}).
26025 @end itemize
26027 Typically, it helps to go back to the last working version of the input
26028 and compare the differences for each of these errors.  Another
26029 possibility is to sprinkle pairs of @code{m4_traceon} and
26030 @code{m4_traceoff} judiciously in the code, either without a parameter
26031 or listing some macro names and watch @command{m4} expand its input
26032 verbosely (@pxref{Debugging via autom4te}).
26034 @item
26035 Sometimes @command{autoconf} succeeds but the generated
26036 @command{configure} script has invalid shell syntax.  You can detect this
26037 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26038 If this command fails, the same tips apply, as if @command{autoconf} had
26039 failed.
26041 @item
26042 Debugging @command{configure} script execution may be done by sprinkling
26043 pairs of @code{set -x} and @code{set +x} into the shell script before
26044 and after the region that contains a bug.  Running the whole script with
26045 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26046 @var{shell} may work, but produces lots of output.  Here, it can help to
26047 search for markers like @samp{checking for} a particular test in the
26048 @var{log-file}.
26050 @item
26051 Alternatively, you might use a shell with debugging capabilities like
26052 @uref{http://bashdb.sourceforge.net/, bashdb}.
26054 @item
26055 When @command{configure} tests produce invalid results for your system,
26056 it may be necessary to override them:
26058 @itemize
26059 @item
26060 For programs, tools or libraries variables, preprocessor, compiler, or
26061 linker flags, it is often sufficient to override them at @command{make}
26062 run time with some care (@pxref{Macros and Submakes}).  Since this
26063 normally won't cause @command{configure} to be run again with these
26064 changed settings, it may fail if the changed variable would have caused
26065 different test results from @command{configure}, so this may work only
26066 for simple differences.
26068 @item
26069 Most tests which produce their result in a substituted variable allow to
26070 override the test by setting the variable on the @command{configure}
26071 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26072 @pxref{Particular Systems}).
26074 @item
26075 Many tests store their result in a cache variable (@pxref{Caching
26076 Results}).  This lets you override them either on the
26077 @command{configure} command line as above, or through a primed cache or
26078 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26079 cache variable is documented with a test macro or may be inferred from
26080 @ref{Cache Variable Names}; the precise semantics of undocumented
26081 variables are often internal details, subject to change.
26082 @end itemize
26084 @item
26085 Alternatively, @command{configure} may produce invalid results because
26086 of uncaught programming errors, in your package or in an upstream
26087 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26088 library with a specified function, always check @file{config.log}.  This
26089 will reveal the exact error that produced the failing result: the
26090 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26091 @end itemize
26093 Conversely, as macro author, you can make it easier for users of your
26094 macro:
26096 @itemize
26097 @item
26098 by minimizing dependencies between tests and between test results as far
26099 as possible,
26101 @item
26102 by using @command{make} variables to factorize and allow
26103 override of settings at @command{make} run time,
26105 @item
26106 by honoring the GNU Coding Standards and not overriding flags
26107 reserved for the user except temporarily during @command{configure}
26108 tests,
26110 @item
26111 by not requiring users of your macro to use the cache variables.
26112 Instead, expose the result of the test via @var{run-if-true} and
26113 @var{run-if-false} parameters.  If the result is not a boolean,
26114 then provide it through documented shell variables.
26115 @end itemize
26118 @c ===================================================== History of Autoconf.
26120 @node History
26121 @chapter History of Autoconf
26122 @cindex History of autoconf
26124 @emph{This chapter was written by the original author, David MacKenzie.}
26126 You may be wondering, Why was Autoconf originally written?  How did it
26127 get into its present form?  (Why does it look like gorilla spit?)  If
26128 you're not wondering, then this chapter contains no information useful
26129 to you, and you might as well skip it.  If you @emph{are} wondering,
26130 then let there be light@enddots{}
26132 @menu
26133 * Genesis::                     Prehistory and naming of @command{configure}
26134 * Exodus::                      The plagues of M4 and Perl
26135 * Leviticus::                   The priestly code of portability arrives
26136 * Numbers::                     Growth and contributors
26137 * Deuteronomy::                 Approaching the promises of easy configuration
26138 @end menu
26140 @node Genesis
26141 @section Genesis
26143 In June 1991 I was maintaining many of the GNU utilities for the
26144 Free Software Foundation.  As they were ported to more platforms and
26145 more programs were added, the number of @option{-D} options that users
26146 had to select in the makefile (around 20) became burdensome.
26147 Especially for me---I had to test each new release on a bunch of
26148 different systems.  So I wrote a little shell script to guess some of
26149 the correct settings for the fileutils package, and released it as part
26150 of fileutils 2.0.  That @command{configure} script worked well enough that
26151 the next month I adapted it (by hand) to create similar @command{configure}
26152 scripts for several other GNU utilities packages.  Brian Berliner
26153 also adapted one of my scripts for his CVS revision control system.
26155 Later that summer, I learned that Richard Stallman and Richard Pixley
26156 were developing similar scripts to use in the GNU compiler tools;
26157 so I adapted my @command{configure} scripts to support their evolving
26158 interface: using the file name @file{Makefile.in} as the templates;
26159 adding @samp{+srcdir}, the first option (of many); and creating
26160 @file{config.status} files.
26162 @node Exodus
26163 @section Exodus
26165 As I got feedback from users, I incorporated many improvements, using
26166 Emacs to search and replace, cut and paste, similar changes in each of
26167 the scripts.  As I adapted more GNU utilities packages to use
26168 @command{configure} scripts, updating them all by hand became impractical.
26169 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26170 mail saying that the @command{configure} scripts were great, and asking if
26171 I had a tool for generating them that I could send him.  No, I thought,
26172 but I should!  So I started to work out how to generate them.  And the
26173 journey from the slavery of hand-written @command{configure} scripts to the
26174 abundance and ease of Autoconf began.
26176 Cygnus @command{configure}, which was being developed at around that time,
26177 is table driven; it is meant to deal mainly with a discrete number of
26178 system types with a small number of mainly unguessable features (such as
26179 details of the object file format).  The automatic configuration system
26180 that Brian Fox had developed for Bash takes a similar approach.  For
26181 general use, it seems to me a hopeless cause to try to maintain an
26182 up-to-date database of which features each variant of each operating
26183 system has.  It's easier and more reliable to check for most features on
26184 the fly---especially on hybrid systems that people have hacked on
26185 locally or that have patches from vendors installed.
26187 I considered using an architecture similar to that of Cygnus
26188 @command{configure}, where there is a single @command{configure} script that
26189 reads pieces of @file{configure.in} when run.  But I didn't want to have
26190 to distribute all of the feature tests with every package, so I settled
26191 on having a different @command{configure} made from each
26192 @file{configure.in} by a preprocessor.  That approach also offered more
26193 control and flexibility.
26195 I looked briefly into using the Metaconfig package, by Larry Wall,
26196 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26197 reasons.  The @command{Configure} scripts it produces are interactive,
26198 which I find quite inconvenient; I didn't like the ways it checked for
26199 some features (such as library functions); I didn't know that it was
26200 still being maintained, and the @command{Configure} scripts I had
26201 seen didn't work on many modern systems (such as System V R4 and NeXT);
26202 it wasn't flexible in what it could do in response to a feature's
26203 presence or absence; I found it confusing to learn; and it was too big
26204 and complex for my needs (I didn't realize then how much Autoconf would
26205 eventually have to grow).
26207 I considered using Perl to generate my style of @command{configure}
26208 scripts, but decided that M4 was better suited to the job of simple
26209 textual substitutions: it gets in the way less, because output is
26210 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26211 the GNU extensions to M4.)  Also, some of my friends at the
26212 University of Maryland had recently been putting M4 front ends on
26213 several programs, including @code{tvtwm}, and I was interested in trying
26214 out a new language.
26216 @node Leviticus
26217 @section Leviticus
26219 Since my @command{configure} scripts determine the system's capabilities
26220 automatically, with no interactive user intervention, I decided to call
26221 the program that generates them Autoconfig.  But with a version number
26222 tacked on, that name would be too long for old Unix file systems,
26223 so I shortened it to Autoconf.
26225 In the fall of 1991 I called together a group of fellow questers after
26226 the Holy Grail of portability (er, that is, alpha testers) to give me
26227 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26228 and continued to add features and improve the techniques used in the
26229 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26230 with the idea of making an Autoconf shell script to run M4
26231 and check for unresolved macro calls; Richard Pixley, who suggested
26232 running the compiler instead of searching the file system to find
26233 include files and symbols, for more accurate results; Karl Berry, who
26234 got Autoconf to configure @TeX{} and added the macro index to the
26235 documentation; and Ian Lance Taylor, who added support for creating a C
26236 header file as an alternative to putting @option{-D} options in a
26237 makefile, so he could use Autoconf for his UUCP package.
26238 The alpha testers cheerfully adjusted their files again and again as the
26239 names and calling conventions of the Autoconf macros changed from
26240 release to release.  They all contributed many specific checks, great
26241 ideas, and bug fixes.
26243 @node Numbers
26244 @section Numbers
26246 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26247 and converted many GNU packages to use it.  I was surprised by how
26248 positive the reaction to it was.  More people started using it than I
26249 could keep track of, including people working on software that wasn't
26250 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26251 Autoconf continued to improve rapidly, as many people using the
26252 @command{configure} scripts reported problems they encountered.
26254 Autoconf turned out to be a good torture test for M4 implementations.
26255 Unix M4 started to dump core because of the length of the
26256 macros that Autoconf defined, and several bugs showed up in GNU
26257 M4 as well.  Eventually, we realized that we needed to use some
26258 features that only GNU M4 has.  4.3BSD M4, in
26259 particular, has an impoverished set of builtin macros; the System V
26260 version is better, but still doesn't provide everything we need.
26262 More development occurred as people put Autoconf under more stresses
26263 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26264 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26265 invalid arguments.  Jim Blandy bravely coerced it into configuring
26266 GNU Emacs, laying the groundwork for several later improvements.
26267 Roland McGrath got it to configure the GNU C Library, wrote the
26268 @command{autoheader} script to automate the creation of C header file
26269 templates, and added a @option{--verbose} option to @command{configure}.
26270 Noah Friedman added the @option{--autoconf-dir} option and
26271 @code{AC_MACRODIR} environment variable.  (He also coined the term
26272 @dfn{autoconfiscate} to mean ``adapt a software package to use
26273 Autoconf''.)  Roland and Noah improved the quoting protection in
26274 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26275 dealing with portability problems from February through June, 1993.
26277 @node Deuteronomy
26278 @section Deuteronomy
26280 A long wish list for major features had accumulated, and the effect of
26281 several years of patching by various people had left some residual
26282 cruft.  In April 1994, while working for Cygnus Support, I began a major
26283 revision of Autoconf.  I added most of the features of the Cygnus
26284 @command{configure} that Autoconf had lacked, largely by adapting the
26285 relevant parts of Cygnus @command{configure} with the help of david zuhn
26286 and Ken Raeburn.  These features include support for using
26287 @file{config.sub}, @file{config.guess}, @option{--host}, and
26288 @option{--target}; making links to files; and running @command{configure}
26289 scripts in subdirectories.  Adding these features enabled Ken to convert
26290 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26291 Autoconf.
26293 I added more features in response to other peoples' requests.  Many
26294 people had asked for @command{configure} scripts to share the results of
26295 the checks between runs, because (particularly when configuring a large
26296 source tree, like Cygnus does) they were frustratingly slow.  Mike
26297 Haertel suggested adding site-specific initialization scripts.  People
26298 distributing software that had to unpack on MS-DOS asked for a way to
26299 override the @file{.in} extension on the file names, which produced file
26300 names like @file{config.h.in} containing two dots.  Jim Avera did an
26301 extensive examination of the problems with quoting in @code{AC_DEFINE}
26302 and @code{AC_SUBST}; his insights led to significant improvements.
26303 Richard Stallman asked that compiler output be sent to @file{config.log}
26304 instead of @file{/dev/null}, to help people debug the Emacs
26305 @command{configure} script.
26307 I made some other changes because of my dissatisfaction with the quality
26308 of the program.  I made the messages showing results of the checks less
26309 ambiguous, always printing a result.  I regularized the names of the
26310 macros and cleaned up coding style inconsistencies.  I added some
26311 auxiliary utilities that I had developed to help convert source code
26312 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26313 the macros not interrupt each others' messages.  (That feature revealed
26314 some performance bottlenecks in GNU M4, which he hastily
26315 corrected!)  I reorganized the documentation around problems people want
26316 to solve.  And I began a test suite, because experience had shown that
26317 Autoconf has a pronounced tendency to regress when we change it.
26319 Again, several alpha testers gave invaluable feedback, especially
26320 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26321 and Mark Eichin.
26323 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26324 have free time again.  I think.  Yeah, right.)
26327 @c ========================================================== Appendices
26330 @node GNU Free Documentation License
26331 @appendix GNU Free Documentation License
26333 @include fdl.texi
26335 @node Indices
26336 @appendix Indices
26338 @menu
26339 * Environment Variable Index::  Index of environment variables used
26340 * Output Variable Index::       Index of variables set in output files
26341 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26342 * Cache Variable Index::        Index of documented cache variables
26343 * Autoconf Macro Index::        Index of Autoconf macros
26344 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26345 * Autotest Macro Index::        Index of Autotest macros
26346 * Program & Function Index::    Index of those with portability problems
26347 * Concept Index::               General index
26348 @end menu
26350 @node Environment Variable Index
26351 @appendixsec Environment Variable Index
26353 This is an alphabetical list of the environment variables that might
26354 influence Autoconf checks.
26356 @printindex ev
26358 @node Output Variable Index
26359 @appendixsec Output Variable Index
26361 This is an alphabetical list of the variables that Autoconf can
26362 substitute into files that it creates, typically one or more
26363 makefiles.  @xref{Setting Output Variables}, for more information
26364 on how this is done.
26366 @printindex ov
26368 @node Preprocessor Symbol Index
26369 @appendixsec Preprocessor Symbol Index
26371 This is an alphabetical list of the C preprocessor symbols that the
26372 Autoconf macros define.  To work with Autoconf, C source code needs to
26373 use these names in @code{#if} or @code{#ifdef} directives.
26375 @printindex cv
26377 @node Cache Variable Index
26378 @appendixsec Cache Variable Index
26380 This is an alphabetical list of documented cache variables used
26381 by macros defined in Autoconf.  Autoconf macros may use additional cache
26382 variables internally.
26383 @ifset shortindexflag
26384 To make the list easier to use, the variables are listed without their
26385 preceding @samp{ac_cv_}.
26386 @end ifset
26388 @printindex CA
26390 @node Autoconf Macro Index
26391 @appendixsec Autoconf Macro Index
26393 This is an alphabetical list of the Autoconf macros.
26394 @ifset shortindexflag
26395 To make the list easier to use, the macros are listed without their
26396 preceding @samp{AC_}.
26397 @end ifset
26399 @printindex AC
26401 @node M4 Macro Index
26402 @appendixsec M4 Macro Index
26404 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26405 @ifset shortindexflag
26406 To make the list easier to use, the macros are listed without their
26407 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26408 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26409 names.
26410 @end ifset
26412 @printindex MS
26414 @node Autotest Macro Index
26415 @appendixsec Autotest Macro Index
26417 This is an alphabetical list of the Autotest macros.
26418 @ifset shortindexflag
26419 To make the list easier to use, the macros are listed without their
26420 preceding @samp{AT_}.
26421 @end ifset
26423 @printindex AT
26425 @node Program & Function Index
26426 @appendixsec Program and Function Index
26428 This is an alphabetical list of the programs and functions whose
26429 portability is discussed in this document.
26431 @printindex pr
26433 @node Concept Index
26434 @appendixsec Concept Index
26436 This is an alphabetical list of the files, tools, and concepts
26437 introduced in this document.
26439 @printindex cp
26441 @bye
26443 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26444 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26445 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26446 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26447 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26448 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26449 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26450 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26451 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26452 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26453 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26454 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26455 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26456 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26457 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26458 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26459 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26460 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26461 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26462 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26463 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26464 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26465 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26466 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26467 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26468 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26469 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26470 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26471 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26472 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26473 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26474 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26475 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26476 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26477 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26478 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26479 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26480 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26481 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26482 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26483 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26484 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26485 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26486 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26487 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26488 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
26489 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26490 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26491 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26492 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26493 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26494 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26495 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26496 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26497 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26498 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26499 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26500 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26501 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26502 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26503 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26504 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26505 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26506 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26507 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26508 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26509 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26510 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26511 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26512 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26513 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26514 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26515 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26516 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26517 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26518 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26519 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26520 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26521 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26522 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26523 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26524 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26525 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26526 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26527 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26528 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26529 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26530 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26531 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26532 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26533 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
26534 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26536 @c Local Variables:
26537 @c fill-column: 72
26538 @c ispell-local-dictionary: "american"
26539 @c indent-tabs-mode: nil
26540 @c whitespace-check-buffer-indent: nil
26541 @c End: