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
12
13@c @ovar(ARG)
14@c ----------
15@c The ARG is an optional argument.  To be used for macro arguments in
16@c their documentation (@defmac).
17@macro ovar{varname}
18@r{[}@var{\varname\}@r{]}
19@end macro
20
21@c @dvar(ARG, DEFAULT)
22@c -------------------
23@c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24@c for macro arguments in their documentation (@defmac).
25@macro dvar{varname, default}
26@r{[}@var{\varname\} = @samp{\default\}@r{]}
27@end macro
28
29@c Handling the indexes with Texinfo yields several different problems.
30@c
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.
39@c
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''.
44@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.
48
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
70
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
77
78@c @acindex{MACRO}
79@c ---------------
80@c Registering an AC_\MACRO\.
81@ifset shortindexflag
82@macro acindex{macro}
83@ACindex \macro\
84@c
85@end macro
86@end ifset
87@ifclear shortindexflag
88@macro acindex{macro}
89@ACindex AC_\macro\
90@end macro
91@end ifclear
92
93@c @ahindex{MACRO}
94@c ---------------
95@c Registering an AH_\MACRO\.
96@macro ahindex{macro}
97@ACindex AH_\macro\
98@c
99@end macro
100
101@c @asindex{MACRO}
102@c ---------------
103@c Registering an AS_\MACRO\.
104@ifset shortindexflag
105@macro asindex{macro}
106@MSindex \macro\
107@c
108@end macro
109@end ifset
110@ifclear shortindexflag
111@macro asindex{macro}
112@MSindex AS_\macro\
113@end macro
114@end ifclear
115
116@c @atindex{MACRO}
117@c ---------------
118@c Registering an AT_\MACRO\.
119@ifset shortindexflag
120@macro atindex{macro}
121@ATindex \macro\
122@c
123@end macro
124@end ifset
125@ifclear shortindexflag
126@macro atindex{macro}
127@ATindex AT_\macro\
128@end macro
129@end ifclear
130
131@c @auindex{MACRO}
132@c ---------------
133@c Registering an AU_\MACRO\.
134@macro auindex{macro}
135@ACindex AU_\macro\
136@c
137@end macro
138
139@c @hdrindex{MACRO}
140@c ----------------
141@c Indexing a header.
142@macro hdrindex{macro}
143@prindex @file{\macro\}
144@c
145@end macro
146
147@c @msindex{MACRO}
148@c ---------------
149@c Registering an m4_\MACRO\.
150@ifset shortindexflag
151@macro msindex{macro}
152@MSindex \macro\
153@c
154@end macro
155@end ifset
156@ifclear shortindexflag
157@macro msindex{macro}
158@MSindex m4_\macro\
159@end macro
160@end ifclear
161
162
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
176
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.
180
181@c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
182@c
183@c   ! No room for a new @write .
184@c   l.112 @defcodeindex fu
185@c
186@c   so don't define yet another one :(  Just put some tags before each
187@c   @prindex which is actually a @funindex.
188@c
189@c   @defcodeindex fu
190@c
191@c
192@c   @c Put the programs and functions into their own index.
193@c   @syncodeindex fu pr
194
195@comment %**end of header
196@comment ========================================================
197
198@copying
199
200This manual (@value{UPDATED}) is for GNU Autoconf
201(version @value{VERSION}),
202a package for creating scripts to configure source code packages using
203templates and an M4 macro package.
204
205Copyright @copyright{} 1992-1996, 1998-2012 Free Software Foundation,
206Inc.
207
208@quotation
209Permission is granted to copy, distribute and/or modify this document
210under the terms of the GNU Free Documentation License,
211Version 1.3 or any later version published by the Free Software
212Foundation; with no Invariant Sections, no Front-Cover texts, and
213no Back-Cover Texts.  A copy of the license is included in the section
214entitled ``GNU Free Documentation License.''
215@end quotation
216@end copying
217
218
219
220@dircategory Programming & development tools
221@direntry
222* Autoconf: (autoconf).         Create source code configuration scripts.
223@end direntry
224
225@titlepage
226@title Autoconf
227@subtitle Creating Automatic Configuration Scripts
228@subtitle for version @value{VERSION}, @value{UPDATED}
229@author David MacKenzie
230@author Ben Elliston
231@author Akim Demaille
232@page
233@vskip 0pt plus 1filll
234@insertcopying
235@end titlepage
236
237@contents
238
239
240@ifnottex
241@node Top
242@top Autoconf
243@insertcopying
244@end ifnottex
245
246@c The master menu, created with texinfo-master-menu, goes here.
247
248@menu
249* Introduction::                Autoconf's purpose, strengths, and weaknesses
250* The GNU Build System::        A set of tools for portable software packages
251* Making configure Scripts::    How to organize and produce Autoconf scripts
252* Setup::                       Initialization and output
253* Existing Tests::              Macros that check for particular features
254* Writing Tests::               How to write new feature checks
255* Results::                     What to do with results from feature checks
256* Programming in M4::           Layers on top of which Autoconf is written
257* Programming in M4sh::         Shell portability layer
258* Writing Autoconf Macros::     Adding new macros to Autoconf
259* Portable Shell::              Shell script portability pitfalls
260* Portable Make::               Makefile portability pitfalls
261* Portable C and C++::          C and C++ portability pitfalls
262* Manual Configuration::        Selecting features that can't be guessed
263* Site Configuration::          Local defaults for @command{configure}
264* Running configure Scripts::   How to use the Autoconf output
265* config.status Invocation::    Recreating a configuration
266* Obsolete Constructs::         Kept for backward compatibility
267* Using Autotest::              Creating portable test suites
268* FAQ::                         Frequent Autoconf Questions, with answers
269* History::                     History of Autoconf
270* GNU Free Documentation License::  License for copying this manual
271* Indices::                     Indices of symbols, concepts, etc.
272
273@detailmenu
274 --- The Detailed Node Listing ---
275
276The GNU Build System
277
278* Automake::                    Escaping makefile hell
279* Gnulib::                      The GNU portability library
280* Libtool::                     Building libraries portably
281* Pointers::                    More info on the GNU build system
282
283Making @command{configure} Scripts
284
285* Writing Autoconf Input::      What to put in an Autoconf input file
286* autoscan Invocation::         Semi-automatic @file{configure.ac} writing
287* ifnames Invocation::          Listing the conditionals in source code
288* autoconf Invocation::         How to create configuration scripts
289* autoreconf Invocation::       Remaking multiple @command{configure} scripts
290
291Writing @file{configure.ac}
292
293* Shell Script Compiler::       Autoconf as solution of a problem
294* Autoconf Language::           Programming in Autoconf
295* Autoconf Input Layout::       Standard organization of @file{configure.ac}
296
297Initialization and Output Files
298
299* Initializing configure::      Option processing etc.
300* Versioning::                  Dealing with Autoconf versions
301* Notices::                     Copyright, version numbers in @command{configure}
302* Input::                       Where Autoconf should find files
303* Output::                      Outputting results from the configuration
304* Configuration Actions::       Preparing the output based on results
305* Configuration Files::         Creating output files
306* Makefile Substitutions::      Using output variables in makefiles
307* Configuration Headers::       Creating a configuration header file
308* Configuration Commands::      Running arbitrary instantiation commands
309* Configuration Links::         Links depending on the configuration
310* Subdirectories::              Configuring independent packages together
311* Default Prefix::              Changing the default installation prefix
312
313Substitutions in Makefiles
314
315* Preset Output Variables::     Output variables that are always set
316* Installation Directory Variables::  Other preset output variables
317* Changed Directory Variables::  Warnings about @file{datarootdir}
318* Build Directories::           Supporting multiple concurrent compiles
319* Automatic Remaking::          Makefile rules for configuring
320
321Configuration Header Files
322
323* Header Templates::            Input for the configuration headers
324* autoheader Invocation::       How to create configuration templates
325* Autoheader Macros::           How to specify CPP templates
326
327Existing Tests
328
329* Common Behavior::             Macros' standard schemes
330* Alternative Programs::        Selecting between alternative programs
331* Files::                       Checking for the existence of files
332* Libraries::                   Library archives that might be missing
333* Library Functions::           C library functions that might be missing
334* Header Files::                Header files that might be missing
335* Declarations::                Declarations that may be missing
336* Structures::                  Structures or members that might be missing
337* Types::                       Types that might be missing
338* Compilers and Preprocessors::  Checking for compiling programs
339* System Services::             Operating system services
340* Posix Variants::              Special kludges for specific Posix variants
341* Erlang Libraries::            Checking for the existence of Erlang libraries
342
343Common Behavior
344
345* Standard Symbols::            Symbols defined by the macros
346* Default Includes::            Includes used by the generic macros
347
348Alternative Programs
349
350* Particular Programs::         Special handling to find certain programs
351* Generic Programs::            How to find other programs
352
353Library Functions
354
355* Function Portability::        Pitfalls with usual functions
356* Particular Functions::        Special handling to find certain functions
357* Generic Functions::           How to find other functions
358
359Header Files
360
361* Header Portability::          Collected knowledge on common headers
362* Particular Headers::          Special handling to find certain headers
363* Generic Headers::             How to find other headers
364
365Declarations
366
367* Particular Declarations::     Macros to check for certain declarations
368* Generic Declarations::        How to find other declarations
369
370Structures
371
372* Particular Structures::       Macros to check for certain structure members
373* Generic Structures::          How to find other structure members
374
375Types
376
377* Particular Types::            Special handling to find certain types
378* Generic Types::               How to find other types
379
380Compilers and Preprocessors
381
382* Specific Compiler Characteristics::  Some portability issues
383* Generic Compiler Characteristics::  Language independent tests and features
384* C Compiler::                  Checking its characteristics
385* C++ Compiler::                Likewise
386* Objective C Compiler::        Likewise
387* Objective C++ Compiler::      Likewise
388* Erlang Compiler and Interpreter::  Likewise
389* Fortran Compiler::            Likewise
390* Go Compiler::                 Likewise
391
392Writing Tests
393
394* Language Choice::             Selecting which language to use for testing
395* Writing Test Programs::       Forging source files for compilers
396* Running the Preprocessor::    Detecting preprocessor symbols
397* Running the Compiler::        Detecting language or header features
398* Running the Linker::          Detecting library features
399* Runtime::                     Testing for runtime features
400* Systemology::                 A zoology of operating systems
401* Multiple Cases::              Tests for several possible values
402
403Writing Test Programs
404
405* Guidelines::                  General rules for writing test programs
406* Test Functions::              Avoiding pitfalls in test programs
407* Generating Sources::          Source program boilerplate
408
409Results of Tests
410
411* Defining Symbols::            Defining C preprocessor symbols
412* Setting Output Variables::    Replacing variables in output files
413* Special Chars in Variables::  Characters to beware of in variables
414* Caching Results::             Speeding up subsequent @command{configure} runs
415* Printing Messages::           Notifying @command{configure} users
416
417Caching Results
418
419* Cache Variable Names::        Shell variables used in caches
420* Cache Files::                 Files @command{configure} uses for caching
421* Cache Checkpointing::         Loading and saving the cache file
422
423Programming in M4
424
425* M4 Quotation::                Protecting macros from unwanted expansion
426* Using autom4te::              The Autoconf executables backbone
427* Programming in M4sugar::      Convenient pure M4 macros
428* Debugging via autom4te::      Figuring out what M4 was doing
429
430M4 Quotation
431
432* Active Characters::           Characters that change the behavior of M4
433* One Macro Call::              Quotation and one macro call
434* Quoting and Parameters::      M4 vs. shell parameters
435* Quotation and Nested Macros::  Macros calling macros
436* Changequote is Evil::         Worse than INTERCAL: M4 + changequote
437* Quadrigraphs::                Another way to escape special characters
438* Balancing Parentheses::       Dealing with unbalanced parentheses
439* Quotation Rule Of Thumb::     One parenthesis, one quote
440
441Using @command{autom4te}
442
443* autom4te Invocation::         A GNU M4 wrapper
444* Customizing autom4te::        Customizing the Autoconf package
445
446Programming in M4sugar
447
448* Redefined M4 Macros::         M4 builtins changed in M4sugar
449* Diagnostic Macros::           Diagnostic messages from M4sugar
450* Diversion support::           Diversions in M4sugar
451* Conditional constructs::      Conditions in M4
452* Looping constructs::          Iteration in M4
453* Evaluation Macros::           More quotation and evaluation control
454* Text processing Macros::      String manipulation in M4
455* Number processing Macros::    Arithmetic computation in M4
456* Set manipulation Macros::     Set manipulation in M4
457* Forbidden Patterns::          Catching unexpanded macros
458
459Programming in M4sh
460
461* Common Shell Constructs::     Portability layer for common shell constructs
462* Polymorphic Variables::       Support for indirect variable names
463* Initialization Macros::       Macros to establish a sane shell environment
464* File Descriptor Macros::      File descriptor macros for input and output
465
466Writing Autoconf Macros
467
468* Macro Definitions::           Basic format of an Autoconf macro
469* Macro Names::                 What to call your new macros
470* Reporting Messages::          Notifying @command{autoconf} users
471* Dependencies Between Macros::  What to do when macros depend on other macros
472* Obsoleting Macros::           Warning about old ways of doing things
473* Coding Style::                Writing Autoconf macros @`a la Autoconf
474
475Dependencies Between Macros
476
477* Prerequisite Macros::         Ensuring required information
478* Suggested Ordering::          Warning about possible ordering problems
479* One-Shot Macros::             Ensuring a macro is called only once
480
481Portable Shell Programming
482
483* Shellology::                  A zoology of shells
484* Invoking the Shell::          Invoking the shell as a command
485* Here-Documents::              Quirks and tricks
486* File Descriptors::            FDs and redirections
487* Signal Handling::             Shells, signals, and headaches
488* File System Conventions::     File names
489* Shell Pattern Matching::      Pattern matching
490* Shell Substitutions::         Variable and command expansions
491* Assignments::                 Varying side effects of assignments
492* Parentheses::                 Parentheses in shell scripts
493* Slashes::                     Slashes in shell scripts
494* Special Shell Variables::     Variables you should not change
495* Shell Functions::             What to look out for if you use them
496* Limitations of Builtins::     Portable use of not so portable /bin/sh
497* Limitations of Usual Tools::  Portable use of portable tools
498
499Portable Make Programming
500
501* $< in Ordinary Make Rules::   $< in ordinary rules
502* Failure in Make Rules::       Failing portably in rules
503* Special Chars in Names::      Special Characters in Macro Names
504* Backslash-Newline-Empty::     Empty lines after backslash-newline
505* Backslash-Newline Comments::  Spanning comments across line boundaries
506* Long Lines in Makefiles::     Line length limitations
507* Macros and Submakes::         @code{make macro=value} and submakes
508* The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
509* The Make Macro SHELL::        @code{$(SHELL)} portability issues
510* Parallel Make::               Parallel @command{make} quirks
511* Comments in Make Rules::      Other problems with Make comments
512* Newlines in Make Rules::      Using literal newlines in rules
513* Comments in Make Macros::     Other problems with Make comments in macros
514* Trailing whitespace in Make Macros::  Macro substitution problems
515* Command-line Macros and whitespace::  Whitespace trimming of values
516* obj/ and Make::               Don't name a subdirectory @file{obj}
517* make -k Status::              Exit status of @samp{make -k}
518* VPATH and Make::              @code{VPATH} woes
519* Single Suffix Rules::         Single suffix rules and separated dependencies
520* Timestamps and Make::         Subsecond timestamp resolution
521
522@code{VPATH} and Make
523
524* Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
525* VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
526* $< in Explicit Rules::        @code{$<} does not work in ordinary rules
527* Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
528* Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
529* Make Target Lookup::          More details about @code{VPATH} lookup
530
531Portable C and C++ Programming
532
533* Varieties of Unportability::  How to make your programs unportable
534* Integer Overflow::            When integers get too large
535* Preprocessor Arithmetic::     @code{#if} expression problems
536* Null Pointers::               Properties of null pointers
537* Buffer Overruns::             Subscript errors and the like
538* Volatile Objects::            @code{volatile} and signals
539* Floating Point Portability::  Portable floating-point arithmetic
540* Exiting Portably::            Exiting and the exit status
541
542Integer Overflow
543
544* Integer Overflow Basics::     Why integer overflow is a problem
545* Signed Overflow Examples::    Examples of code assuming wraparound
546* Optimization and Wraparound::  Optimizations that break uses of wraparound
547* Signed Overflow Advice::      Practical advice for signed overflow issues
548* Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
549
550Manual Configuration
551
552* Specifying Target Triplets::  Specifying target triplets
553* Canonicalizing::              Getting the canonical system type
554* Using System Type::           What to do with the system type
555
556Site Configuration
557
558* Help Formatting::             Customizing @samp{configure --help}
559* External Software::           Working with other optional software
560* Package Options::             Selecting optional features
561* Pretty Help Strings::         Formatting help string
562* Option Checking::             Controlling checking of @command{configure} options
563* Site Details::                Configuring site details
564* Transforming Names::          Changing program names when installing
565* Site Defaults::               Giving @command{configure} local defaults
566
567Transforming Program Names When Installing
568
569* Transformation Options::      @command{configure} options to transform names
570* Transformation Examples::     Sample uses of transforming names
571* Transformation Rules::        Makefile uses of transforming names
572
573Running @command{configure} Scripts
574
575* Basic Installation::          Instructions for typical cases
576* Compilers and Options::       Selecting compilers and optimization
577* Multiple Architectures::      Compiling for multiple architectures at once
578* Installation Names::          Installing in different directories
579* Optional Features::           Selecting optional features
580* Particular Systems::          Particular systems
581* System Type::                 Specifying the system type
582* Sharing Defaults::            Setting site-wide defaults for @command{configure}
583* Defining Variables::          Specifying the compiler etc.
584* configure Invocation::        Changing how @command{configure} runs
585
586Obsolete Constructs
587
588* Obsolete config.status Use::  Obsolete convention for @command{config.status}
589* acconfig Header::             Additional entries in @file{config.h.in}
590* autoupdate Invocation::       Automatic update of @file{configure.ac}
591* Obsolete Macros::             Backward compatibility macros
592* Autoconf 1::                  Tips for upgrading your files
593* Autoconf 2.13::               Some fresher tips
594
595Upgrading From Version 1
596
597* Changed File Names::          Files you might rename
598* Changed Makefiles::           New things to put in @file{Makefile.in}
599* Changed Macros::              Macro calls you might replace
600* Changed Results::             Changes in how to check test results
601* Changed Macro Writing::       Better ways to write your own macros
602
603Upgrading From Version 2.13
604
605* Changed Quotation::           Broken code which used to work
606* New Macros::                  Interaction with foreign macros
607* Hosts and Cross-Compilation::  Bugward compatibility kludges
608* AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
609* AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
610
611Generating Test Suites with Autotest
612
613* Using an Autotest Test Suite::  Autotest and the user
614* Writing Testsuites::          Autotest macros
615* testsuite Invocation::        Running @command{testsuite} scripts
616* Making testsuite Scripts::    Using autom4te to create @command{testsuite}
617
618Using an Autotest Test Suite
619
620* testsuite Scripts::           The concepts of Autotest
621* Autotest Logs::               Their contents
622
623Frequent Autoconf Questions, with answers
624
625* Distributing::                Distributing @command{configure} scripts
626* Why GNU M4::                  Why not use the standard M4?
627* Bootstrapping::               Autoconf and GNU M4 require each other?
628* Why Not Imake::               Why GNU uses @command{configure} instead of Imake
629* Defining Directories::        Passing @code{datadir} to program
630* Autom4te Cache::              What is it?  Can I remove it?
631* Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
632* Expanded Before Required::    Expanded Before Required
633* Debugging::                   Debugging @command{configure} scripts
634
635History of Autoconf
636
637* Genesis::                     Prehistory and naming of @command{configure}
638* Exodus::                      The plagues of M4 and Perl
639* Leviticus::                   The priestly code of portability arrives
640* Numbers::                     Growth and contributors
641* Deuteronomy::                 Approaching the promises of easy configuration
642
643Indices
644
645* Environment Variable Index::  Index of environment variables used
646* Output Variable Index::       Index of variables set in output files
647* Preprocessor Symbol Index::   Index of C preprocessor symbols defined
648* Cache Variable Index::        Index of documented cache variables
649* Autoconf Macro Index::        Index of Autoconf macros
650* M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
651* Autotest Macro Index::        Index of Autotest macros
652* Program & Function Index::    Index of those with portability problems
653* Concept Index::               General index
654
655@end detailmenu
656@end menu
657
658@c ============================================================= Introduction.
659
660@node Introduction
661@chapter Introduction
662@cindex Introduction
663
664@flushright
665A physicist, an engineer, and a computer scientist were discussing the
666nature of God.  ``Surely a Physicist,'' said the physicist, ``because
667early in the Creation, God made Light; and you know, Maxwell's
668equations, the dual nature of electromagnetic waves, the relativistic
669consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
670before making Light, God split the Chaos into Land and Water; it takes a
671hell of an engineer to handle that big amount of mud, and orderly
672separation of solids from liquids@enddots{}'' The computer scientist
673shouted: ``And the Chaos, where do you think it was coming from, hmm?''
674
675---Anonymous
676@end flushright
677@c (via Franc,ois Pinard)
678
679Autoconf is a tool for producing shell scripts that automatically
680configure software source code packages to adapt to many kinds of
681Posix-like systems.  The configuration scripts produced by Autoconf
682are independent of Autoconf when they are run, so their users do not
683need to have Autoconf.
684
685The configuration scripts produced by Autoconf require no manual user
686intervention when run; they do not normally even need an argument
687specifying the system type.  Instead, they individually test for the
688presence of each feature that the software package they are for might need.
689(Before each check, they print a one-line message stating what they are
690checking for, so the user doesn't get too bored while waiting for the
691script to finish.)  As a result, they deal well with systems that are
692hybrids or customized from the more common Posix variants.  There is
693no need to maintain files that list the features supported by each
694release of each variant of Posix.
695
696For each software package that Autoconf is used with, it creates a
697configuration script from a template file that lists the system features
698that the package needs or can use.  After the shell code to recognize
699and respond to a system feature has been written, Autoconf allows it to
700be shared by many software packages that can use (or need) that feature.
701If it later turns out that the shell code needs adjustment for some
702reason, it needs to be changed in only one place; all of the
703configuration scripts can be regenerated automatically to take advantage
704of the updated code.
705
706@c "Those who do not understand Unix are condemned to reinvent it, poorly."
707@c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
708Those who do not understand Autoconf are condemned to reinvent it, poorly.
709The primary goal of Autoconf is making the @emph{user's} life easier;
710making the @emph{maintainer's} life easier is only a secondary goal.
711Put another way, the primary goal is not to make the generation of
712@file{configure} automatic for package maintainers (although patches
713along that front are welcome, since package maintainers form the user
714base of Autoconf); rather, the goal is to make @file{configure}
715painless, portable, and predictable for the end user of each
716@dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
717successful at its goal --- most complaints to the Autoconf list are
718about difficulties in writing Autoconf input, and not in the behavior of
719the resulting @file{configure}.  Even packages that don't use Autoconf
720will generally provide a @file{configure} script, and the most common
721complaint about these alternative home-grown scripts is that they fail
722to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
723standards, The GNU Coding Standards}) that users
724have come to expect from Autoconf-generated @file{configure} scripts.
725
726The Metaconfig package is similar in purpose to Autoconf, but the
727scripts it produces require manual user intervention, which is quite
728inconvenient when configuring large source trees.  Unlike Metaconfig
729scripts, Autoconf scripts can support cross-compiling, if some care is
730taken in writing them.
731
732Autoconf does not solve all problems related to making portable
733software packages---for a more complete solution, it should be used in
734concert with other GNU build tools like Automake and
735Libtool.  These other tools take on jobs like the creation of a
736portable, recursive makefile with all of the standard targets,
737linking of shared libraries, and so on.  @xref{The GNU Build System},
738for more information.
739
740Autoconf imposes some restrictions on the names of macros used with
741@code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
742
743Autoconf requires GNU M4 version 1.4.6 or later in order to
744generate the scripts.  It uses features that some versions of M4,
745including GNU M4 1.3, do not have.  Autoconf works better
746with GNU M4 version 1.4.14 or later, though this is not
747required.
748
749@xref{Autoconf 1}, for information about upgrading from version 1.
750@xref{History}, for the story of Autoconf's development.  @xref{FAQ},
751for answers to some common questions about Autoconf.
752
753See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
754Autoconf web page} for up-to-date information, details on the mailing
755lists, pointers to a list of known bugs, etc.
756
757Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
758list}.  Past suggestions are
759@uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
760
761Mail bug reports to @email{bug-autoconf@@gnu.org, the
762Autoconf Bugs mailing list}.  Past bug reports are
763@uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
764
765If possible, first check that your bug is
766not already solved in current development versions, and that it has not
767been reported yet.  Be sure to include all the needed information and a
768short @file{configure.ac} that demonstrates the problem.
769
770Autoconf's development tree is accessible via @command{git}; see the
771@uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
772Summary} for details, or view
773@uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
774repository}.  Anonymous CVS access is also available, see
775@file{README} for more details.  Patches relative to the
776current @command{git} version can be sent for review to the
777@email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
778discussion on prior patches
779@uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
780archived}; and all commits are posted in the read-only
781@email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
782also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
783archived}.
784
785Because of its mission, the Autoconf package itself
786includes only a set of often-used
787macros that have already demonstrated their usefulness.  Nevertheless,
788if you wish to share your macros, or find existing ones, see the
789@uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
790Archive}, which is kindly run by @email{simons@@cryp.to,
791Peter Simons}.
792
793
794@c ================================================= The GNU Build System
795
796@node The GNU Build System
797@chapter The GNU Build System
798@cindex GNU build system
799
800Autoconf solves an important problem---reliable discovery of
801system-specific build and runtime information---but this is only one
802piece of the puzzle for the development of portable software.  To this
803end, the GNU project has developed a suite of integrated
804utilities to finish the job Autoconf started: the GNU build
805system, whose most important components are Autoconf, Automake, and
806Libtool.  In this chapter, we introduce you to those tools, point you
807to sources of more information, and try to convince you to use the
808entire GNU build system for your software.
809
810@menu
811* Automake::                    Escaping makefile hell
812* Gnulib::                      The GNU portability library
813* Libtool::                     Building libraries portably
814* Pointers::                    More info on the GNU build system
815@end menu
816
817@node Automake
818@section Automake
819
820The ubiquity of @command{make} means that a makefile is almost the
821only viable way to distribute automatic build rules for software, but
822one quickly runs into its numerous limitations.  Its lack of
823support for automatic dependency tracking, recursive builds in
824subdirectories, reliable timestamps (e.g., for network file systems), and
825so on, mean that developers must painfully (and often incorrectly)
826reinvent the wheel for each project.  Portability is non-trivial, thanks
827to the quirks of @command{make} on many systems.  On top of all this is the
828manual labor required to implement the many standard targets that users
829have come to expect (@code{make install}, @code{make distclean},
830@code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
831you also have to insert repetitive code in your @file{Makefile.in} to
832recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
833provided by @command{configure}.  Into this mess steps @dfn{Automake}.
834@cindex Automake
835
836Automake allows you to specify your build needs in a @file{Makefile.am}
837file with a vastly simpler and more powerful syntax than that of a plain
838makefile, and then generates a portable @file{Makefile.in} for
839use with Autoconf.  For example, the @file{Makefile.am} to build and
840install a simple ``Hello world'' program might look like:
841
842@example
843bin_PROGRAMS = hello
844hello_SOURCES = hello.c
845@end example
846
847@noindent
848The resulting @file{Makefile.in} (~400 lines) automatically supports all
849the standard targets, the substitutions provided by Autoconf, automatic
850dependency tracking, @code{VPATH} building, and so on.  @command{make}
851builds the @code{hello} program, and @code{make install} installs it
852in @file{/usr/local/bin} (or whatever prefix was given to
853@command{configure}, if not @file{/usr/local}).
854
855The benefits of Automake increase for larger packages (especially ones
856with subdirectories), but even for small programs the added convenience
857and portability can be substantial.  And that's not all@enddots{}
858
859@node Gnulib
860@section Gnulib
861
862GNU software has a well-deserved reputation for running on
863many different types of systems.  While our primary goal is to write
864software for the GNU system, many users and developers have
865been introduced to us through the systems that they were already using.
866
867@cindex Gnulib
868Gnulib is a central location for common GNU code, intended to
869be shared among free software packages.  Its components are typically
870shared at the source level, rather than being a library that gets built,
871installed, and linked against.  The idea is to copy files from Gnulib
872into your own source tree.  There is no distribution tarball; developers
873should just grab source modules from the repository.  The source files
874are available online, under various licenses, mostly GNU
875GPL or GNU LGPL.
876
877Gnulib modules typically contain C source code along with Autoconf
878macros used to configure the source code.  For example, the Gnulib
879@code{stdbool} module implements a @file{stdbool.h} header that nearly
880conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
881This module contains a source file for the replacement header, along
882with an Autoconf macro that arranges to use the replacement header on
883old-fashioned systems.
884
885@node Libtool
886@section Libtool
887
888Often, one wants to build not only programs, but libraries, so that
889other programs can benefit from the fruits of your labor.  Ideally, one
890would like to produce @emph{shared} (dynamically linked) libraries,
891which can be used by multiple programs without duplication on disk or in
892memory and can be updated independently of the linked programs.
893Producing shared libraries portably, however, is the stuff of
894nightmares---each system has its own incompatible tools, compiler flags,
895and magic incantations.  Fortunately, GNU provides a solution:
896@dfn{Libtool}.
897@cindex Libtool
898
899Libtool handles all the requirements of building shared libraries for
900you, and at this time seems to be the @emph{only} way to do so with any
901portability.  It also handles many other headaches, such as: the
902interaction of Make rules with the variable suffixes of
903shared libraries, linking reliably with shared libraries before they are
904installed by the superuser, and supplying a consistent versioning system
905(so that different versions of a library can be installed or upgraded
906without breaking binary compatibility).  Although Libtool, like
907Autoconf, can be used without Automake, it is most simply utilized in
908conjunction with Automake---there, Libtool is used automatically
909whenever shared libraries are needed, and you need not know its syntax.
910
911@node Pointers
912@section Pointers
913
914Developers who are used to the simplicity of @command{make} for small
915projects on a single system might be daunted at the prospect of
916learning to use Automake and Autoconf.  As your software is
917distributed to more and more users, however, you otherwise
918quickly find yourself putting lots of effort into reinventing the
919services that the GNU build tools provide, and making the
920same mistakes that they once made and overcame.  (Besides, since
921you're already learning Autoconf, Automake is a piece of cake.)
922
923There are a number of places that you can go to for more information on
924the GNU build tools.
925
926@itemize @minus
927
928@item Web
929
930The project home pages for
931@uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
932@uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
933@uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
934@uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
935
936@item Automake Manual
937
938@xref{Top, , Automake, automake, GNU Automake}, for more
939information on Automake.
940
941@item Books
942
943The book @cite{GNU Autoconf, Automake and
944Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
945by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
946New Riders), 2000, ISBN 1578701902.} describes the complete GNU
947build environment.  You can also find
948@uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
949
950@end itemize
951
952@c ================================================= Making configure Scripts.
953
954@node Making configure Scripts
955@chapter Making @command{configure} Scripts
956@cindex @file{aclocal.m4}
957@cindex @command{configure}
958
959The configuration scripts that Autoconf produces are by convention
960called @command{configure}.  When run, @command{configure} creates several
961files, replacing configuration parameters in them with appropriate
962values.  The files that @command{configure} creates are:
963
964@itemize @minus
965@item
966one or more @file{Makefile} files, usually one in each subdirectory of the
967package (@pxref{Makefile Substitutions});
968
969@item
970optionally, a C header file, the name of which is configurable,
971containing @code{#define} directives (@pxref{Configuration Headers});
972
973@item
974a shell script called @file{config.status} that, when run, recreates
975the files listed above (@pxref{config.status Invocation});
976
977@item
978an optional shell script normally called @file{config.cache}
979(created when using @samp{configure --config-cache}) that
980saves the results of running many of the tests (@pxref{Cache Files});
981
982@item
983a file called @file{config.log} containing any messages produced by
984compilers, to help debugging if @command{configure} makes a mistake.
985@end itemize
986
987@cindex @file{configure.in}
988@cindex @file{configure.ac}
989To create a @command{configure} script with Autoconf, you need to write an
990Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
991@command{autoconf} on it.  If you write your own feature tests to
992supplement those that come with Autoconf, you might also write files
993called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
994file to contain @code{#define} directives, you might also run
995@command{autoheader}, and you can distribute the generated file
996@file{config.h.in} with the package.
997
998Here is a diagram showing how the files that can be used in
999configuration are produced.  Programs that are executed are suffixed by
1000@samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1001@command{autoconf} and @command{autoheader} also read the installed Autoconf
1002macro files (by reading @file{autoconf.m4}).
1003
1004@noindent
1005Files used in preparing a software package for distribution, when using
1006just Autoconf:
1007@example
1008your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1009
1010@group
1011configure.ac --.
1012               |   .------> autoconf* -----> configure
1013[aclocal.m4] --+---+
1014               |   `-----> [autoheader*] --> [config.h.in]
1015[acsite.m4] ---'
1016@end group
1017
1018Makefile.in
1019@end example
1020
1021@noindent
1022Additionally, if you use Automake, the following additional productions
1023come into play:
1024
1025@example
1026@group
1027[acinclude.m4] --.
1028                 |
1029[local macros] --+--> aclocal* --> aclocal.m4
1030                 |
1031configure.ac ----'
1032@end group
1033
1034@group
1035configure.ac --.
1036               +--> automake* --> Makefile.in
1037Makefile.am ---'
1038@end group
1039@end example
1040
1041@noindent
1042Files used in configuring a software package:
1043@example
1044@group
1045                       .-------------> [config.cache]
1046configure* ------------+-------------> config.log
1047                       |
1048[config.h.in] -.       v            .-> [config.h] -.
1049               +--> config.status* -+               +--> make*
1050Makefile.in ---'                    `-> Makefile ---'
1051@end group
1052@end example
1053
1054@menu
1055* Writing Autoconf Input::      What to put in an Autoconf input file
1056* autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1057* ifnames Invocation::          Listing the conditionals in source code
1058* autoconf Invocation::         How to create configuration scripts
1059* autoreconf Invocation::       Remaking multiple @command{configure} scripts
1060@end menu
1061
1062@node Writing Autoconf Input
1063@section Writing @file{configure.ac}
1064
1065To produce a @command{configure} script for a software package, create a
1066file called @file{configure.ac} that contains invocations of the
1067Autoconf macros that test the system features your package needs or can
1068use.  Autoconf macros already exist to check for many features; see
1069@ref{Existing Tests}, for their descriptions.  For most other features,
1070you can use Autoconf template macros to produce custom checks; see
1071@ref{Writing Tests}, for information about them.  For especially tricky
1072or specialized features, @file{configure.ac} might need to contain some
1073hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1074Programming}.  The @command{autoscan} program can give you a good start
1075in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1076information).
1077
1078Previous versions of Autoconf promoted the name @file{configure.in},
1079which is somewhat ambiguous (the tool needed to process this file is not
1080described by its extension), and introduces a slight confusion with
1081@file{config.h.in} and so on (for which @samp{.in} means ``to be
1082processed by @command{configure}'').  Using @file{configure.ac} is now
1083preferred.
1084
1085@menu
1086* Shell Script Compiler::       Autoconf as solution of a problem
1087* Autoconf Language::           Programming in Autoconf
1088* Autoconf Input Layout::       Standard organization of @file{configure.ac}
1089@end menu
1090
1091@node Shell Script Compiler
1092@subsection A Shell Script Compiler
1093
1094Just as for any other computer language, in order to properly program
1095@file{configure.ac} in Autoconf you must understand @emph{what} problem
1096the language tries to address and @emph{how} it does so.
1097
1098The problem Autoconf addresses is that the world is a mess.  After all,
1099you are using Autoconf in order to have your package compile easily on
1100all sorts of different systems, some of them being extremely hostile.
1101Autoconf itself bears the price for these differences: @command{configure}
1102must run on all those systems, and thus @command{configure} must limit itself
1103to their lowest common denominator of features.
1104
1105Naturally, you might then think of shell scripts; who needs
1106@command{autoconf}?  A set of properly written shell functions is enough to
1107make it easy to write @command{configure} scripts by hand.  Sigh!
1108Unfortunately, even in 2008, where shells without any function support are
1109far and few between, there are pitfalls to avoid when making use of them.
1110Also, finding a Bourne shell that accepts shell functions is not trivial,
1111even though there is almost always one on interesting porting targets.
1112
1113So, what is really needed is some kind of compiler, @command{autoconf},
1114that takes an Autoconf program, @file{configure.ac}, and transforms it
1115into a portable shell script, @command{configure}.
1116
1117How does @command{autoconf} perform this task?
1118
1119There are two obvious possibilities: creating a brand new language or
1120extending an existing one.  The former option is attractive: all
1121sorts of optimizations could easily be implemented in the compiler and
1122many rigorous checks could be performed on the Autoconf program
1123(e.g., rejecting any non-portable construct).  Alternatively, you can
1124extend an existing language, such as the @code{sh} (Bourne shell)
1125language.
1126
1127Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1128therefore most convenient to implement @command{autoconf} as a macro
1129expander: a program that repeatedly performs @dfn{macro expansions} on
1130text input, replacing macro calls with macro bodies and producing a pure
1131@code{sh} script in the end.  Instead of implementing a dedicated
1132Autoconf macro expander, it is natural to use an existing
1133general-purpose macro language, such as M4, and implement the extensions
1134as a set of M4 macros.
1135
1136
1137@node Autoconf Language
1138@subsection The Autoconf Language
1139@cindex quotation
1140
1141The Autoconf language differs from many other computer
1142languages because it treats actual code the same as plain text.  Whereas
1143in C, for instance, data and instructions have different syntactic
1144status, in Autoconf their status is rigorously the same.  Therefore, we
1145need a means to distinguish literal strings from text to be expanded:
1146quotation.
1147
1148When calling macros that take arguments, there must not be any white
1149space between the macro name and the open parenthesis.
1150
1151@example
1152AC_INIT ([oops], [1.0]) # incorrect
1153AC_INIT([hello], [1.0]) # good
1154@end example
1155
1156Arguments should
1157be enclosed within the quote characters @samp{[} and @samp{]}, and be
1158separated by commas.  Any leading blanks or newlines in arguments are ignored,
1159unless they are quoted.  You should always quote an argument that
1160might contain a macro name, comma, parenthesis, or a leading blank or
1161newline.  This rule applies recursively for every macro
1162call, including macros called from other macros.  For more details on
1163quoting rules, see @ref{Programming in M4}.
1164
1165For instance:
1166
1167@example
1168AC_CHECK_HEADER([stdio.h],
1169                [AC_DEFINE([HAVE_STDIO_H], [1],
1170                   [Define to 1 if you have <stdio.h>.])],
1171                [AC_MSG_ERROR([sorry, can't do anything for you])])
1172@end example
1173
1174@noindent
1175is quoted properly.  You may safely simplify its quotation to:
1176
1177@example
1178AC_CHECK_HEADER([stdio.h],
1179                [AC_DEFINE([HAVE_STDIO_H], 1,
1180                   [Define to 1 if you have <stdio.h>.])],
1181                [AC_MSG_ERROR([sorry, can't do anything for you])])
1182@end example
1183
1184@noindent
1185because @samp{1} cannot contain a macro call.  Here, the argument of
1186@code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1187interpreted as an argument separator.  Also, the second and third arguments
1188of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1189macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1190and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1191if you unwisely defined a macro with a name like @samp{Define} or
1192@samp{stdio} then they would need quoting.  Cautious Autoconf users
1193would keep the quotes, but many Autoconf users find such precautions
1194annoying, and would rewrite the example as follows:
1195
1196@example
1197AC_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
1202
1203@noindent
1204This is safe, so long as you adopt good naming conventions and do not
1205define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1206@samp{h}.  Though it is also safe here to omit the quotes around
1207@samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1208message strings are more likely to inadvertently contain commas.
1209
1210The following example is wrong and dangerous, as it is underquoted:
1211
1212@example
1213AC_CHECK_HEADER(stdio.h,
1214                AC_DEFINE(HAVE_STDIO_H, 1,
1215                   Define to 1 if you have <stdio.h>.),
1216                AC_MSG_ERROR([sorry, can't do anything for you]))
1217@end example
1218
1219In other cases, you may have to use text that also resembles a macro
1220call.  You must quote that text even when it is not passed as a macro
1221argument.  For example, these two approaches in @file{configure.ac}
1222(quoting just the potential problems, or quoting the entire line) will
1223protect your script in case autoconf ever adds a macro @code{AC_DC}:
1224
1225@example
1226echo "Hard rock was here!  --[AC_DC]"
1227[echo "Hard rock was here!  --AC_DC"]
1228@end example
1229
1230@noindent
1231which results in this text in @file{configure}:
1232
1233@example
1234echo "Hard rock was here!  --AC_DC"
1235echo "Hard rock was here!  --AC_DC"
1236@end example
1237
1238@noindent
1239When you use the same text in a macro argument, you must therefore have
1240an extra quotation level (since one is stripped away by the macro
1241substitution).  In general, then, it is a good idea to @emph{use double
1242quoting for all literal string arguments}, either around just the
1243problematic portions, or over the entire argument:
1244
1245@example
1246AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1247AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1248@end example
1249
1250However, the above example triggers a warning about a possibly
1251unexpanded macro when running @command{autoconf}, because it collides
1252with the namespace of macros reserved for the Autoconf language.  To be
1253really safe, you can use additional escaping (either a quadrigraph, or
1254creative shell constructs) to silence that particular warning:
1255
1256@example
1257echo "Hard rock was here!  --AC""_DC"
1258AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1259@end example
1260
1261You are now able to understand one of the constructs of Autoconf that
1262has been continually misunderstood@enddots{}  The rule of thumb is that
1263@emph{whenever you expect macro expansion, expect quote expansion};
1264i.e., expect one level of quotes to be lost.  For instance:
1265
1266@example
1267AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1268 [AC_MSG_ERROR([you lose])])
1269@end example
1270
1271@noindent
1272is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1273@samp{char b[10];} and is expanded once, which results in
1274@samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1275to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1276in Autoconf's past to
1277address this issue via the M4 @code{changequote} primitive, but do not
1278use it!)  Let's take a closer look: the author meant the first argument
1279to be understood as a literal, and therefore it must be quoted twice;
1280likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1281once so that it is only expanded after the rest of the body of
1282@code{AC_COMPILE_IFELSE} is in place:
1283
1284@example
1285AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1286  [AC_MSG_ERROR([you lose])])
1287@end example
1288
1289@noindent
1290Voil@`a, you actually produce @samp{char b[10];} this time!
1291
1292On the other hand, descriptions (e.g., the last parameter of
1293@code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1294are subject to line breaking, for example---and should not be double quoted.
1295Even if these descriptions are short and are not actually broken, double
1296quoting them yields weird results.
1297
1298Some macros take optional arguments, which this documentation represents
1299as @ovar{arg} (not to be confused with the quote characters).  You may
1300just leave them empty, or use @samp{[]} to make the emptiness of the
1301argument explicit, or you may simply omit the trailing commas.  The
1302three lines below are equivalent:
1303
1304@example
1305AC_CHECK_HEADERS([stdio.h], [], [], [])
1306AC_CHECK_HEADERS([stdio.h],,,)
1307AC_CHECK_HEADERS([stdio.h])
1308@end example
1309
1310It is best to put each macro call on its own line in
1311@file{configure.ac}.  Most of the macros don't add extra newlines; they
1312rely on the newline after the macro call to terminate the commands.
1313This approach makes the generated @command{configure} script a little
1314easier to read by not inserting lots of blank lines.  It is generally
1315safe to set shell variables on the same line as a macro call, because
1316the shell allows assignments without intervening newlines.
1317
1318You can include comments in @file{configure.ac} files by starting them
1319with the @samp{#}.  For example, it is helpful to begin
1320@file{configure.ac} files with a line like this:
1321
1322@example
1323# Process this file with autoconf to produce a configure script.
1324@end example
1325
1326@node Autoconf Input Layout
1327@subsection Standard @file{configure.ac} Layout
1328
1329The order in which @file{configure.ac} calls the Autoconf macros is not
1330important, with a few exceptions.  Every @file{configure.ac} must
1331contain a call to @code{AC_INIT} before the checks, and a call to
1332@code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1333rely on other macros having been called first, because they check
1334previously set values of some variables to decide what to do.  These
1335macros are noted in the individual descriptions (@pxref{Existing
1336Tests}), and they also warn you when @command{configure} is created if they
1337are called out of order.
1338
1339To encourage consistency, here is a suggested order for calling the
1340Autoconf macros.  Generally speaking, the things near the end of this
1341list are those that could depend on things earlier in it.  For example,
1342library functions could be affected by types and libraries.
1343
1344@display
1345@group
1346Autoconf requirements
1347@code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1348information on the package
1349checks for programs
1350checks for libraries
1351checks for header files
1352checks for types
1353checks for structures
1354checks for compiler characteristics
1355checks for library functions
1356checks for system services
1357@code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1358@code{AC_OUTPUT}
1359@end group
1360@end display
1361
1362
1363@node autoscan Invocation
1364@section Using @command{autoscan} to Create @file{configure.ac}
1365@cindex @command{autoscan}
1366
1367The @command{autoscan} program can help you create and/or maintain a
1368@file{configure.ac} file for a software package.  @command{autoscan}
1369examines source files in the directory tree rooted at a directory given
1370as a command line argument, or the current directory if none is given.
1371It searches the source files for common portability problems and creates
1372a file @file{configure.scan} which is a preliminary @file{configure.ac}
1373for that package, and checks a possibly existing @file{configure.ac} for
1374completeness.
1375
1376When using @command{autoscan} to create a @file{configure.ac}, you
1377should manually examine @file{configure.scan} before renaming it to
1378@file{configure.ac}; it probably needs some adjustments.
1379Occasionally, @command{autoscan} outputs a macro in the wrong order
1380relative to another macro, so that @command{autoconf} produces a warning;
1381you need to move such macros manually.  Also, if you want the package to
1382use a configuration header file, you must add a call to
1383@code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1384also have to change or add some @code{#if} directives to your program in
1385order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1386information about a program that can help with that job).
1387
1388When using @command{autoscan} to maintain a @file{configure.ac}, simply
1389consider adding its suggestions.  The file @file{autoscan.log}
1390contains detailed information on why a macro is requested.
1391
1392@command{autoscan} uses several data files (installed along with Autoconf)
1393to determine which macros to output when it finds particular symbols in
1394a package's source files.  These data files all have the same format:
1395each line consists of a symbol, one or more blanks, and the Autoconf macro to
1396output if that symbol is encountered.  Lines starting with @samp{#} are
1397comments.
1398
1399@command{autoscan} accepts the following options:
1400
1401@table @option
1402@item --help
1403@itemx -h
1404Print a summary of the command line options and exit.
1405
1406@item --version
1407@itemx -V
1408Print the version number of Autoconf and exit.
1409
1410@item --verbose
1411@itemx -v
1412Print the names of the files it examines and the potentially interesting
1413symbols it finds in them.  This output can be voluminous.
1414
1415@item --debug
1416@itemx -d
1417Don't remove temporary files.
1418
1419@item --include=@var{dir}
1420@itemx -I @var{dir}
1421Append @var{dir} to the include path.  Multiple invocations accumulate.
1422
1423@item --prepend-include=@var{dir}
1424@itemx -B @var{dir}
1425Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1426@end table
1427
1428@node ifnames Invocation
1429@section Using @command{ifnames} to List Conditionals
1430@cindex @command{ifnames}
1431
1432@command{ifnames} can help you write @file{configure.ac} for a software
1433package.  It prints the identifiers that the package already uses in C
1434preprocessor conditionals.  If a package has already been set up to have
1435some portability, @command{ifnames} can thus help you figure out what its
1436@command{configure} needs to check for.  It may help fill in some gaps in a
1437@file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1438Invocation}).
1439
1440@command{ifnames} scans all of the C source files named on the command line
1441(or the standard input, if none are given) and writes to the standard
1442output a sorted list of all the identifiers that appear in those files
1443in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1444directives.  It prints each identifier on a line, followed by a
1445space-separated list of the files in which that identifier occurs.
1446
1447@noindent
1448@command{ifnames} accepts the following options:
1449
1450@table @option
1451@item --help
1452@itemx -h
1453Print a summary of the command line options and exit.
1454
1455@item --version
1456@itemx -V
1457Print the version number of Autoconf and exit.
1458@end table
1459
1460@node autoconf Invocation
1461@section Using @command{autoconf} to Create @command{configure}
1462@cindex @command{autoconf}
1463
1464To create @command{configure} from @file{configure.ac}, run the
1465@command{autoconf} program with no arguments.  @command{autoconf} processes
1466@file{configure.ac} with the M4 macro processor, using the
1467Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1468file instead of @file{configure.ac} and writes the configuration script
1469to the standard output instead of to @command{configure}.  If you give
1470@command{autoconf} the argument @option{-}, it reads from the standard
1471input instead of @file{configure.ac} and writes the configuration script
1472to the standard output.
1473
1474The Autoconf macros are defined in several files.  Some of the files are
1475distributed with Autoconf; @command{autoconf} reads them first.  Then it
1476looks for the optional file @file{acsite.m4} in the directory that
1477contains the distributed Autoconf macro files, and for the optional file
1478@file{aclocal.m4} in the current directory.  Those files can contain
1479your site's or the package's own Autoconf macro definitions
1480(@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1481defined in more than one of the files that @command{autoconf} reads, the
1482last definition it reads overrides the earlier ones.
1483
1484@command{autoconf} accepts the following options:
1485
1486@table @option
1487@item --help
1488@itemx -h
1489Print a summary of the command line options and exit.
1490
1491@item --version
1492@itemx -V
1493Print the version number of Autoconf and exit.
1494
1495@item --verbose
1496@itemx -v
1497Report processing steps.
1498
1499@item --debug
1500@itemx -d
1501Don't remove the temporary files.
1502
1503@item --force
1504@itemx -f
1505Remake @file{configure} even if newer than its input files.
1506
1507@item --include=@var{dir}
1508@itemx -I @var{dir}
1509Append @var{dir} to the include path.  Multiple invocations accumulate.
1510
1511@item --prepend-include=@var{dir}
1512@itemx -B @var{dir}
1513Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1514
1515@item --output=@var{file}
1516@itemx -o @var{file}
1517Save output (script or trace) to @var{file}.  The file @option{-} stands
1518for the standard output.
1519
1520@item --warnings=@var{category}
1521@itemx -W @var{category}
1522@evindex WARNINGS
1523Report the warnings related to @var{category} (which can actually be a
1524comma separated list).  @xref{Reporting Messages}, macro
1525@code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1526values include:
1527
1528@table @samp
1529@item all
1530report all the warnings
1531
1532@item none
1533report none
1534
1535@item error
1536treats warnings as errors
1537
1538@item no-@var{category}
1539disable warnings falling into @var{category}
1540@end table
1541
1542Warnings about @samp{syntax} are enabled by default, and the environment
1543variable @env{WARNINGS}, a comma separated list of categories, is
1544honored as well.  Passing @option{-W @var{category}} actually behaves as if
1545you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1546disable the defaults and @env{WARNINGS}, and then
1547enable warnings about obsolete constructs, use @option{-W
1548none,obsolete}.
1549
1550@cindex Back trace
1551@cindex Macro invocation stack
1552Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1553displays a back trace for errors, but not for warnings; if you want
1554them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1555examples.
1556
1557@item --trace=@var{macro}[:@var{format}]
1558@itemx -t @var{macro}[:@var{format}]
1559Do not create the @command{configure} script, but list the calls to
1560@var{macro} according to the @var{format}.  Multiple @option{--trace}
1561arguments can be used to list several macros.  Multiple @option{--trace}
1562arguments for a single macro are not cumulative; instead, you should
1563just make @var{format} as long as needed.
1564
1565The @var{format} is a regular string, with newlines if desired, and
1566several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1567@ref{autom4te Invocation}, for details on the @var{format}.
1568
1569@item --initialization
1570@itemx -i
1571By default, @option{--trace} does not trace the initialization of the
1572Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1573results in a noticeable speedup, but can be disabled by this option.
1574@end table
1575
1576
1577It is often necessary to check the content of a @file{configure.ac}
1578file, but parsing it yourself is extremely fragile and error-prone.  It
1579is suggested that you rely upon @option{--trace} to scan
1580@file{configure.ac}.  For instance, to find the list of variables that
1581are substituted, use:
1582
1583@example
1584@group
1585$ @kbd{autoconf -t AC_SUBST}
1586configure.ac:2:AC_SUBST:ECHO_C
1587configure.ac:2:AC_SUBST:ECHO_N
1588configure.ac:2:AC_SUBST:ECHO_T
1589@i{More traces deleted}
1590@end group
1591@end example
1592
1593@noindent
1594The example below highlights the difference between @samp{$@@},
1595@samp{$*}, and @samp{$%}.
1596
1597@example
1598@group
1599$ @kbd{cat configure.ac}
1600AC_DEFINE(This, is, [an
1601[example]])
1602$ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1603*: $*
1604%: $%'
1605@@: [This],[is],[an
1606[example]]
1607*: This,is,an
1608[example]
1609%: This:is:an [example]
1610@end group
1611@end example
1612
1613@noindent
1614The @var{format} gives you a lot of freedom:
1615
1616@example
1617@group
1618$ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1619$ac_subst@{"ECHO_C"@} = "configure.ac:2";
1620$ac_subst@{"ECHO_N"@} = "configure.ac:2";
1621$ac_subst@{"ECHO_T"@} = "configure.ac:2";
1622@i{More traces deleted}
1623@end group
1624@end example
1625
1626@noindent
1627A long @var{separator} can be used to improve the readability of complex
1628structures, and to ease their parsing (for instance when no single
1629character is suitable as a separator):
1630
1631@example
1632@group
1633$ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1634ACLOCAL|:::::|aclocal|:::::|$missing_dir
1635AUTOCONF|:::::|autoconf|:::::|$missing_dir
1636AUTOMAKE|:::::|automake|:::::|$missing_dir
1637@i{More traces deleted}
1638@end group
1639@end example
1640
1641@node autoreconf Invocation
1642@section Using @command{autoreconf} to Update @command{configure} Scripts
1643@cindex @command{autoreconf}
1644
1645Installing the various components of the GNU Build System can be
1646tedious: running @command{autopoint} for Gettext, @command{automake} for
1647@file{Makefile.in} etc.@: in each directory.  It may be needed either
1648because some tools such as @command{automake} have been updated on your
1649system, or because some of the sources such as @file{configure.ac} have
1650been updated, or finally, simply in order to install the GNU Build
1651System in a fresh tree.
1652
1653@command{autoreconf} runs @command{autoconf}, @command{autoheader},
1654@command{aclocal}, @command{automake}, @command{libtoolize}, and
1655@command{autopoint} (when appropriate) repeatedly to update the
1656GNU Build System in the specified directories and their
1657subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1658those files that are older than their sources.  The environment variables
1659@env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1660@env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1661may be used to override the invocation of the respective tools.
1662
1663If you install a new version of some tool, you can make
1664@command{autoreconf} remake @emph{all} of the files by giving it the
1665@option{--force} option.
1666
1667@xref{Automatic Remaking}, for Make rules to automatically
1668rebuild @command{configure} scripts when their source files change.  That
1669method handles the timestamps of configuration header templates
1670properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1671@option{--localdir=@var{dir}}.
1672
1673@cindex Gettext
1674@cindex @command{autopoint}
1675Gettext supplies the @command{autopoint} command to add translation
1676infrastructure to a source package.  If you use @command{autopoint},
1677your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1678@code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1679Invocation, , Invoking the @code{autopoint} Program, gettext,
1680GNU @code{gettext} utilities}, for further details.
1681
1682@noindent
1683@command{autoreconf} accepts the following options:
1684
1685@table @option
1686@item --help
1687@itemx -h
1688Print a summary of the command line options and exit.
1689
1690@item --version
1691@itemx -V
1692Print the version number of Autoconf and exit.
1693
1694@item --verbose
1695@itemx -v
1696Print the name of each directory @command{autoreconf} examines and the
1697commands it runs.  If given two or more times, pass @option{--verbose}
1698to subordinate tools that support it.
1699
1700@item --debug
1701@itemx -d
1702Don't remove the temporary files.
1703
1704@item --force
1705@itemx -f
1706Remake even @file{configure} scripts and configuration headers that are
1707newer than their input files (@file{configure.ac} and, if present,
1708@file{aclocal.m4}).
1709
1710@item --install
1711@itemx -i
1712Install the missing auxiliary files in the package.  By default, files
1713are copied; this can be changed with @option{--symlink}.
1714
1715If deemed appropriate, this option triggers calls to
1716@samp{automake --add-missing},
1717@samp{libtoolize}, @samp{autopoint}, etc.
1718
1719@item --no-recursive
1720Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1721macro @code{AC_CONFIG_SUBDIRS}).
1722
1723@item --symlink
1724@itemx -s
1725When used with @option{--install}, install symbolic links to the missing
1726auxiliary files instead of copying them.
1727
1728@item --make
1729@itemx -m
1730When the directories were configured, update the configuration by
1731running @samp{./config.status --recheck && ./config.status}, and then
1732run @samp{make}.
1733
1734@item --include=@var{dir}
1735@itemx -I @var{dir}
1736Append @var{dir} to the include path.  Multiple invocations accumulate.
1737Passed on to @command{aclocal}, @command{autoconf} and
1738@command{autoheader} internally.
1739
1740@item --prepend-include=@var{dir}
1741@itemx -B @var{dir}
1742Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1743Passed on to @command{autoconf} and @command{autoheader} internally.
1744
1745@item --warnings=@var{category}
1746@itemx -W @var{category}
1747@evindex WARNINGS
1748Report the warnings related to @var{category} (which can actually be a
1749comma separated list).
1750
1751@table @samp
1752@item cross
1753related to cross compilation issues.
1754
1755@item obsolete
1756report the uses of obsolete constructs.
1757
1758@item portability
1759portability issues
1760
1761@item syntax
1762dubious syntactic constructs.
1763
1764@item all
1765report all the warnings
1766
1767@item none
1768report none
1769
1770@item error
1771treats warnings as errors
1772
1773@item no-@var{category}
1774disable warnings falling into @var{category}
1775@end table
1776
1777Warnings about @samp{syntax} are enabled by default, and the environment
1778variable @env{WARNINGS}, a comma separated list of categories, is
1779honored as well.  Passing @option{-W @var{category}} actually behaves as if
1780you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1781disable the defaults and @env{WARNINGS}, and then
1782enable warnings about obsolete constructs, use @option{-W
1783none,obsolete}.
1784@end table
1785
1786If you want @command{autoreconf} to pass flags that are not listed here
1787on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1788Due to a limitation in the Autoconf implementation these flags currently
1789must be set on a single line in @file{Makefile.am}, without any
1790backslash-newlines.
1791
1792@c ========================================= Initialization and Output Files.
1793
1794@node Setup
1795@chapter Initialization and Output Files
1796
1797Autoconf-generated @command{configure} scripts need some information about
1798how to initialize, such as how to find the package's source files and
1799about the output files to produce.  The following sections describe the
1800initialization and the creation of output files.
1801
1802@menu
1803* Initializing configure::      Option processing etc.
1804* Versioning::                  Dealing with Autoconf versions
1805* Notices::                     Copyright, version numbers in @command{configure}
1806* Input::                       Where Autoconf should find files
1807* Output::                      Outputting results from the configuration
1808* Configuration Actions::       Preparing the output based on results
1809* Configuration Files::         Creating output files
1810* Makefile Substitutions::      Using output variables in makefiles
1811* Configuration Headers::       Creating a configuration header file
1812* Configuration Commands::      Running arbitrary instantiation commands
1813* Configuration Links::         Links depending on the configuration
1814* Subdirectories::              Configuring independent packages together
1815* Default Prefix::              Changing the default installation prefix
1816@end menu
1817
1818@node Initializing configure
1819@section Initializing @command{configure}
1820
1821Every @command{configure} script must call @code{AC_INIT} before doing
1822anything else that produces output.  Calls to silent macros, such as
1823@code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1824are generally used via @file{aclocal.m4}, since that is implicitly
1825included before the start of @file{configure.ac}.  The only other
1826required macro is @code{AC_OUTPUT} (@pxref{Output}).
1827
1828@anchor{AC_INIT}
1829@defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1830  @ovar{tarname}, @ovar{url})
1831@acindex{INIT}
1832Process any command-line arguments and perform initialization
1833and verification.
1834
1835Set the name of the @var{package} and its @var{version}.  These are
1836typically used in @option{--version} support, including that of
1837@command{configure}.  The optional argument @var{bug-report} should be
1838the email to which users should send bug reports.  The package
1839@var{tarname} differs from @var{package}: the latter designates the full
1840package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1841distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1842@var{package} with @samp{GNU } stripped, lower-cased, and all characters
1843other than alphanumerics and underscores are changed to @samp{-}.  If
1844provided, @var{url} should be the home page for the package.
1845
1846The arguments of @code{AC_INIT} must be static, i.e., there should not
1847be any shell computation, quotes, or newlines, but they can be computed
1848by M4.  This is because the package information strings are expanded at
1849M4 time into several contexts, and must give the same text at shell time
1850whether used in single-quoted strings, double-quoted strings, quoted
1851here-documents, or unquoted here-documents.  It is permissible to use
1852@code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1853that changes with every commit to a version control system (in fact,
1854Autoconf does just that, for all builds of the development tree made
1855between releases).
1856
1857The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1858(e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1859@code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1860
1861@table @asis
1862@item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1863@acindex{PACKAGE_NAME}
1864@ovindex PACKAGE_NAME
1865@cvindex PACKAGE_NAME
1866Exactly @var{package}.
1867
1868@item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1869@acindex{PACKAGE_TARNAME}
1870@ovindex PACKAGE_TARNAME
1871@cvindex PACKAGE_TARNAME
1872Exactly @var{tarname}, possibly generated from @var{package}.
1873
1874@item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1875@acindex{PACKAGE_VERSION}
1876@ovindex PACKAGE_VERSION
1877@cvindex PACKAGE_VERSION
1878Exactly @var{version}.
1879
1880@item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1881@acindex{PACKAGE_STRING}
1882@ovindex PACKAGE_STRING
1883@cvindex PACKAGE_STRING
1884Exactly @samp{@var{package} @var{version}}.
1885
1886@item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1887@acindex{PACKAGE_BUGREPORT}
1888@ovindex PACKAGE_BUGREPORT
1889@cvindex PACKAGE_BUGREPORT
1890Exactly @var{bug-report}, if one was provided.  Typically an email
1891address, or URL to a bug management web page.
1892
1893@item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1894@acindex{PACKAGE_URL}
1895@ovindex PACKAGE_URL
1896@cvindex PACKAGE_URL
1897Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1898@var{package} begins with @samp{GNU }, then this defaults to
1899@samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1900assumed.
1901@end table
1902@end defmac
1903
1904If your @command{configure} script does its own option processing, it
1905should inspect @samp{$@@} or @samp{$*} immediately after calling
1906@code{AC_INIT}, because other Autoconf macros liberally use the
1907@command{set} command to process strings, and this has the side effect
1908of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1909standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1910implement your own option processing.  @xref{Site Configuration}.
1911
1912@node Versioning
1913@section Dealing with Autoconf versions
1914@cindex Autoconf version
1915@cindex version, Autoconf
1916
1917The following optional macros can be used to help choose the minimum
1918version of Autoconf that can successfully compile a given
1919@file{configure.ac}.
1920
1921@defmac AC_PREREQ (@var{version})
1922@acindex{PREREQ}
1923@cindex Version
1924Ensure that a recent enough version of Autoconf is being used.  If the
1925version of Autoconf being used to create @command{configure} is
1926earlier than @var{version}, print an error message to the standard
1927error output and exit with failure (exit status is 63).  For example:
1928
1929@example
1930AC_PREREQ([@value{VERSION}])
1931@end example
1932
1933This macro may be used before @code{AC_INIT}.
1934@end defmac
1935
1936@defmac AC_AUTOCONF_VERSION
1937@acindex{AUTOCONF_VERSION}
1938This macro was introduced in Autoconf 2.62.  It identifies the version
1939of Autoconf that is currently parsing the input file, in a format
1940suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1941other words, for this release of Autoconf, its value is
1942@samp{@value{VERSION}}.  One potential use of this macro is for writing
1943conditional fallbacks based on when a feature was added to Autoconf,
1944rather than using @code{AC_PREREQ} to require the newer version of
1945Autoconf.  However, remember that the Autoconf philosophy favors feature
1946checks over version checks.
1947
1948You should not expand this macro directly; use
1949@samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1950users might
1951have a beta version of Autoconf installed, with arbitrary letters
1952included in its version string.  This means it is possible for the
1953version string to contain the name of a defined macro, such that
1954expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1955macro during rescanning, and change the version string to be different
1956than what you intended to check.
1957@end defmac
1958
1959@node Notices
1960@section Notices in @command{configure}
1961@cindex Notices in @command{configure}
1962
1963The following macros manage version numbers for @command{configure}
1964scripts.  Using them is optional.
1965
1966@defmac AC_COPYRIGHT (@var{copyright-notice})
1967@acindex{COPYRIGHT}
1968@cindex Copyright Notice
1969State that, in addition to the Free Software Foundation's copyright on
1970the Autoconf macros, parts of your @command{configure} are covered by the
1971@var{copyright-notice}.
1972
1973The @var{copyright-notice} shows up in both the head of
1974@command{configure} and in @samp{configure --version}.
1975@end defmac
1976
1977
1978@defmac AC_REVISION (@var{revision-info})
1979@acindex{REVISION}
1980@cindex Revision
1981Copy revision stamp @var{revision-info} into the @command{configure}
1982script, with any dollar signs or double-quotes removed.  This macro lets
1983you put a revision stamp from @file{configure.ac} into @command{configure}
1984without RCS or CVS changing it when you check in
1985@command{configure}.  That way, you can determine easily which revision of
1986@file{configure.ac} a particular @command{configure} corresponds to.
1987
1988For example, this line in @file{configure.ac}:
1989
1990@c The @w prevents RCS from changing the example in the manual.
1991@example
1992AC_REVISION([@w{$}Revision: 1.30 $])
1993@end example
1994
1995@noindent
1996produces this in @command{configure}:
1997
1998@example
1999#!/bin/sh
2000# From configure.ac Revision: 1.30
2001@end example
2002@end defmac
2003
2004
2005@node Input
2006@section Finding @command{configure} Input
2007
2008@anchor{AC_CONFIG_SRCDIR}
2009@defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2010@acindex{CONFIG_SRCDIR}
2011@var{unique-file-in-source-dir} is some file that is in the package's
2012source directory; @command{configure} checks for this file's existence to
2013make sure that the directory that it is told contains the source code in
2014fact does.  Occasionally people accidentally specify the wrong directory
2015with @option{--srcdir}; this is a safety check.  @xref{configure
2016Invocation}, for more information.
2017@end defmac
2018
2019
2020@c FIXME: Remove definitively once --install explained.
2021@c
2022@c Small packages may store all their macros in @code{aclocal.m4}.  As the
2023@c set of macros grows, or for maintenance reasons, a maintainer may prefer
2024@c to split the macros in several files.  In this case, Autoconf must be
2025@c told which files to load, and in which order.
2026@c
2027@c @defmac AC_INCLUDE (@var{file}@dots{})
2028@c @acindex{INCLUDE}
2029@c @c FIXME: There is no longer shell globbing.
2030@c Read the macro definitions that appear in the listed files.  A list of
2031@c space-separated file names or shell globbing patterns is expected.  The
2032@c files are read in the order they're listed.
2033@c
2034@c Because the order of definition of macros is important (only the last
2035@c definition of a macro is used), beware that it is @code{AC_INIT} that
2036@c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2037@c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2038@c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2039@c the latter case, non-macro lines from included files may end up in the
2040@c @file{configure} script, whereas in the former case, they'd be discarded
2041@c just like any text that appear before @code{AC_INIT}.
2042@c @end defmac
2043
2044Packages that do manual configuration or use the @command{install} program
2045might need to tell @command{configure} where to find some other shell
2046scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2047it looks are correct for most cases.
2048
2049@defmac AC_CONFIG_AUX_DIR (@var{dir})
2050@acindex{CONFIG_AUX_DIR}
2051Use the auxiliary build tools (e.g., @file{install-sh},
2052@file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2053Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2054These are auxiliary files used in configuration.  @var{dir} can be
2055either absolute or relative to @file{@var{srcdir}}.  The default is
2056@file{@var{srcdir}} or @file{@var{srcdir}/..} or
2057@file{@var{srcdir}/../..}, whichever is the first that contains
2058@file{install-sh}.  The other files are not checked for, so that using
2059@code{AC_PROG_INSTALL} does not automatically require distributing the
2060other auxiliary files.  It checks for @file{install.sh} also, but that
2061name is obsolete because some @command{make} have a rule that creates
2062@file{install} from it if there is no makefile.
2063
2064The auxiliary directory is commonly named @file{build-aux}.
2065If you need portability to DOS variants, do not name the
2066auxiliary directory @file{aux}.  @xref{File System Conventions}.
2067@end defmac
2068
2069@defmac AC_REQUIRE_AUX_FILE (@var{file})
2070@acindex{REQUIRE_AUX_FILE}
2071Declares that @var{file} is expected in the directory defined above.  In
2072Autoconf proper, this macro does nothing: its sole purpose is to be
2073traced by third-party tools to produce a list of expected auxiliary
2074files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2075(@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2076(@pxref{Canonicalizing}) to register the auxiliary files they need.
2077@end defmac
2078
2079Similarly, packages that use @command{aclocal} should declare where
2080local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2081
2082@defmac AC_CONFIG_MACRO_DIR (@var{dir})
2083@acindex{CONFIG_MACRO_DIR}
2084Specify @var{dir} as the location of additional local Autoconf macros.
2085This macro is intended for use by future versions of commands like
2086@command{autoreconf} that trace macro calls.  It should be called
2087directly from @file{configure.ac} so that tools that install macros for
2088@command{aclocal} can find the macros' declarations.
2089
2090Note that if you use @command{aclocal} from Automake to generate
2091@file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2092@var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2093the Autoconf implementation of @command{autoreconf}, these include
2094directives currently must be set on a single line in @file{Makefile.am},
2095without any backslash-newlines.
2096@end defmac
2097
2098
2099@node Output
2100@section Outputting Files
2101@cindex Outputting files
2102
2103Every Autoconf script, e.g., @file{configure.ac}, should finish by
2104calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2105@file{config.status}, which in turn creates the makefiles and any
2106other files resulting from configuration.  This is the only required
2107macro besides @code{AC_INIT} (@pxref{Input}).
2108
2109@anchor{AC_OUTPUT}
2110@defmac AC_OUTPUT
2111@acindex{OUTPUT}
2112@cindex Instantiation
2113Generate @file{config.status} and launch it.  Call this macro once, at
2114the end of @file{configure.ac}.
2115
2116@file{config.status} performs all the configuration actions: all the
2117output files (see @ref{Configuration Files}, macro
2118@code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2119macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2120Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2121@ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2122to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2123are honored.
2124
2125The location of your @code{AC_OUTPUT} invocation is the exact point
2126where configuration actions are taken: any code afterwards is
2127executed by @command{configure} once @command{config.status} was run.  If
2128you want to bind actions to @command{config.status} itself
2129(independently of whether @command{configure} is being run), see
2130@ref{Configuration Commands, , Running Arbitrary Configuration
2131Commands}.
2132@end defmac
2133
2134Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2135@xref{Obsolete Macros}, for a description of the arguments that
2136@code{AC_OUTPUT} used to support.
2137
2138
2139If you run @command{make} in subdirectories, you should run it using the
2140@command{make} variable @code{MAKE}.  Most versions of @command{make} set
2141@code{MAKE} to the name of the @command{make} program plus any options it
2142was given.  (But many do not include in it the values of any variables
2143set on the command line, so those are not passed on automatically.)
2144Some old versions of @command{make} do not set this variable.  The
2145following macro allows you to use it even with those versions.
2146
2147@anchor{AC_PROG_MAKE_SET}
2148@defmac AC_PROG_MAKE_SET
2149@acindex{PROG_MAKE_SET}
2150@ovindex SET_MAKE
2151If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2152@code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2153Otherwise, define @code{SET_MAKE} to a macro definition that sets
2154@code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2155@code{SET_MAKE}.
2156@end defmac
2157
2158If you use this macro, place a line like this in each @file{Makefile.in}
2159that runs @command{MAKE} on other directories:
2160
2161@example
2162@@SET_MAKE@@
2163@end example
2164
2165
2166
2167@node Configuration Actions
2168@section Performing Configuration Actions
2169@cindex Configuration actions
2170
2171@file{configure} is designed so that it appears to do everything itself,
2172but there is actually a hidden slave: @file{config.status}.
2173@file{configure} is in charge of examining your system, but it is
2174@file{config.status} that actually takes the proper actions based on the
2175results of @file{configure}.  The most typical task of
2176@file{config.status} is to @emph{instantiate} files.
2177
2178@acindex{CONFIG_@var{ITEMS}}
2179This section describes the common behavior of the four standard
2180instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2181@code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2182have this prototype:
2183
2184@c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2185@c awful.
2186@example
2187AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2188@end example
2189
2190@noindent
2191where the arguments are:
2192
2193@table @var
2194@item tag@dots{}
2195A blank-or-newline-separated list of tags, which are typically the names of
2196the files to instantiate.
2197
2198You are encouraged to use literals as @var{tags}.  In particular, you
2199should avoid
2200
2201@example
2202@dots{} && my_foos="$my_foos fooo"
2203@dots{} && my_foos="$my_foos foooo"
2204AC_CONFIG_@var{ITEMS}([$my_foos])
2205@end example
2206
2207@noindent
2208and use this instead:
2209
2210@example
2211@dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2212@dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2213@end example
2214
2215The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2216special @var{tag} values: they may have the form @samp{@var{output}} or
2217@samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2218from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2219
2220@samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2221for example, asks for
2222the creation of the file @file{Makefile} that contains the expansion of the
2223output variables in the concatenation of @file{boiler/top.mk} and
2224@file{boiler/bot.mk}.
2225
2226The special value @samp{-} might be used to denote the standard output
2227when used in @var{output}, or the standard input when used in the
2228@var{inputs}.  You most probably don't need to use this in
2229@file{configure.ac}, but it is convenient when using the command line
2230interface of @file{./config.status}, see @ref{config.status Invocation},
2231for more details.
2232
2233The @var{inputs} may be absolute or relative file names.  In the latter
2234case they are first looked for in the build tree, and then in the source
2235tree.  Input files should be text files, and a line length below 2000
2236bytes should be safe.
2237
2238@item commands
2239Shell commands output literally into @file{config.status}, and
2240associated with a tag that the user can use to tell @file{config.status}
2241which commands to run.  The commands are run each time a @var{tag}
2242request is given to @file{config.status}, typically each time the file
2243@file{@var{tag}} is created.
2244
2245The variables set during the execution of @command{configure} are
2246@emph{not} available here: you first need to set them via the
2247@var{init-cmds}.  Nonetheless the following variables are precomputed:
2248
2249@table @code
2250@item srcdir
2251@vrindex srcdir
2252The name of the top source directory, assuming that the working
2253directory is the top build directory.  This
2254is what the @command{configure} option @option{--srcdir} sets.
2255
2256@item ac_top_srcdir
2257@vrindex ac_top_srcdir
2258The name of the top source directory, assuming that the working
2259directory is the current build directory.
2260
2261@item ac_top_build_prefix
2262@vrindex ac_top_build_prefix
2263The name of the top build directory, assuming that the working
2264directory is the current build directory.
2265It can be empty, or else ends with a slash, so that you may concatenate
2266it.
2267
2268@item ac_srcdir
2269@vrindex ac_srcdir
2270The name of the corresponding source directory, assuming that the
2271working directory is the current build directory.
2272
2273@item tmp
2274@vrindex tmp
2275The name of a temporary directory within the build tree, which you
2276can use if you need to create additional temporary files.  The
2277directory is cleaned up when @command{config.status} is done or
2278interrupted.  Please use package-specific file name prefixes to
2279avoid clashing with files that @command{config.status} may use
2280internally.
2281@end table
2282
2283@noindent
2284The @dfn{current} directory refers to the directory (or
2285pseudo-directory) containing the input part of @var{tags}.  For
2286instance, running
2287
2288@example
2289AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2290@end example
2291
2292@noindent
2293 with @option{--srcdir=../package} produces the following values:
2294
2295@example
2296# Argument of --srcdir
2297srcdir='../package'
2298# Reversing deep/dir
2299ac_top_build_prefix='../../'
2300# Concatenation of $ac_top_build_prefix and srcdir
2301ac_top_srcdir='../../../package'
2302# Concatenation of $ac_top_srcdir and deep/dir
2303ac_srcdir='../../../package/deep/dir'
2304@end example
2305
2306@noindent
2307independently of @samp{in/in.in}.
2308
2309@item init-cmds
2310Shell commands output @emph{unquoted} near the beginning of
2311@file{config.status}, and executed each time @file{config.status} runs
2312(regardless of the tag).  Because they are unquoted, for example,
2313@samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2314is typically used by @file{configure} to give @file{config.status} some
2315variables it needs to run the @var{commands}.
2316
2317You should be extremely cautious in your variable names: all the
2318@var{init-cmds} share the same name space and may overwrite each other
2319in unpredictable ways.  Sorry@enddots{}
2320@end table
2321
2322All these macros can be called multiple times, with different
2323@var{tag} values, of course!
2324
2325
2326@node Configuration Files
2327@section Creating Configuration Files
2328@cindex Creating configuration files
2329@cindex Configuration file creation
2330
2331Be sure to read the previous section, @ref{Configuration Actions}.
2332
2333@anchor{AC_CONFIG_FILES}
2334@defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2335@acindex{CONFIG_FILES}
2336Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2337file (by default @file{@var{file}.in}), substituting the output variable
2338values.
2339@c Before we used to have this feature, which was later rejected
2340@c because it complicates the writing of makefiles:
2341@c If the file would be unchanged, it is left untouched, to preserve
2342@c timestamp.
2343This macro is one of the instantiating macros; see @ref{Configuration
2344Actions}.  @xref{Makefile Substitutions}, for more information on using
2345output variables.  @xref{Setting Output Variables}, for more information
2346on creating them.  This macro creates the directory that the file is in
2347if it doesn't exist.  Usually, makefiles are created this way,
2348but other files, such as @file{.gdbinit}, can be specified as well.
2349
2350Typical calls to @code{AC_CONFIG_FILES} look like this:
2351
2352@example
2353AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2354AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2355@end example
2356
2357You can override an input file name by appending to @var{file} a
2358colon-separated list of input files.  Examples:
2359
2360@example
2361AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2362                [lib/Makefile:boiler/lib.mk])
2363@end example
2364
2365@noindent
2366Doing this allows you to keep your file names acceptable to
2367DOS variants, or
2368to prepend and/or append boilerplate to the file.
2369@end defmac
2370
2371
2372
2373@node Makefile Substitutions
2374@section Substitutions in Makefiles
2375@cindex Substitutions in makefiles
2376@cindex Makefile substitutions
2377
2378Each subdirectory in a distribution that contains something to be
2379compiled or installed should come with a file @file{Makefile.in}, from
2380which @command{configure} creates a file @file{Makefile} in that directory.
2381To create @file{Makefile}, @command{configure} performs a simple variable
2382substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2383@file{Makefile.in} with the value that @command{configure} has determined
2384for that variable.  Variables that are substituted into output files in
2385this way are called @dfn{output variables}.  They are ordinary shell
2386variables that are set in @command{configure}.  To make @command{configure}
2387substitute a particular variable into the output files, the macro
2388@code{AC_SUBST} must be called with that variable name as an argument.
2389Any occurrences of @samp{@@@var{variable}@@} for other variables are
2390left unchanged.  @xref{Setting Output Variables}, for more information
2391on creating output variables with @code{AC_SUBST}.
2392
2393A software package that uses a @command{configure} script should be
2394distributed with a file @file{Makefile.in}, but no makefile; that
2395way, the user has to properly configure the package for the local system
2396before compiling it.
2397
2398@xref{Makefile Conventions, , Makefile Conventions, standards, The
2399GNU Coding Standards}, for more information on what to put in
2400makefiles.
2401
2402@menu
2403* Preset Output Variables::     Output variables that are always set
2404* Installation Directory Variables::  Other preset output variables
2405* Changed Directory Variables::  Warnings about @file{datarootdir}
2406* Build Directories::           Supporting multiple concurrent compiles
2407* Automatic Remaking::          Makefile rules for configuring
2408@end menu
2409
2410@node Preset Output Variables
2411@subsection Preset Output Variables
2412@cindex Output variables
2413
2414Some output variables are preset by the Autoconf macros.  Some of the
2415Autoconf macros set additional output variables, which are mentioned in
2416the descriptions for those macros.  @xref{Output Variable Index}, for a
2417complete list of output variables.  @xref{Installation Directory
2418Variables}, for the list of the preset ones related to installation
2419directories.  Below are listed the other preset ones, many of which are
2420precious variables (@pxref{Setting Output Variables},
2421@code{AC_ARG_VAR}).
2422
2423The preset variables which are available during @file{config.status}
2424(@pxref{Configuration Actions}) may also be used during
2425@command{configure} tests.  For example, it is permissible to reference
2426@samp{$srcdir} when constructing a list of directories to pass via
2427option @option{-I} during a compiler feature check.  When used in this
2428manner, coupled with the fact that @command{configure} is always run
2429from the top build directory, it is sufficient to use just
2430@samp{$srcdir} instead of @samp{$top_srcdir}.
2431
2432@c Just say no to ASCII sorting!  We're humans, not computers.
2433@c These variables are listed as they would be in a dictionary:
2434@c actor
2435@c Actress
2436@c actress
2437
2438@defvar CFLAGS
2439@evindex CFLAGS
2440@ovindex CFLAGS
2441Debugging and optimization options for the C compiler.  If it is not set
2442in the environment when @command{configure} runs, the default value is set
2443when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2444uses this variable when compiling or linking programs to test for C features.
2445
2446If a compiler option affects only the behavior of the preprocessor
2447(e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2448instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2449it should be put into @code{LDFLAGS} instead.  If it
2450affects only the compiler proper, @code{CFLAGS} is the natural home for
2451it.  If an option affects multiple phases of the compiler, though,
2452matters get tricky.  One approach to put such options directly into
2453@code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2454@code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2455
2456However, remember that some @file{Makefile} variables are reserved by
2457the GNU Coding Standards for the use of the ``user''---the person
2458building the package.  For instance, @code{CFLAGS} is one such variable.
2459
2460Sometimes package developers are tempted to set user variables such as
2461@code{CFLAGS} because it appears to make their job easier.  However, the
2462package itself should never set a user variable, particularly not to
2463include switches that are required for proper compilation of the
2464package.  Since these variables are documented as being for the package
2465builder, that person rightfully expects to be able to override any of
2466these variables at build time.  If the package developer needs to add
2467switches without interfering with the user, the proper way to do that is
2468to introduce an additional variable.  Automake makes this easy by
2469introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2470automake, GNU Automake}), but the concept is the same even if
2471Automake is not used.
2472@end defvar
2473
2474@defvar configure_input
2475@ovindex configure_input
2476A comment saying that the file was generated automatically by
2477@command{configure} and giving the name of the input file.
2478@code{AC_OUTPUT} adds a comment line containing this variable to the top
2479of every makefile it creates.  For other files, you should
2480reference this variable in a comment at the top of each input file.  For
2481example, an input shell script should begin like this:
2482
2483@example
2484#!/bin/sh
2485# @@configure_input@@
2486@end example
2487
2488@noindent
2489The presence of that line also reminds people editing the file that it
2490needs to be processed by @command{configure} in order to be used.
2491@end defvar
2492
2493@defvar CPPFLAGS
2494@evindex CPPFLAGS
2495@ovindex CPPFLAGS
2496Preprocessor options for the C, C++, Objective C, and Objective C++
2497preprocessors and compilers.  If
2498it is not set in the environment when @command{configure} runs, the default
2499value is empty.  @command{configure} uses this variable when preprocessing
2500or compiling programs to test for C, C++, Objective C, and Objective C++
2501features.
2502
2503This variable's contents should contain options like @option{-I},
2504@option{-D}, and @option{-U} that affect only the behavior of the
2505preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2506can do if an option affects other phases of the compiler as well.
2507
2508Currently, @command{configure} always links as part of a single
2509invocation of the compiler that also preprocesses and compiles, so it
2510uses this variable also when linking programs.  However, it is unwise to
2511depend on this behavior because the GNU Coding Standards do
2512not require it and many packages do not use @code{CPPFLAGS} when linking
2513programs.
2514
2515@xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2516might run into.
2517@end defvar
2518
2519@defvar CXXFLAGS
2520@evindex CXXFLAGS
2521@ovindex CXXFLAGS
2522Debugging and optimization options for the C++ compiler.  It acts like
2523@code{CFLAGS}, but for C++ instead of C.
2524@end defvar
2525
2526@defvar DEFS
2527@ovindex DEFS
2528@option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2529is called, @command{configure} replaces @samp{@@DEFS@@} with
2530@option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2531variable is not defined while @command{configure} is performing its tests,
2532only when creating the output files.  @xref{Setting Output Variables}, for
2533how to check the results of previous tests.
2534@end defvar
2535
2536@defvar ECHO_C
2537@defvarx ECHO_N
2538@defvarx ECHO_T
2539@ovindex ECHO_C
2540@ovindex ECHO_N
2541@ovindex ECHO_T
2542How does one suppress the trailing newline from @command{echo} for
2543question-answer message pairs?  These variables provide a way:
2544
2545@example
2546echo $ECHO_N "And the winner is... $ECHO_C"
2547sleep 100000000000
2548echo "$@{ECHO_T@}dead."
2549@end example
2550
2551@noindent
2552Some old and uncommon @command{echo} implementations offer no means to
2553achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2554want to use it.
2555@end defvar
2556
2557@defvar ERLCFLAGS
2558@evindex ERLCFLAGS
2559@ovindex ERLCFLAGS
2560Debugging and optimization options for the Erlang compiler.  If it is not set
2561in the environment when @command{configure} runs, the default value is empty.
2562@command{configure} uses this variable when compiling
2563programs to test for Erlang features.
2564@end defvar
2565
2566@defvar FCFLAGS
2567@evindex FCFLAGS
2568@ovindex FCFLAGS
2569Debugging and optimization options for the Fortran compiler.  If it
2570is not set in the environment when @command{configure} runs, the default
2571value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2572@command{configure} uses this variable when compiling or linking
2573programs to test for Fortran features.
2574@end defvar
2575
2576@defvar FFLAGS
2577@evindex FFLAGS
2578@ovindex FFLAGS
2579Debugging and optimization options for the Fortran 77 compiler.  If it
2580is not set in the environment when @command{configure} runs, the default
2581value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2582@command{configure} uses this variable when compiling or linking
2583programs to test for Fortran 77 features.
2584@end defvar
2585
2586@defvar LDFLAGS
2587@evindex LDFLAGS
2588@ovindex LDFLAGS
2589Options for the linker.  If it is not set
2590in the environment when @command{configure} runs, the default value is empty.
2591@command{configure} uses this variable when linking programs to test for
2592C, C++, Objective C, Objective C++, Fortran, and Go features.
2593
2594This variable's contents should contain options like @option{-s} and
2595@option{-L} that affect only the behavior of the linker.  Please see the
2596explanation of @code{CFLAGS} for what you can do if an option also
2597affects other phases of the compiler.
2598
2599Don't use this variable to pass library names
2600(@option{-l}) to the linker; use @code{LIBS} instead.
2601@end defvar
2602
2603@defvar LIBS
2604@evindex LIBS
2605@ovindex LIBS
2606@option{-l} options to pass to the linker.  The default value is empty,
2607but some Autoconf macros may prepend extra libraries to this variable if
2608those libraries are found and provide necessary functions, see
2609@ref{Libraries}.  @command{configure} uses this variable when linking
2610programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2611features.
2612@end defvar
2613
2614@defvar OBJCFLAGS
2615@evindex OBJCFLAGS
2616@ovindex OBJCFLAGS
2617Debugging and optimization options for the Objective C compiler.  It
2618acts like @code{CFLAGS}, but for Objective C instead of C.
2619@end defvar
2620
2621@defvar OBJCXXFLAGS
2622@evindex OBJCXXFLAGS
2623@ovindex OBJCXXFLAGS
2624Debugging and optimization options for the Objective C++ compiler.  It
2625acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2626@end defvar
2627
2628@defvar GOFLAGS
2629@evindex GOFLAGS
2630@ovindex GOFLAGS
2631Debugging and optimization options for the Go compiler.  It acts like
2632@code{CFLAGS}, but for Go instead of C.
2633@end defvar
2634
2635@defvar builddir
2636@ovindex builddir
2637Rigorously equal to @samp{.}.  Added for symmetry only.
2638@end defvar
2639
2640@defvar abs_builddir
2641@ovindex abs_builddir
2642Absolute name of @code{builddir}.
2643@end defvar
2644
2645@defvar top_builddir
2646@ovindex top_builddir
2647The relative name of the top level of the current build tree.  In the
2648top-level directory, this is the same as @code{builddir}.
2649@end defvar
2650
2651@defvar top_build_prefix
2652@ovindex top_build_prefix
2653The relative name of the top level of the current build tree with final
2654slash if nonempty.  This is the same as @code{top_builddir}, except that
2655it contains zero or more runs of @code{../}, so it should not be
2656appended with a slash for concatenation.  This helps for @command{make}
2657implementations that otherwise do not treat @file{./file} and @file{file}
2658as equal in the toplevel build directory.
2659@end defvar
2660
2661@defvar abs_top_builddir
2662@ovindex abs_top_builddir
2663Absolute name of @code{top_builddir}.
2664@end defvar
2665
2666@defvar srcdir
2667@ovindex srcdir
2668The name of the directory that contains the source code for
2669that makefile.
2670@end defvar
2671
2672@defvar abs_srcdir
2673@ovindex abs_srcdir
2674Absolute name of @code{srcdir}.
2675@end defvar
2676
2677@defvar top_srcdir
2678@ovindex top_srcdir
2679The name of the top-level source code directory for the
2680package.  In the top-level directory, this is the same as @code{srcdir}.
2681@end defvar
2682
2683@defvar abs_top_srcdir
2684@ovindex abs_top_srcdir
2685Absolute name of @code{top_srcdir}.
2686@end defvar
2687
2688@node Installation Directory Variables
2689@subsection Installation Directory Variables
2690@cindex Installation directories
2691@cindex Directories, installation
2692
2693The following variables specify the directories for
2694package installation, see @ref{Directory Variables, , Variables for
2695Installation Directories, standards, The GNU Coding
2696Standards}, for more information.  Each variable corresponds to an
2697argument of @command{configure}; trailing slashes are stripped so that
2698expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2699between directory names.  See the end of this section for
2700details on when and how to use these variables.
2701
2702@defvar bindir
2703@ovindex bindir
2704The directory for installing executables that users run.
2705@end defvar
2706
2707@defvar datadir
2708@ovindex datadir
2709The directory for installing idiosyncratic read-only
2710architecture-independent data.
2711@end defvar
2712
2713@defvar datarootdir
2714@ovindex datarootdir
2715The root of the directory tree for read-only architecture-independent
2716data files.
2717@end defvar
2718
2719@defvar docdir
2720@ovindex docdir
2721The directory for installing documentation files (other than Info and
2722man).
2723@end defvar
2724
2725@defvar dvidir
2726@ovindex dvidir
2727The directory for installing documentation files in DVI format.
2728@end defvar
2729
2730@defvar exec_prefix
2731@ovindex exec_prefix
2732The installation prefix for architecture-dependent files.  By default
2733it's the same as @code{prefix}.  You should avoid installing anything
2734directly to @code{exec_prefix}.  However, the default value for
2735directories containing architecture-dependent files should be relative
2736to @code{exec_prefix}.
2737@end defvar
2738
2739@defvar htmldir
2740@ovindex htmldir
2741The directory for installing HTML documentation.
2742@end defvar
2743
2744@defvar includedir
2745@ovindex includedir
2746The directory for installing C header files.
2747@end defvar
2748
2749@defvar infodir
2750@ovindex infodir
2751The directory for installing documentation in Info format.
2752@end defvar
2753
2754@defvar libdir
2755@ovindex libdir
2756The directory for installing object code libraries.
2757@end defvar
2758
2759@defvar libexecdir
2760@ovindex libexecdir
2761The directory for installing executables that other programs run.
2762@end defvar
2763
2764@defvar localedir
2765@ovindex localedir
2766The directory for installing locale-dependent but
2767architecture-independent data, such as message catalogs.  This directory
2768usually has a subdirectory per locale.
2769@end defvar
2770
2771@defvar localstatedir
2772@ovindex localstatedir
2773The directory for installing modifiable single-machine data.
2774@end defvar
2775
2776@defvar mandir
2777@ovindex mandir
2778The top-level directory for installing documentation in man format.
2779@end defvar
2780
2781@defvar oldincludedir
2782@ovindex oldincludedir
2783The directory for installing C header files for non-GCC compilers.
2784@end defvar
2785
2786@defvar pdfdir
2787@ovindex pdfdir
2788The directory for installing PDF documentation.
2789@end defvar
2790
2791@defvar prefix
2792@ovindex prefix
2793The common installation prefix for all files.  If @code{exec_prefix}
2794is defined to a different value, @code{prefix} is used only for
2795architecture-independent files.
2796@end defvar
2797
2798@defvar psdir
2799@ovindex psdir
2800The directory for installing PostScript documentation.
2801@end defvar
2802
2803@defvar sbindir
2804@ovindex sbindir
2805The directory for installing executables that system
2806administrators run.
2807@end defvar
2808
2809@defvar sharedstatedir
2810@ovindex sharedstatedir
2811The directory for installing modifiable architecture-independent data.
2812@end defvar
2813
2814@defvar sysconfdir
2815@ovindex sysconfdir
2816The directory for installing read-only single-machine data.
2817@end defvar
2818
2819
2820Most of these variables have values that rely on @code{prefix} or
2821@code{exec_prefix}.  It is deliberate that the directory output
2822variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2823replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2824@samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2825
2826This behavior is mandated by the GNU Coding Standards, so that when
2827the user runs:
2828
2829@table @samp
2830@item make
2831she can still specify a different prefix from the one specified to
2832@command{configure}, in which case, if needed, the package should hard
2833code dependencies corresponding to the make-specified prefix.
2834
2835@item make install
2836she can specify a different installation location, in which case the
2837package @emph{must} still depend on the location which was compiled in
2838(i.e., never recompile when @samp{make install} is run).  This is an
2839extremely important feature, as many people may decide to install all
2840the files of a package grouped together, and then install links from
2841the final locations to there.
2842@end table
2843
2844In order to support these features, it is essential that
2845@code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2846so that its value can be expanded based
2847on the current value of @code{prefix}.
2848
2849A corollary is that you should not use these variables except in
2850makefiles.  For instance, instead of trying to evaluate @code{datadir}
2851in @file{configure} and hard-coding it in makefiles using
2852e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2853you should add
2854@option{-DDATADIR='$(datadir)'} to your makefile's definition of
2855@code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2856
2857Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2858@code{bindir} and friends in your shell scripts and other files; instead,
2859let @command{make} manage their replacement.  For instance Autoconf
2860ships templates of its shell scripts ending with @samp{.in}, and uses a
2861makefile snippet similar to the following to build scripts like
2862@command{autoheader} and @command{autom4te}:
2863
2864@example
2865@group
2866edit = sed \
2867        -e 's|@@bindir[@@]|$(bindir)|g' \
2868        -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2869        -e 's|@@prefix[@@]|$(prefix)|g'
2870@end group
2871
2872@group
2873autoheader autom4te: Makefile
2874        rm -f $@@ $@@.tmp
2875        srcdir=''; \
2876          test -f ./$@@.in || srcdir=$(srcdir)/; \
2877          $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2878@c $$ restore font-lock
2879        chmod +x $@@.tmp
2880        chmod a-w $@@.tmp
2881        mv $@@.tmp $@@
2882@end group
2883
2884@group
2885autoheader: $(srcdir)/autoheader.in
2886autom4te: $(srcdir)/autom4te.in
2887@end group
2888@end example
2889
2890Some details are noteworthy:
2891
2892@table @asis
2893@item @samp{@@bindir[@@]}
2894The brackets prevent @command{configure} from replacing
2895@samp{@@bindir@@} in the Sed expression itself.
2896Brackets are preferable to a backslash here, since
2897Posix says @samp{\@@} is not portable.
2898
2899@item @samp{$(bindir)}
2900Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2901instead.
2902
2903@item @samp{$(pkgdatadir)}
2904The example takes advantage of the variable @samp{$(pkgdatadir)}
2905provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2906
2907@item @samp{/}
2908Don't use @samp{/} in the Sed expressions that replace file names since
2909most likely the
2910variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2911Use a shell metacharacter instead, such as @samp{|}.
2912
2913@item special characters
2914File names, file name components, and the value of @code{VPATH} should
2915not contain shell metacharacters or white
2916space.  @xref{Special Chars in Variables}.
2917
2918@item dependency on @file{Makefile}
2919Since @code{edit} uses values that depend on the configuration specific
2920values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2921the output depends on @file{Makefile}, not @file{configure.ac}.
2922
2923@item @samp{$@@}
2924The main rule is generic, and uses @samp{$@@} extensively to
2925avoid the need for multiple copies of the rule.
2926
2927@item Separated dependencies and single suffix rules
2928You can't use them!  The above snippet cannot be (portably) rewritten
2929as:
2930
2931@example
2932autoconf autoheader: Makefile
2933@group
2934.in:
2935        rm -f $@@ $@@.tmp
2936        $(edit) $< >$@@.tmp
2937        chmod +x $@@.tmp
2938        mv $@@.tmp $@@
2939@end group
2940@end example
2941
2942@xref{Single Suffix Rules}, for details.
2943
2944@item @samp{$(srcdir)}
2945Be sure to specify the name of the source directory,
2946otherwise the package won't support separated builds.
2947@end table
2948
2949For the more specific installation of Erlang libraries, the following variables
2950are defined:
2951
2952@defvar ERLANG_INSTALL_LIB_DIR
2953@ovindex ERLANG_INSTALL_LIB_DIR
2954@acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2955The common parent directory of Erlang library installation directories.
2956This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2957macro in @file{configure.ac}.
2958@end defvar
2959
2960@defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2961@ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2962@acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2963The installation directory for Erlang library @var{library}.
2964This variable is set by using the
2965@samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2966macro in @file{configure.ac}.
2967@end defvar
2968
2969@xref{Erlang Libraries}, for details.
2970
2971
2972@node Changed Directory Variables
2973@subsection Changed Directory Variables
2974@cindex @file{datarootdir}
2975
2976In Autoconf 2.60, the set of directory variables has changed, and the
2977defaults of some variables have been adjusted
2978(@pxref{Installation Directory Variables}) to changes in the
2979GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2980@file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2981upgrading from an earlier Autoconf version, you may need to adjust your files
2982to ensure that the directory variables are substituted correctly
2983(@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2984in place.  For example, in a @file{Makefile.in}, adding
2985
2986@example
2987datarootdir = @@datarootdir@@
2988@end example
2989
2990@noindent
2991is usually sufficient.  If you use Automake to create @file{Makefile.in},
2992it will add this for you.
2993
2994To help with the transition, Autoconf warns about files that seem to use
2995@code{datarootdir} without defining it.  In some cases, it then expands
2996the value of @code{$datarootdir} in substitutions of the directory
2997variables.  The following example shows such a warning:
2998
2999@example
3000$ @kbd{cat configure.ac}
3001AC_INIT
3002AC_CONFIG_FILES([Makefile])
3003AC_OUTPUT
3004$ @kbd{cat Makefile.in}
3005prefix = @@prefix@@
3006datadir = @@datadir@@
3007$ @kbd{autoconf}
3008$ @kbd{configure}
3009configure: creating ./config.status
3010config.status: creating Makefile
3011config.status: WARNING:
3012               Makefile.in seems to ignore the --datarootdir setting
3013$ @kbd{cat Makefile}
3014prefix = /usr/local
3015datadir = $@{prefix@}/share
3016@end example
3017
3018Usually one can easily change the file to accommodate both older and newer
3019Autoconf releases:
3020
3021@example
3022$ @kbd{cat Makefile.in}
3023prefix = @@prefix@@
3024datarootdir = @@datarootdir@@
3025datadir = @@datadir@@
3026$ @kbd{configure}
3027configure: creating ./config.status
3028config.status: creating Makefile
3029$ @kbd{cat Makefile}
3030prefix = /usr/local
3031datarootdir = $@{prefix@}/share
3032datadir = $@{datarootdir@}
3033@end example
3034
3035@acindex{DATAROOTDIR_CHECKED}
3036In some cases, however, the checks may not be able to detect that a suitable
3037initialization of @code{datarootdir} is in place, or they may fail to detect
3038that such an initialization is necessary in the output file.  If, after
3039auditing your package, there are still spurious @file{configure} warnings about
3040@code{datarootdir}, you may add the line
3041
3042@example
3043AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3044@end example
3045
3046@noindent
3047to your @file{configure.ac} to disable the warnings.  This is an exception
3048to the usual rule that you should not define a macro whose name begins with
3049@code{AC_} (@pxref{Macro Names}).
3050
3051
3052
3053@node Build Directories
3054@subsection Build Directories
3055@cindex Build directories
3056@cindex Directories, build
3057
3058You can support compiling a software package for several architectures
3059simultaneously from the same copy of the source code.  The object files
3060for each architecture are kept in their own directory.
3061
3062To support doing this, @command{make} uses the @code{VPATH} variable to
3063find the files that are in the source directory.  GNU Make
3064can do this.  Most other recent @command{make} programs can do this as
3065well, though they may have difficulties and it is often simpler to
3066recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3067@command{make} programs do not support @code{VPATH}; when using them, the
3068source code must be in the same directory as the object files.
3069
3070If you are using GNU Automake, the remaining details in this
3071section are already covered for you, based on the contents of your
3072@file{Makefile.am}.  But if you are using Autoconf in isolation, then
3073supporting @code{VPATH} requires the following in your
3074@file{Makefile.in}:
3075
3076@example
3077srcdir = @@srcdir@@
3078VPATH = @@srcdir@@
3079@end example
3080
3081Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3082listed in VPATH}.
3083
3084@command{configure} substitutes the correct value for @code{srcdir} when
3085it produces @file{Makefile}.
3086
3087Do not use the @command{make} variable @code{$<}, which expands to the
3088file name of the file in the source directory (found with @code{VPATH}),
3089except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3090which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3091versions of @command{make} do not set @code{$<} in explicit rules; they
3092expand it to an empty value.
3093
3094Instead, Make command lines should always refer to source
3095files by prefixing them with @samp{$(srcdir)/}.  For example:
3096
3097@example
3098time.info: time.texinfo
3099        $(MAKEINFO) '$(srcdir)/time.texinfo'
3100@end example
3101
3102@node Automatic Remaking
3103@subsection Automatic Remaking
3104@cindex Automatic remaking
3105@cindex Remaking automatically
3106
3107You can put rules like the following in the top-level @file{Makefile.in}
3108for a package to automatically update the configuration information when
3109you change the configuration files.  This example includes all of the
3110optional files, such as @file{aclocal.m4} and those related to
3111configuration header files.  Omit from the @file{Makefile.in} rules for
3112any of these files that your package does not use.
3113
3114The @samp{$(srcdir)/} prefix is included because of limitations in the
3115@code{VPATH} mechanism.
3116
3117The @file{stamp-} files are necessary because the timestamps of
3118@file{config.h.in} and @file{config.h} are not changed if remaking
3119them does not change their contents.  This feature avoids unnecessary
3120recompilation.  You should include the file @file{stamp-h.in} in your
3121package's distribution, so that @command{make} considers
3122@file{config.h.in} up to date.  Don't use @command{touch}
3123(@pxref{touch, , Limitations of Usual Tools}); instead, use
3124@command{echo} (using
3125@command{date} would cause needless differences, hence CVS
3126conflicts, etc.).
3127
3128@example
3129@group
3130$(srcdir)/configure: configure.ac aclocal.m4
3131        cd '$(srcdir)' && autoconf
3132
3133# autoheader might not change config.h.in, so touch a stamp file.
3134$(srcdir)/config.h.in: stamp-h.in
3135$(srcdir)/stamp-h.in: configure.ac aclocal.m4
3136        cd '$(srcdir)' && autoheader
3137        echo timestamp > '$(srcdir)/stamp-h.in'
3138
3139config.h: stamp-h
3140stamp-h: config.h.in config.status
3141        ./config.status
3142
3143Makefile: Makefile.in config.status
3144        ./config.status
3145
3146config.status: configure
3147        ./config.status --recheck
3148@end group
3149@end example
3150
3151@noindent
3152(Be careful if you copy these lines directly into your makefile, as you
3153need to convert the indented lines to start with the tab character.)
3154
3155In addition, you should use
3156
3157@example
3158AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3159@end example
3160
3161@noindent
3162so @file{config.status} ensures that @file{config.h} is considered up to
3163date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3164
3165@xref{config.status Invocation}, for more examples of handling
3166configuration-related dependencies.
3167
3168@node Configuration Headers
3169@section Configuration Header Files
3170@cindex Configuration Header
3171@cindex @file{config.h}
3172
3173When a package contains more than a few tests that define C preprocessor
3174symbols, the command lines to pass @option{-D} options to the compiler
3175can get quite long.  This causes two problems.  One is that the
3176@command{make} output is hard to visually scan for errors.  More
3177seriously, the command lines can exceed the length limits of some
3178operating systems.  As an alternative to passing @option{-D} options to
3179the compiler, @command{configure} scripts can create a C header file
3180containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3181macro selects this kind of output.  Though it can be called anywhere
3182between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3183it right after @code{AC_INIT}.
3184
3185The package should @samp{#include} the configuration header file before
3186any other header files, to prevent inconsistencies in declarations (for
3187example, if it redefines @code{const}).
3188
3189To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3190option (or @option{-I..}; whichever directory contains @file{config.h}).
3191Even if you use @samp{#include "config.h"}, the preprocessor searches only
3192the directory of the currently read file, i.e., the source directory, not
3193the build directory.
3194
3195With the appropriate @option{-I} option, you can use
3196@samp{#include <config.h>}.  Actually, it's a good habit to use it,
3197because in the rare case when the source directory contains another
3198@file{config.h}, the build directory should be searched first.
3199
3200
3201@defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3202@acindex{CONFIG_HEADERS}
3203@cvindex HAVE_CONFIG_H
3204This macro is one of the instantiating macros; see @ref{Configuration
3205Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3206blank-or-newline-separated list @var{header} containing C preprocessor
3207@code{#define} statements, and replace @samp{@@DEFS@@} in generated
3208files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3209The usual name for @var{header} is @file{config.h}.
3210
3211If @var{header} already exists and its contents are identical to what
3212@code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3213making some changes in the configuration without needlessly causing
3214object files that depend on the header file to be recompiled.
3215
3216Usually the input file is named @file{@var{header}.in}; however, you can
3217override the input file name by appending to @var{header} a
3218colon-separated list of input files.  For example, you might need to make
3219the input file name acceptable to DOS variants:
3220
3221@example
3222AC_CONFIG_HEADERS([config.h:config.hin])
3223@end example
3224
3225@end defmac
3226
3227@defmac AH_HEADER
3228@ahindex{HEADER}
3229This macro is defined as the name of the first declared config header
3230and undefined if no config headers have been declared up to this point.
3231A third-party macro may, for example, require use of a config header
3232without invoking AC_CONFIG_HEADERS twice, like this:
3233
3234@example
3235AC_CONFIG_COMMANDS_PRE(
3236        [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3237@end example
3238
3239@end defmac
3240
3241@xref{Configuration Actions}, for more details on @var{header}.
3242
3243@menu
3244* Header Templates::            Input for the configuration headers
3245* autoheader Invocation::       How to create configuration templates
3246* Autoheader Macros::           How to specify CPP templates
3247@end menu
3248
3249@node Header Templates
3250@subsection Configuration Header Templates
3251@cindex Configuration Header Template
3252@cindex Header templates
3253@cindex @file{config.h.in}
3254
3255Your distribution should contain a template file that looks as you want
3256the final header file to look, including comments, with @code{#undef}
3257statements which are used as hooks.  For example, suppose your
3258@file{configure.ac} makes these calls:
3259
3260@example
3261AC_CONFIG_HEADERS([conf.h])
3262AC_CHECK_HEADERS([unistd.h])
3263@end example
3264
3265@noindent
3266Then you could have code like the following in @file{conf.h.in}.
3267The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3268to 1, if and only if the system has @file{unistd.h}.
3269
3270@example
3271@group
3272/* Define as 1 if you have unistd.h.  */
3273#undef HAVE_UNISTD_H
3274@end group
3275@end example
3276
3277The format of the template file is stricter than what the C preprocessor
3278is required to accept.  A directive line should contain only whitespace,
3279@samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3280instead of @samp{#undef}, or of comments on the same line as
3281@samp{#undef}, is strongly discouraged.  Each hook should only be listed
3282once.  Other preprocessor lines, such as @samp{#ifdef} or
3283@samp{#include}, are copied verbatim from the template into the
3284generated header.
3285
3286Since it is a tedious task to keep a template header up to date, you may
3287use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3288
3289During the instantiation of the header, each @samp{#undef} line in the
3290template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3291appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3292been executed during the @command{configure} run, the @samp{#undef} line is
3293commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3294on many systems, it can be implicitly defined by the compiler, and
3295undefining it in the header would then break compilation of subsequent
3296headers.)
3297
3298Currently, @emph{all} remaining @samp{#undef} lines in the header
3299template are commented out, whether or not there was a corresponding
3300@samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3301for future releases of Autoconf.
3302
3303Generally speaking, since you should not use @samp{#define}, and you
3304cannot guarantee whether a @samp{#undef} directive in the header
3305template will be converted to a @samp{#define} or commented out in the
3306generated header file, the template file cannot be used for conditional
3307definition effects.  Consequently, if you need to use the construct
3308
3309@example
3310@group
3311#ifdef THIS
3312# define THAT
3313#endif
3314@end group
3315@end example
3316
3317@noindent
3318you must place it outside of the template.
3319If you absolutely need to hook it to the config header itself, please put
3320the directives to a separate file, and @samp{#include} that file from the
3321config header template.  If you are using @command{autoheader}, you would
3322probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3323
3324
3325@node autoheader Invocation
3326@subsection Using @command{autoheader} to Create @file{config.h.in}
3327@cindex @command{autoheader}
3328
3329The @command{autoheader} program can create a template file of C
3330@samp{#define} statements for @command{configure} to use.
3331It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3332@file{configure} sources to determine the name of the template.
3333(If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3334input file name, @command{autoheader} uses the first one.)
3335
3336It is recommended that only one input file is used.  If you want to append
3337a boilerplate code, it is preferable to use
3338@samp{AH_BOTTOM([#include <conf_post.h>])}.
3339File @file{conf_post.h} is not processed during the configuration then,
3340which make things clearer.  Analogically, @code{AH_TOP} can be used to
3341prepend a boilerplate code.
3342
3343In order to do its job, @command{autoheader} needs you to document all
3344of the symbols that you might use.  Typically this is done via an
3345@code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3346is a literal symbol and whose third argument describes the symbol
3347(@pxref{Defining Symbols}).  Alternatively, you can use
3348@code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3349suitable input file for a subsequent configuration header file.
3350Symbols defined by Autoconf's builtin tests are already documented properly;
3351you need to document only those that you
3352define yourself.
3353
3354You might wonder why @command{autoheader} is needed: after all, why
3355would @command{configure} need to ``patch'' a @file{config.h.in} to
3356produce a @file{config.h} instead of just creating @file{config.h} from
3357scratch?  Well, when everything rocks, the answer is just that we are
3358wasting our time maintaining @command{autoheader}: generating
3359@file{config.h} directly is all that is needed.  When things go wrong,
3360however, you'll be thankful for the existence of @command{autoheader}.
3361
3362The fact that the symbols are documented is important in order to
3363@emph{check} that @file{config.h} makes sense.  The fact that there is a
3364well-defined list of symbols that should be defined (or not) is
3365also important for people who are porting packages to environments where
3366@command{configure} cannot be run: they just have to @emph{fill in the
3367blanks}.
3368
3369But let's come back to the point: the invocation of @command{autoheader}@dots{}
3370
3371If you give @command{autoheader} an argument, it uses that file instead
3372of @file{configure.ac} and writes the header file to the standard output
3373instead of to @file{config.h.in}.  If you give @command{autoheader} an
3374argument of @option{-}, it reads the standard input instead of
3375@file{configure.ac} and writes the header file to the standard output.
3376
3377@command{autoheader} accepts the following options:
3378
3379@table @option
3380@item --help
3381@itemx -h
3382Print a summary of the command line options and exit.
3383
3384@item --version
3385@itemx -V
3386Print the version number of Autoconf and exit.
3387
3388@item --verbose
3389@itemx -v
3390Report processing steps.
3391
3392@item --debug
3393@itemx -d
3394Don't remove the temporary files.
3395
3396@item --force
3397@itemx -f
3398Remake the template file even if newer than its input files.
3399
3400@item --include=@var{dir}
3401@itemx -I @var{dir}
3402Append @var{dir} to the include path.  Multiple invocations accumulate.
3403
3404@item --prepend-include=@var{dir}
3405@itemx -B @var{dir}
3406Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3407
3408@item --warnings=@var{category}
3409@itemx -W @var{category}
3410@evindex WARNINGS
3411Report the warnings related to @var{category} (which can actually be a
3412comma separated list).  Current categories include:
3413
3414@table @samp
3415@item obsolete
3416report the uses of obsolete constructs
3417
3418@item all
3419report all the warnings
3420
3421@item none
3422report none
3423
3424@item error
3425treats warnings as errors
3426
3427@item no-@var{category}
3428disable warnings falling into @var{category}
3429@end table
3430
3431@end table
3432
3433
3434
3435@node Autoheader Macros
3436@subsection Autoheader Macros
3437@cindex Autoheader macros
3438
3439@command{autoheader} scans @file{configure.ac} and figures out which C
3440preprocessor symbols it might define.  It knows how to generate
3441templates for symbols defined by @code{AC_CHECK_HEADERS},
3442@code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3443symbol, you must define a template for it.  If there are missing
3444templates, @command{autoheader} fails with an error message.
3445
3446The template for a @var{symbol} is created
3447by @command{autoheader} from
3448the @var{description} argument to an @code{AC_DEFINE};
3449see @ref{Defining Symbols}.
3450
3451For special needs, you can use the following macros.
3452
3453
3454@defmac AH_TEMPLATE (@var{key}, @var{description})
3455@ahindex{TEMPLATE}
3456Tell @command{autoheader} to generate a template for @var{key}.  This macro
3457generates standard templates just like @code{AC_DEFINE} when a
3458@var{description} is given.
3459
3460For example:
3461
3462@example
3463AH_TEMPLATE([CRAY_STACKSEG_END],
3464            [Define to one of _getb67, GETB67, getb67
3465             for Cray-2 and Cray-YMP systems.  This
3466             function is required for alloca.c support
3467             on those systems.])
3468@end example
3469
3470@noindent
3471generates the following template, with the description properly
3472justified.
3473
3474@example
3475/* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3476   Cray-YMP systems.  This function is required for alloca.c
3477   support on those systems.  */
3478#undef CRAY_STACKSEG_END
3479@end example
3480@end defmac
3481
3482
3483@defmac AH_VERBATIM (@var{key}, @var{template})
3484@ahindex{VERBATIM}
3485Tell @command{autoheader} to include the @var{template} as-is in the header
3486template file.  This @var{template} is associated with the @var{key},
3487which is used to sort all the different templates and guarantee their
3488uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3489@end defmac
3490
3491
3492@defmac AH_TOP (@var{text})
3493@ahindex{TOP}
3494Include @var{text} at the top of the header template file.
3495@end defmac
3496
3497
3498@defmac AH_BOTTOM (@var{text})
3499@ahindex{BOTTOM}
3500Include @var{text} at the bottom of the header template file.
3501@end defmac
3502
3503
3504Please note that @var{text} gets included ``verbatim'' to the template file,
3505not to the resulting config header, so it can easily get mangled when the
3506template is processed.  There is rarely a need for something other than
3507
3508@example
3509AH_BOTTOM([#include <custom.h>])
3510@end example
3511
3512
3513
3514@node Configuration Commands
3515@section Running Arbitrary Configuration Commands
3516@cindex Configuration commands
3517@cindex Commands for configuration
3518
3519You can execute arbitrary commands before, during, and after
3520@file{config.status} is run.  The three following macros accumulate the
3521commands to run when they are called multiple times.
3522@code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3523@code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3524
3525@anchor{AC_CONFIG_COMMANDS}
3526@defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3527@acindex{CONFIG_COMMANDS}
3528Specify additional shell commands to run at the end of
3529@file{config.status}, and shell commands to initialize any variables
3530from @command{configure}.  Associate the commands with @var{tag}.
3531Since typically the @var{cmds} create a file, @var{tag} should
3532naturally be the name of that file.  If needed, the directory hosting
3533@var{tag} is created.  This macro is one of the instantiating macros;
3534see @ref{Configuration Actions}.
3535
3536Here is an unrealistic example:
3537@example
3538fubar=42
3539AC_CONFIG_COMMANDS([fubar],
3540                   [echo this is extra $fubar, and so on.],
3541                   [fubar=$fubar])
3542@end example
3543
3544Here is a better one:
3545@example
3546AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3547@end example
3548@end defmac
3549
3550The following two macros look similar, but in fact they are not of the same
3551breed: they are executed directly by @file{configure}, so you cannot use
3552@file{config.status} to rerun them.
3553
3554@c Yet it is good to leave them here.  The user sees them together and
3555@c decides which best fits their needs.
3556
3557@defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3558@acindex{CONFIG_COMMANDS_PRE}
3559Execute the @var{cmds} right before creating @file{config.status}.
3560
3561This macro presents the last opportunity to call @code{AC_SUBST},
3562@code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3563@end defmac
3564
3565@defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3566@acindex{CONFIG_COMMANDS_POST}
3567Execute the @var{cmds} right after creating @file{config.status}.
3568@end defmac
3569
3570
3571
3572
3573@node Configuration Links
3574@section Creating Configuration Links
3575@cindex Configuration links
3576@cindex Links for configuration
3577
3578You may find it convenient to create links whose destinations depend upon
3579results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3580creation of relative symbolic links can be delicate when the package is
3581built in a directory different from the source directory.
3582
3583@anchor{AC_CONFIG_LINKS}
3584@defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3585  @ovar{init-cmds})
3586@acindex{CONFIG_LINKS}
3587@cindex Links
3588Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3589the corresponding link name @var{dest}.  Makes a symbolic link if
3590possible, otherwise a hard link if possible, otherwise a copy.  The
3591@var{dest} and @var{source} names should be relative to the top level
3592source or build directory.  This macro is one of the instantiating
3593macros; see @ref{Configuration Actions}.
3594
3595For example, this call:
3596
3597@example
3598AC_CONFIG_LINKS([host.h:config/$machine.h
3599                object.h:config/$obj_format.h])
3600@end example
3601
3602@noindent
3603creates in the current directory @file{host.h} as a link to
3604@file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3605link to @file{@var{srcdir}/config/$obj_format.h}.
3606
3607The tempting value @samp{.} for @var{dest} is invalid: it makes it
3608impossible for @samp{config.status} to guess the links to establish.
3609
3610One can then run:
3611@example
3612./config.status host.h object.h
3613@end example
3614@noindent
3615to create the links.
3616@end defmac
3617
3618
3619
3620@node Subdirectories
3621@section Configuring Other Packages in Subdirectories
3622@cindex Configure subdirectories
3623@cindex Subdirectory configure
3624
3625In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3626makefiles in subdirectories.  However, @command{configure} scripts
3627that control more than one independent package can use
3628@code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3629packages in subdirectories.
3630
3631@defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3632@acindex{CONFIG_SUBDIRS}
3633@ovindex subdirs
3634Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3635@var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3636be a literal, i.e., please do not use:
3637
3638@example
3639@c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3640if test "x$package_foo_enabled" = xyes; then
3641  my_subdirs="$my_subdirs foo"
3642fi
3643AC_CONFIG_SUBDIRS([$my_subdirs])
3644@end example
3645
3646@noindent
3647because this prevents @samp{./configure --help=recursive} from
3648displaying the options of the package @code{foo}.  Instead, you should
3649write:
3650
3651@example
3652if test "x$package_foo_enabled" = xyes; then
3653  AC_CONFIG_SUBDIRS([foo])
3654fi
3655@end example
3656
3657If a given @var{dir} is not found at @command{configure} run time, a
3658warning is reported; if the subdirectory is optional, write:
3659
3660@example
3661if test -d "$srcdir/foo"; then
3662  AC_CONFIG_SUBDIRS([foo])
3663fi
3664@end example
3665
3666@c NB: Yes, below we mean configure.in, not configure.ac.
3667If a given @var{dir} contains @command{configure.gnu}, it is run instead
3668of @command{configure}.  This is for packages that might use a
3669non-Autoconf script @command{Configure}, which can't be called through a
3670wrapper @command{configure} since it would be the same file on
3671case-insensitive file systems.  Likewise, if a @var{dir} contains
3672@file{configure.in} but no @command{configure}, the Cygnus
3673@command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3674
3675The subdirectory @command{configure} scripts are given the same command
3676line options that were given to this @command{configure} script, with minor
3677changes if needed, which include:
3678
3679@itemize @minus
3680@item
3681adjusting a relative name for the cache file;
3682
3683@item
3684adjusting a relative name for the source directory;
3685
3686@item
3687propagating the current value of @code{$prefix}, including if it was
3688defaulted, and if the default values of the top level and of the subdirectory
3689@file{configure} differ.
3690@end itemize
3691
3692This macro also sets the output variable @code{subdirs} to the list of
3693directories @samp{@var{dir} @dots{}}.  Make rules can use
3694this variable to determine which subdirectories to recurse into.
3695
3696This macro may be called multiple times.
3697@end defmac
3698
3699@node Default Prefix
3700@section Default Prefix
3701@cindex Install prefix
3702@cindex Prefix for install
3703
3704By default, @command{configure} sets the prefix for files it installs to
3705@file{/usr/local}.  The user of @command{configure} can select a different
3706prefix using the @option{--prefix} and @option{--exec-prefix} options.
3707There are two ways to change the default: when creating
3708@command{configure}, and when running it.
3709
3710Some software packages might want to install in a directory other than
3711@file{/usr/local} by default.  To accomplish that, use the
3712@code{AC_PREFIX_DEFAULT} macro.
3713
3714@defmac AC_PREFIX_DEFAULT (@var{prefix})
3715@acindex{PREFIX_DEFAULT}
3716Set the default installation prefix to @var{prefix} instead of
3717@file{/usr/local}.
3718@end defmac
3719
3720It may be convenient for users to have @command{configure} guess the
3721installation prefix from the location of a related program that they
3722have already installed.  If you wish to do that, you can call
3723@code{AC_PREFIX_PROGRAM}.
3724
3725@anchor{AC_PREFIX_PROGRAM}
3726@defmac AC_PREFIX_PROGRAM (@var{program})
3727@acindex{PREFIX_PROGRAM}
3728If the user did not specify an installation prefix (using the
3729@option{--prefix} option), guess a value for it by looking for
3730@var{program} in @env{PATH}, the way the shell does.  If @var{program}
3731is found, set the prefix to the parent of the directory containing
3732@var{program}, else default the prefix as described above
3733(@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3734@var{program} is @code{gcc} and the @env{PATH} contains
3735@file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3736@end defmac
3737
3738
3739
3740@c ======================================================== Existing tests
3741
3742@node Existing Tests
3743@chapter Existing Tests
3744
3745These macros test for particular system features that packages might
3746need or want to use.  If you need to test for a kind of feature that
3747none of these macros check for, you can probably do it by calling
3748primitive test macros with appropriate arguments (@pxref{Writing
3749Tests}).
3750
3751These tests print messages telling the user which feature they're
3752checking for, and what they find.  They cache their results for future
3753@command{configure} runs (@pxref{Caching Results}).
3754
3755Some of these macros set output variables.  @xref{Makefile
3756Substitutions}, for how to get their values.  The phrase ``define
3757@var{name}'' is used below as a shorthand to mean ``define the C
3758preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3759Symbols}, for how to get those symbol definitions into your program.
3760
3761@menu
3762* Common Behavior::             Macros' standard schemes
3763* Alternative Programs::        Selecting between alternative programs
3764* Files::                       Checking for the existence of files
3765* Libraries::                   Library archives that might be missing
3766* Library Functions::           C library functions that might be missing
3767* Header Files::                Header files that might be missing
3768* Declarations::                Declarations that may be missing
3769* Structures::                  Structures or members that might be missing
3770* Types::                       Types that might be missing
3771* Compilers and Preprocessors::  Checking for compiling programs
3772* System Services::             Operating system services
3773* Posix Variants::              Special kludges for specific Posix variants
3774* Erlang Libraries::            Checking for the existence of Erlang libraries
3775@end menu
3776
3777@node Common Behavior
3778@section Common Behavior
3779@cindex Common autoconf behavior
3780
3781Much effort has been expended to make Autoconf easy to learn.  The most
3782obvious way to reach this goal is simply to enforce standard interfaces
3783and behaviors, avoiding exceptions as much as possible.  Because of
3784history and inertia, unfortunately, there are still too many exceptions
3785in Autoconf; nevertheless, this section describes some of the common
3786rules.
3787
3788@menu
3789* Standard Symbols::            Symbols defined by the macros
3790* Default Includes::            Includes used by the generic macros
3791@end menu
3792
3793@node Standard Symbols
3794@subsection Standard Symbols
3795@cindex Standard symbols
3796
3797All the generic macros that @code{AC_DEFINE} a symbol as a result of
3798their test transform their @var{argument} values to a standard alphabet.
3799First, @var{argument} is converted to upper case and any asterisks
3800(@samp{*}) are each converted to @samp{P}.  Any remaining characters
3801that are not alphanumeric are converted to underscores.
3802
3803For instance,
3804
3805@example
3806AC_CHECK_TYPES([struct $Expensive*])
3807@end example
3808
3809@noindent
3810defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3811succeeds.
3812
3813
3814@node Default Includes
3815@subsection Default Includes
3816@cindex Default includes
3817@cindex Includes, default
3818
3819Several tests depend upon a set of header files.  Since these headers
3820are not universally available, tests actually have to provide a set of
3821protected includes, such as:
3822
3823@example
3824@group
3825#ifdef TIME_WITH_SYS_TIME
3826# include <sys/time.h>
3827# include <time.h>
3828#else
3829# ifdef HAVE_SYS_TIME_H
3830#  include <sys/time.h>
3831# else
3832#  include <time.h>
3833# endif
3834#endif
3835@end group
3836@end example
3837
3838@noindent
3839Unless you know exactly what you are doing, you should avoid using
3840unconditional includes, and check the existence of the headers you
3841include beforehand (@pxref{Header Files}).
3842
3843Most generic macros use the following macro to provide the default set
3844of includes:
3845
3846@defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3847@acindex{INCLUDES_DEFAULT}
3848Expand to @var{include-directives} if defined, otherwise to:
3849
3850@example
3851@group
3852#include <stdio.h>
3853#ifdef HAVE_SYS_TYPES_H
3854# include <sys/types.h>
3855#endif
3856#ifdef HAVE_SYS_STAT_H
3857# include <sys/stat.h>
3858#endif
3859#ifdef STDC_HEADERS
3860# include <stdlib.h>
3861# include <stddef.h>
3862#else
3863# ifdef HAVE_STDLIB_H
3864#  include <stdlib.h>
3865# endif
3866#endif
3867#ifdef HAVE_STRING_H
3868# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3869#  include <memory.h>
3870# endif
3871# include <string.h>
3872#endif
3873#ifdef HAVE_STRINGS_H
3874# include <strings.h>
3875#endif
3876#ifdef HAVE_INTTYPES_H
3877# include <inttypes.h>
3878#endif
3879#ifdef HAVE_STDINT_H
3880# include <stdint.h>
3881#endif
3882#ifdef HAVE_UNISTD_H
3883# include <unistd.h>
3884#endif
3885@end group
3886@end example
3887
3888If the default includes are used, then check for the presence of these
3889headers and their compatibility, i.e., you don't need to run
3890@code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3891
3892These headers are checked for in the same order as they are included.
3893For instance, on some systems @file{string.h} and @file{strings.h} both
3894exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3895@code{HAVE_STRINGS_H}.
3896@end defmac
3897
3898@node Alternative Programs
3899@section Alternative Programs
3900@cindex Programs, checking
3901
3902These macros check for the presence or behavior of particular programs.
3903They are used to choose between several alternative programs and to
3904decide what to do once one has been chosen.  If there is no macro
3905specifically defined to check for a program you need, and you don't need
3906to check for any special properties of it, then you can use one of the
3907general program-check macros.
3908
3909@menu
3910* Particular Programs::         Special handling to find certain programs
3911* Generic Programs::            How to find other programs
3912@end menu
3913
3914@node Particular Programs
3915@subsection Particular Program Checks
3916
3917These macros check for particular programs---whether they exist, and
3918in some cases whether they support certain features.
3919
3920@defmac AC_PROG_AWK
3921@acindex{PROG_AWK}
3922@ovindex AWK
3923@caindex prog_AWK
3924Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3925order, and set output variable @code{AWK} to the first one that is found.
3926It tries @code{gawk} first because that is reported to be the
3927best implementation.  The result can be overridden by setting the
3928variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3929
3930Using this macro is sufficient to avoid the pitfalls of traditional
3931@command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3932@end defmac
3933
3934@defmac AC_PROG_GREP
3935@acindex{PROG_GREP}
3936@ovindex GREP
3937@caindex prog_GREP
3938Look for the best available @code{grep} or @code{ggrep} that accepts the
3939longest input lines possible, and that supports multiple @option{-e} options.
3940Set the output variable @code{GREP} to whatever is chosen.
3941@xref{grep, , Limitations of Usual Tools}, for more information about
3942portability problems with the @command{grep} command family.  The result
3943can be overridden by setting the @code{GREP} variable and is cached in the
3944@code{ac_cv_path_GREP} variable.
3945@end defmac
3946
3947@defmac AC_PROG_EGREP
3948@acindex{PROG_EGREP}
3949@ovindex EGREP
3950@caindex prog_EGREP
3951Check whether @code{$GREP -E} works, or else look for the best available
3952@code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3953Set the output variable @code{EGREP} to whatever is chosen.  The result
3954can be overridden by setting the @code{EGREP} variable and is cached in the
3955@code{ac_cv_path_EGREP} variable.
3956@end defmac
3957
3958@defmac AC_PROG_FGREP
3959@acindex{PROG_FGREP}
3960@ovindex FGREP
3961@caindex prog_FGREP
3962Check whether @code{$GREP -F} works, or else look for the best available
3963@code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3964Set the output variable @code{FGREP} to whatever is chosen.  The result
3965can be overridden by setting the @code{FGREP} variable and is cached in the
3966@code{ac_cv_path_FGREP} variable.
3967@end defmac
3968
3969@defmac AC_PROG_INSTALL
3970@acindex{PROG_INSTALL}
3971@ovindex INSTALL
3972@ovindex INSTALL_PROGRAM
3973@ovindex INSTALL_DATA
3974@ovindex INSTALL_SCRIPT
3975@caindex path_install
3976Set output variable @code{INSTALL} to the name of a BSD-compatible
3977@command{install} program, if one is found in the current @env{PATH}.
3978Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3979checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3980default directories) to determine @var{dir} (@pxref{Output}).  Also set
3981the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3982@samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3983
3984@samp{@@INSTALL@@} is special, as its value may vary for different
3985configuration files.
3986
3987This macro screens out various instances of @command{install} known not to
3988work.  It prefers to find a C program rather than a shell script, for
3989speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3990but that name is obsolete because some @command{make} programs have a rule
3991that creates @file{install} from it if there is no makefile.  Further, this
3992macro requires @command{install} to be able to install multiple files into a
3993target directory in a single invocation.
3994
3995Autoconf comes with a copy of @file{install-sh} that you can use.  If
3996you use @code{AC_PROG_INSTALL}, you must include either
3997@file{install-sh} or @file{install.sh} in your distribution; otherwise
3998@command{configure} produces an error message saying it can't find
3999them---even if the system you're on has a good @command{install} program.
4000This check is a safety measure to prevent you from accidentally leaving
4001that file out, which would prevent your package from installing on
4002systems that don't have a BSD-compatible @command{install} program.
4003
4004If you need to use your own installation program because it has features
4005not found in standard @command{install} programs, there is no reason to use
4006@code{AC_PROG_INSTALL}; just put the file name of your program into your
4007@file{Makefile.in} files.
4008
4009The result of the test can be overridden by setting the variable
4010@code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4011@end defmac
4012
4013@defmac AC_PROG_MKDIR_P
4014@acindex{PROG_MKDIR_P}
4015@ovindex MKDIR_P
4016@caindex path_mkdir
4017Set output variable @code{MKDIR_P} to a program that ensures that for
4018each argument, a directory named by this argument exists, creating it
4019and its parent directories if needed, and without race conditions when
4020two instances of the program attempt to make the same directory at
4021nearly the same time.
4022
4023This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4024falls back on invoking @command{install-sh} with the @option{-d} option,
4025so your package should
4026contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4027An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4028is vulnerable to race conditions, so if you want to support parallel
4029installs from
4030different packages into the same directory you need to make sure you
4031have an up-to-date @file{install-sh}.  In particular, be careful about
4032using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4033
4034This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4035in M4sh}), but it sets an output variable intended for use in other
4036files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4037@command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4038but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4039might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4040directory, and conversely a makefile should use @code{$(MKDIR_P) --
4041$(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4042Finally, @code{AS_MKDIR_P} does not check for race condition
4043vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4044
4045@samp{@@MKDIR_P@@} is special, as its value may vary for different
4046configuration files.
4047
4048The result of the test can be overridden by setting the variable
4049@code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4050@end defmac
4051
4052@anchor{AC_PROG_LEX}
4053@defmac AC_PROG_LEX
4054@acindex{PROG_LEX}
4055@ovindex LEX
4056@ovindex LEXLIB
4057@cvindex YYTEXT_POINTER
4058@ovindex LEX_OUTPUT_ROOT
4059@caindex prog_LEX
4060If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4061and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4062place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4063@option{-ll}, if found.  If neither variant is available, set @code{LEX}
4064to @samp{:}; for packages that ship the generated @file{file.yy.c}
4065alongside the source @file{file.l}, this default allows users without a
4066lexer generator to still build the package even if the timestamp for
4067@file{file.l} is inadvertently changed.
4068
4069Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4070of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4071the base of the file name that the lexer generates; usually
4072@file{lex.yy}, but sometimes something else.  These results vary
4073according to whether @code{lex} or @code{flex} is being used.
4074
4075You are encouraged to use Flex in your sources, since it is both more
4076pleasant to use than plain Lex and the C source it produces is portable.
4077In order to ensure portability, however, you must either provide a
4078function @code{yywrap} or, if you don't use it (e.g., your scanner has
4079no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4080statement in the scanner's source.  Once this done, the scanner is
4081portable (unless @emph{you} felt free to use nonportable constructs) and
4082does not depend on any library.  In this case, and in this case only, it
4083is suggested that you use this Autoconf snippet:
4084
4085@example
4086AC_PROG_LEX
4087if test "x$LEX" != xflex; then
4088  LEX="$SHELL $missing_dir/missing flex"
4089  AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4090  AC_SUBST([LEXLIB], [''])
4091fi
4092@end example
4093
4094The shell script @command{missing} can be found in the Automake
4095distribution.
4096
4097Remember that the user may have supplied an alternate location in
4098@env{LEX}, so if Flex is required, it is better to check that the user
4099provided something sufficient by parsing the output of @samp{$LEX
4100--version} than by simply relying on @code{test "x$LEX" = xflex}.
4101
4102To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4103(indirectly) this macro twice, which causes an annoying but benign
4104``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4105of Automake will fix this issue; meanwhile, just ignore this message.
4106
4107As part of running the test, this macro may delete any file in the
4108configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4109
4110The result of this test can be influenced by setting the variable
4111@code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4112@end defmac
4113
4114@anchor{AC_PROG_LN_S}
4115@defmac AC_PROG_LN_S
4116@acindex{PROG_LN_S}
4117@ovindex LN_S
4118If @samp{ln -s} works on the current file system (the operating system
4119and file system support symbolic links), set the output variable
4120@code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4121@code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4122
4123If you make a link in a directory other than the current directory, its
4124meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4125create links using @samp{$(LN_S)}, either find out which form is used
4126and adjust the arguments, or always invoke @code{ln} in the directory
4127where the link is to be created.
4128
4129In other words, it does not work to do:
4130@example
4131$(LN_S) foo /x/bar
4132@end example
4133
4134Instead, do:
4135
4136@example
4137(cd /x && $(LN_S) foo bar)
4138@end example
4139@end defmac
4140
4141@defmac AC_PROG_RANLIB
4142@acindex{PROG_RANLIB}
4143@ovindex RANLIB
4144@c @caindex prog_RANLIB
4145@c @caindex prog_ac_ct_RANLIB
4146Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4147is found, and otherwise to @samp{:} (do nothing).
4148@end defmac
4149
4150@defmac AC_PROG_SED
4151@acindex{PROG_SED}
4152@ovindex SED
4153@caindex path_SED
4154Set output variable @code{SED} to a Sed implementation that conforms to
4155Posix and does not have arbitrary length limits.  Report an error if no
4156acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4157information about portability problems with Sed.
4158
4159The result of this test can be overridden by setting the @code{SED} variable
4160and is cached in the @code{ac_cv_path_SED} variable.
4161@end defmac
4162
4163@defmac AC_PROG_YACC
4164@acindex{PROG_YACC}
4165@evindex YACC
4166@evindex YFLAGS
4167@ovindex YACC
4168@caindex prog_YACC
4169If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4170-o y.tab.c}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4171@samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4172The result of this test can be influenced by setting the variable
4173@code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4174@end defmac
4175
4176@node Generic Programs
4177@subsection Generic Program and File Checks
4178
4179These macros are used to find programs not covered by the ``particular''
4180test macros.  If you need to check the behavior of a program as well as
4181find out whether it is present, you have to write your own test for it
4182(@pxref{Writing Tests}).  By default, these macros use the environment
4183variable @env{PATH}.  If you need to check for a program that might not
4184be in the user's @env{PATH}, you can pass a modified path to use
4185instead, like this:
4186
4187@example
4188AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4189             [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4190[/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4191@end example
4192
4193You are strongly encouraged to declare the @var{variable} passed to
4194@code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4195@code{AC_ARG_VAR}, for more details.
4196
4197@anchor{AC_CHECK_PROG}
4198@defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4199  @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4200  @ovar{reject})
4201@acindex{CHECK_PROG}
4202@caindex prog_@var{variable}
4203Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4204it is found, set @var{variable} to @var{value-if-found}, otherwise to
4205@var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4206absolute file name) even if it is the first found in the search path; in
4207that case, set @var{variable} using the absolute file name of the
4208@var{prog-to-check-for} found that is not @var{reject}.  If
4209@var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4210@var{variable}.  The result of this test can be overridden by setting the
4211@var{variable} variable or the cache variable
4212@code{ac_cv_prog_@var{variable}}.
4213@end defmac
4214
4215@anchor{AC_CHECK_PROGS}
4216@defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4217  @ovar{value-if-not-found}, @dvar{path, $PATH})
4218@acindex{CHECK_PROGS}
4219@caindex prog_@var{variable}
4220Check for each program in the blank-separated list
4221@var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4222@var{variable} to the name of that program.  Otherwise, continue
4223checking the next program in the list.  If none of the programs in the
4224list are found, set @var{variable} to @var{value-if-not-found}; if
4225@var{value-if-not-found} is not specified, the value of @var{variable}
4226is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4227this test can be overridden by setting the @var{variable} variable or the
4228cache variable @code{ac_cv_prog_@var{variable}}.
4229@end defmac
4230
4231@defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4232  @ovar{value-if-not-found}, @dvar{path, $PATH})
4233@acindex{CHECK_TARGET_TOOL}
4234Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4235with a prefix of the target type as determined by
4236@code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4237If the tool cannot be found with a prefix, and if the build and target
4238types are equal, then it is also searched for without a prefix.
4239
4240As noted in @ref{Specifying Target Triplets}, the
4241target is rarely specified, because most of the time it is the same
4242as the host: it is the type of system for which any compiler tool in
4243the package produces code.  What this macro looks for is,
4244for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4245compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4246uses to produce objects, archives or executables}.
4247@end defmac
4248
4249@defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4250  @ovar{value-if-not-found}, @dvar{path, $PATH})
4251@acindex{CHECK_TOOL}
4252@c @caindex prog_@var{VARIABLE}
4253@c @caindex prog_ac_ct_@var{VARIABLE}
4254Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4255with a prefix of the host type as specified by @option{--host}, followed by a
4256dash.  For example, if the user runs
4257@samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4258@example
4259AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4260@end example
4261@noindent
4262sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4263@var{path}, or otherwise to @samp{ranlib} if that program exists in
4264@var{path}, or to @samp{:} if neither program exists.
4265
4266When cross-compiling, this macro will issue a warning if no program
4267prefixed with the host type could be found.
4268For more information, see @ref{Specifying Target Triplets}.
4269@end defmac
4270
4271@defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4272  @ovar{value-if-not-found}, @dvar{path, $PATH})
4273@acindex{CHECK_TARGET_TOOLS}
4274Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4275@var{progs-to-check-for} are checked with a prefix of the target type as
4276determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4277(@pxref{Canonicalizing}).  If none of the tools can be found with a
4278prefix, and if the build and target types are equal, then the first one
4279without a prefix is used.  If a tool is found, set @var{variable} to
4280the name of that program.  If none of the tools in the list are found,
4281set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4282is not specified, the value of @var{variable} is not changed.  Calls
4283@code{AC_SUBST} for @var{variable}.
4284@end defmac
4285
4286@defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4287  @ovar{value-if-not-found}, @dvar{path, $PATH})
4288@acindex{CHECK_TOOLS}
4289Like @code{AC_CHECK_TOOL}, each of the tools in the list
4290@var{progs-to-check-for} are checked with a prefix of the host type as
4291determined by @code{AC_CANONICAL_HOST}, followed by a dash
4292(@pxref{Canonicalizing}).  If none of the tools can be found with a
4293prefix, then the first one without a prefix is used.  If a tool is found,
4294set @var{variable} to the name of that program.  If none of the tools in
4295the list are found, set @var{variable} to @var{value-if-not-found}; if
4296@var{value-if-not-found} is not specified, the value of @var{variable}
4297is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4298
4299When cross-compiling, this macro will issue a warning if no program
4300prefixed with the host type could be found.
4301For more information, see @ref{Specifying Target Triplets}.
4302@end defmac
4303
4304@anchor{AC_PATH_PROG}
4305@defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4306  @ovar{value-if-not-found}, @dvar{path, $PATH})
4307@acindex{PATH_PROG}
4308@caindex path_@var{variable}
4309Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4310name of @var{prog-to-check-for} if found.  The result of this test
4311can be overridden by setting the @var{variable} variable.  A positive
4312result of this test is cached in the @code{ac_cv_path_@var{variable}}
4313variable.
4314@end defmac
4315
4316@anchor{AC_PATH_PROGS}
4317@defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4318  @ovar{value-if-not-found}, @dvar{path, $PATH})
4319@acindex{PATH_PROGS}
4320@caindex path_@var{variable}
4321Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4322are found, set @var{variable} to the absolute name of the program
4323found.  The result of this test can be overridden by setting the
4324@var{variable} variable.  A positive result of this test is cached in
4325the @code{ac_cv_path_@var{variable}} variable.
4326@end defmac
4327
4328@defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4329  @var{progs-to-check-for}, @var{feature-test}, @
4330  @ovar{action-if-not-found}, @dvar{path, $PATH})
4331@acindex{PATH_PROGS_FEATURE_CHECK}
4332@caindex path_@var{variable}
4333@vrindex ac_path_@var{variable}
4334@vrindex ac_path_@var{variable}_found
4335This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4336empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4337its value.  Otherwise, check for each program in the blank-separated
4338list @var{progs-to-check-for} existing in @var{path}.  For each program
4339found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4340set to the absolute name of the candidate program.  If no invocation of
4341@var{feature-test} sets the shell variable
4342@code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4343executed.  @var{feature-test} will be run even when
4344@code{ac_cv_path_@var{variable}} is set, to provide the ability to
4345choose a better candidate found later in @var{path}; to accept the
4346current setting and bypass all further checks, @var{feature-test} can
4347execute @code{ac_path_@var{variable}_found=:}.
4348
4349Note that this macro has some subtle differences from
4350@code{AC_CHECK_PROGS}.  It is designed to be run inside
4351@code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4352particular, @var{variable} is not set to the final value of
4353@code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4354run.  Also, on failure, any action can be performed, whereas
4355@code{AC_CHECK_PROGS} only performs
4356@code{@var{variable}=@var{value-if-not-found}}.
4357
4358Here is an example, similar to what Autoconf uses in its own configure
4359script.  It will search for an implementation of @command{m4} that
4360supports the @code{indir} builtin, even if it goes by the name
4361@command{gm4} or is not the first implementation on @env{PATH}.
4362
4363@example
4364AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4365  [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4366    [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4367      test "x$m4out" = x0 \
4368      && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4369    [AC_MSG_ERROR([could not find m4 that supports indir])])])
4370AC_SUBST([M4], [$ac_cv_path_M4])
4371@end example
4372@end defmac
4373
4374@defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4375  @ovar{value-if-not-found}, @dvar{path, $PATH})
4376@acindex{PATH_TARGET_TOOL}
4377Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4378name of the program if it is found.
4379@end defmac
4380
4381@defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4382  @ovar{value-if-not-found}, @dvar{path, $PATH})
4383@acindex{PATH_TOOL}
4384Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4385name of the program if it is found.
4386
4387When cross-compiling, this macro will issue a warning if no program
4388prefixed with the host type could be found.
4389For more information, see @ref{Specifying Target Triplets}.
4390@end defmac
4391
4392
4393@node Files
4394@section Files
4395@cindex File, checking
4396
4397You might also need to check for the existence of files.  Before using
4398these macros, ask yourself whether a runtime test might not be a better
4399solution.  Be aware that, like most Autoconf macros, they test a feature
4400of the host machine, and therefore, they die when cross-compiling.
4401
4402@defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4403  @ovar{action-if-not-found})
4404@acindex{CHECK_FILE}
4405@caindex file_@var{file}
4406Check whether file @var{file} exists on the native system.  If it is
4407found, execute @var{action-if-found}, otherwise do
4408@var{action-if-not-found}, if given.  The result of this test is cached
4409in the @code{ac_cv_file_@var{file}} variable, with characters not
4410suitable for a variable name mapped to underscores.
4411@end defmac
4412
4413@defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4414  @ovar{action-if-not-found})
4415@acindex{CHECK_FILES}
4416@caindex file_@var{file}
4417Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4418Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4419for each file found.  The results of each test are cached in the
4420@code{ac_cv_file_@var{file}} variable, with characters not suitable for
4421a variable name mapped to underscores.
4422@end defmac
4423
4424
4425@node Libraries
4426@section Library Files
4427@cindex Library, checking
4428
4429The following macros check for the presence of certain C, C++, Fortran,
4430or Go library archive files.
4431
4432@anchor{AC_CHECK_LIB}
4433@defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4434  @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4435@acindex{CHECK_LIB}
4436@caindex lib_@var{library}_@var{function}
4437Test whether the library @var{library} is available by trying to link
4438a test program that calls function @var{function} with the library.
4439@var{function} should be a function provided by the library.
4440Use the base
4441name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4442the @var{library} argument.
4443
4444@var{action-if-found} is a list of shell commands to run if the link
4445with the library succeeds; @var{action-if-not-found} is a list of shell
4446commands to run if the link fails.  If @var{action-if-found} is not
4447specified, the default action prepends @option{-l@var{library}} to
4448@code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4449capitals).  This macro is intended to support building @code{LIBS} in
4450a right-to-left (least-dependent to most-dependent) fashion such that
4451library dependencies are satisfied as a natural side effect of
4452consecutive tests.  Linkers are sensitive to library ordering
4453so the order in which @code{LIBS} is generated is important to reliable
4454detection of libraries.
4455
4456If linking with @var{library} results in unresolved symbols that would
4457be resolved by linking with additional libraries, give those libraries
4458as the @var{other-libraries} argument, separated by spaces:
4459e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4460that @var{library} is present, because linking the test program can
4461fail with unresolved symbols.  The @var{other-libraries} argument
4462should be limited to cases where it is desirable to test for one library
4463in the presence of another that is not already in @code{LIBS}.
4464
4465@code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4466in some common cases.  Many standard functions like @code{gethostbyname}
4467appear in the standard C library on some hosts, and in special libraries
4468like @code{nsl} on other hosts.  On some hosts the special libraries
4469contain variant implementations that you may not want to use.  These
4470days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4471[nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4472
4473The result of this test is cached in the
4474@code{ac_cv_lib_@var{library}_@var{function}} variable.
4475@end defmac
4476
4477@anchor{AC_SEARCH_LIBS}
4478@defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4479  @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4480@acindex{SEARCH_LIBS}
4481@caindex search_@var{function}
4482Search for a library defining @var{function} if it's not already
4483available.  This equates to calling
4484@samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4485no libraries, then for each library listed in @var{search-libs}.
4486
4487Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4488to contain @var{function}, and run @var{action-if-found}.  If the
4489function is not found, run @var{action-if-not-found}.
4490
4491If linking with @var{library} results in unresolved symbols that would
4492be resolved by linking with additional libraries, give those libraries
4493as the @var{other-libraries} argument, separated by spaces:
4494e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4495that @var{function} is present, because linking the test program
4496always fails with unresolved symbols.
4497
4498The result of this test is cached in the
4499@code{ac_cv_search_@var{function}} variable as @samp{none required} if
4500@var{function} is already available, as @samp{no} if no library
4501containing @var{function} was found, otherwise as the
4502@option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4503@end defmac
4504
4505
4506
4507@node Library Functions
4508@section Library Functions
4509
4510The following macros check for particular C library functions.
4511If there is no macro specifically defined to check for a function you need,
4512and you don't need to check for any special properties of
4513it, then you can use one of the general function-check macros.
4514
4515@menu
4516* Function Portability::        Pitfalls with usual functions
4517* Particular Functions::        Special handling to find certain functions
4518* Generic Functions::           How to find other functions
4519@end menu
4520
4521@node Function Portability
4522@subsection Portability of C Functions
4523@cindex Portability of C functions
4524@cindex C function portability
4525
4526Most usual functions can either be missing, or be buggy, or be limited
4527on some architectures.  This section tries to make an inventory of these
4528portability issues.  By definition, this list always requires
4529additions.  A much more complete list is maintained by the Gnulib
4530project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4531Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4532Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4533Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4534help us keep the gnulib list as complete as possible.
4535
4536@table @asis
4537@item @code{exit}
4538@c @fuindex exit
4539@prindex @code{exit}
4540On ancient hosts, @code{exit} returned @code{int}.
4541This is because @code{exit} predates @code{void}, and there was a long
4542tradition of it returning @code{int}.
4543
4544On current hosts, the problem more likely is that @code{exit} is not
4545declared, due to C++ problems of some sort or another.  For this reason
4546we suggest that test programs not invoke @code{exit}, but return from
4547@code{main} instead.
4548
4549@item @code{free}
4550@c @fuindex free
4551@prindex @code{free}
4552The C standard says a call @code{free (NULL)} does nothing, but
4553some old systems don't support this (e.g., NextStep).
4554
4555@item @code{isinf}
4556@itemx @code{isnan}
4557@c @fuindex isinf
4558@c @fuindex isnan
4559@prindex @code{isinf}
4560@prindex @code{isnan}
4561The C99 standard says that @code{isinf} and @code{isnan} are
4562macros.  On some systems just macros are available
4563(e.g., HP-UX and Solaris 10), on
4564some systems both macros and functions (e.g., glibc 2.3.2), and on some
4565systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4566these functions are declared in nonstandard headers like
4567@code{<sunmath.h>} and defined in non-default libraries like
4568@option{-lm} or @option{-lsunmath}.
4569
4570The C99 @code{isinf} and @code{isnan} macros work correctly with
4571@code{long double} arguments, but pre-C99 systems that use functions
4572typically assume @code{double} arguments.  On such a system,
4573@code{isinf} incorrectly returns true for a finite @code{long double}
4574argument that is outside the range of @code{double}.
4575
4576The best workaround for these issues is to use gnulib modules
4577@code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4578solution involves code like the following.
4579
4580@smallexample
4581#include <math.h>
4582
4583#ifndef isnan
4584# define isnan(x) \
4585    (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4586     : sizeof (x) == sizeof (double) ? isnan_d (x) \
4587     : isnan_f (x))
4588static inline int isnan_f  (float       x) @{ return x != x; @}
4589static inline int isnan_d  (double      x) @{ return x != x; @}
4590static inline int isnan_ld (long double x) @{ return x != x; @}
4591#endif
4592
4593#ifndef isinf
4594# define isinf(x) \
4595    (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4596     : sizeof (x) == sizeof (double) ? isinf_d (x) \
4597     : isinf_f (x))
4598static inline int isinf_f  (float       x)
4599@{ return !isnan (x) && isnan (x - x); @}
4600static inline int isinf_d  (double      x)
4601@{ return !isnan (x) && isnan (x - x); @}
4602static inline int isinf_ld (long double x)
4603@{ return !isnan (x) && isnan (x - x); @}
4604#endif
4605@end smallexample
4606
4607Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4608compilers that lack the @code{inline} keyword.  Some optimizing
4609compilers mishandle these definitions, but systems with that bug
4610typically have many other floating point corner-case compliance problems
4611anyway, so it's probably not worth worrying about.
4612
4613@item @code{malloc}
4614@c @fuindex malloc
4615@prindex @code{malloc}
4616The C standard says a call @code{malloc (0)} is implementation
4617dependent.  It can return either @code{NULL} or a new non-null pointer.
4618The latter is more common (e.g., the GNU C Library) but is by
4619no means universal.  @code{AC_FUNC_MALLOC}
4620can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4621
4622@item @code{putenv}
4623@c @fuindex putenv
4624@prindex @code{putenv}
4625Posix prefers @code{setenv} to @code{putenv}; among other things,
4626@code{putenv} is not required of all Posix implementations, but
4627@code{setenv} is.
4628
4629Posix specifies that @code{putenv} puts the given string directly in
4630@code{environ}, but some systems make a copy of it instead (e.g.,
4631glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4632not free it, causing a memory leak (e.g., FreeBSD 4).
4633
4634On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4635environment, but this is not standard usage and it dumps core
4636on some systems (e.g., AIX).
4637
4638On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4639environment, rather than inserting it with an empty value.
4640
4641@item @code{realloc}
4642@c @fuindex realloc
4643@prindex @code{realloc}
4644The C standard says a call @code{realloc (NULL, size)} is equivalent
4645to @code{malloc (size)}, but some old systems don't support this (e.g.,
4646NextStep).
4647
4648@item @code{signal} handler
4649@c @fuindex signal
4650@prindex @code{signal}
4651@prindex @code{sigaction}
4652Normally @code{signal} takes a handler function with a return type of
4653@code{void}, but some old systems required @code{int} instead.  Any
4654actual @code{int} value returned is not used; this is only a
4655difference in the function prototype demanded.
4656
4657All systems we know of in current use return @code{void}.  The
4658@code{int} was to support K&R C, where of course @code{void} is not
4659available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4660(@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4661all cases.
4662
4663In most cases, it is more robust to use @code{sigaction} when it is
4664available, rather than @code{signal}.
4665
4666@item @code{snprintf}
4667@c @fuindex snprintf
4668@prindex @code{snprintf}
4669@c @fuindex vsnprintf
4670@prindex @code{vsnprintf}
4671The C99 standard says that if the output array isn't big enough
4672and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4673truncate the output and return the number of bytes that ought to have
4674been produced.  Some older systems return the truncated length (e.g.,
4675GNU C Library 2.0.x or IRIX 6.5), some a negative value
4676(e.g., earlier GNU C Library versions), and some the buffer
4677length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4678older systems ignore the length and overrun the buffer (e.g., 64-bit
4679Solaris 7).
4680
4681@item @code{sprintf}
4682@c @fuindex sprintf
4683@prindex @code{sprintf}
4684@c @fuindex vsprintf
4685@prindex @code{vsprintf}
4686The C standard says @code{sprintf} and @code{vsprintf} return the
4687number of bytes written.  On some ancient systems (SunOS 4 for
4688instance) they return the buffer pointer instead, but these no
4689longer need to be worried about.
4690
4691@item @code{sscanf}
4692@c @fuindex sscanf
4693@prindex @code{sscanf}
4694On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4695that its
4696input string be writable (though it doesn't actually change it).  This
4697can be a problem when using @command{gcc} since it normally puts
4698constant strings in read-only memory (@pxref{Incompatibilities,
4699Incompatibilities of GCC, , gcc, Using and
4700Porting the GNU Compiler Collection}).  Apparently in some cases even
4701having format strings read-only can be a problem.
4702
4703@item @code{strerror_r}
4704@c @fuindex strerror_r
4705@prindex @code{strerror_r}
4706Posix specifies that @code{strerror_r} returns an @code{int}, but many
4707systems (e.g., GNU C Library version 2.2.4) provide a
4708different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4709can detect which is in use (@pxref{Particular Functions}).
4710
4711@item @code{strnlen}
4712@c @fuindex strnlen
4713@prindex @code{strnlen}
4714AIX 4.3 provides a broken version which produces the
4715following results:
4716
4717@example
4718strnlen ("foobar", 0) = 0
4719strnlen ("foobar", 1) = 3
4720strnlen ("foobar", 2) = 2
4721strnlen ("foobar", 3) = 1
4722strnlen ("foobar", 4) = 0
4723strnlen ("foobar", 5) = 6
4724strnlen ("foobar", 6) = 6
4725strnlen ("foobar", 7) = 6
4726strnlen ("foobar", 8) = 6
4727strnlen ("foobar", 9) = 6
4728@end example
4729
4730@item @code{sysconf}
4731@c @fuindex sysconf
4732@prindex @code{sysconf}
4733@code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
47349) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4735@code{#ifdef}.
4736
4737@item @code{unlink}
4738@c @fuindex unlink
4739@prindex @code{unlink}
4740The Posix spec says that @code{unlink} causes the given file to be
4741removed only after there are no more open file handles for it.  Some
4742non-Posix hosts have trouble with this requirement, though,
4743and some DOS variants even corrupt the file system.
4744
4745@item @code{unsetenv}
4746@c @fuindex unsetenv
4747@prindex @code{unsetenv}
4748On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4749can be removed with a call @code{putenv ("FOO=")}, as described under
4750@code{putenv} above.
4751
4752@item @code{va_copy}
4753@c @fuindex va_copy
4754@prindex @code{va_copy}
4755The C99 standard provides @code{va_copy} for copying
4756@code{va_list} variables.  It may be available in older environments
4757too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4758pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4759@code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4760portability.
4761
4762@item @code{va_list}
4763@c @fuindex va_list
4764@prindex @code{va_list}
4765@code{va_list} is not necessarily just a pointer.  It can be a
4766@code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4767not portable.  Or it can be an array (e.g., @command{gcc} in some
4768PowerPC configurations), which means as a function parameter it can be
4769effectively call-by-reference and library routines might modify the
4770value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
47712.1).
4772
4773@item Signed @code{>>}
4774Normally the C @code{>>} right shift of a signed type replicates the
4775high bit, giving a so-called ``arithmetic'' shift.  But care should be
4776taken since Standard C doesn't require that behavior.  On those
4777few processors without a native arithmetic shift (for instance Cray
4778vector systems) zero bits may be shifted in, the same as a shift of an
4779unsigned type.
4780
4781@item Integer @code{/}
4782C divides signed integers by truncating their quotient toward zero,
4783yielding the same result as Fortran.  However, before C99 the standard
4784allowed C implementations to take the floor or ceiling of the quotient
4785in some cases.  Hardly any implementations took advantage of this
4786freedom, though, and it's probably not worth worrying about this issue
4787nowadays.
4788@end table
4789
4790
4791@node Particular Functions
4792@subsection Particular Function Checks
4793@cindex Function, checking
4794
4795These macros check for particular C functions---whether they exist, and
4796in some cases how they respond when given certain arguments.
4797
4798@anchor{AC_FUNC_ALLOCA}
4799@defmac AC_FUNC_ALLOCA
4800@acindex{FUNC_ALLOCA}
4801@cvindex C_ALLOCA
4802@cvindex HAVE_ALLOCA_H
4803@ovindex ALLOCA
4804@c @fuindex alloca
4805@prindex @code{alloca}
4806@hdrindex{alloca.h}
4807@c @caindex working_alloca_h
4808Check how to get @code{alloca}.  Tries to get a builtin version by
4809checking for @file{alloca.h} or the predefined C preprocessor macros
4810@code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4811it defines @code{HAVE_ALLOCA_H}.
4812
4813If those attempts fail, it looks for the function in the standard C
4814library.  If any of those methods succeed, it defines
4815@code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4816@code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4817@code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4818garbage collect).  This variable is separate from @code{LIBOBJS} so
4819multiple programs can share the value of @code{ALLOCA} without needing
4820to create an actual library, in case only some of them use the code in
4821@code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4822purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4823
4824This macro does not try to get @code{alloca} from the System V R3
4825@file{libPW} or the System V R4 @file{libucb} because those libraries
4826contain some incompatible functions that cause trouble.  Some versions
4827do not even contain @code{alloca} or contain a buggy version.  If you
4828still want to use their @code{alloca}, use @code{ar} to extract
4829@file{alloca.o} from them instead of compiling @file{alloca.c}.
4830
4831Source files that use @code{alloca} should start with a piece of code
4832like the following, to declare it properly.
4833
4834@example
4835@group
4836#ifdef STDC_HEADERS
4837# include <stdlib.h>
4838# include <stddef.h>
4839#else
4840# ifdef HAVE_STDLIB_H
4841#  include <stdlib.h>
4842# endif
4843#endif
4844#ifdef HAVE_ALLOCA_H
4845# include <alloca.h>
4846#elif !defined alloca
4847# ifdef __GNUC__
4848#  define alloca __builtin_alloca
4849# elif defined _AIX
4850#  define alloca __alloca
4851# elif defined _MSC_VER
4852#  include <malloc.h>
4853#  define alloca _alloca
4854# elif !defined HAVE_ALLOCA
4855#  ifdef  __cplusplus
4856extern "C"
4857#  endif
4858void *alloca (size_t);
4859# endif
4860#endif
4861@end group
4862@end example
4863@end defmac
4864
4865@defmac AC_FUNC_CHOWN
4866@acindex{FUNC_CHOWN}
4867@cvindex HAVE_CHOWN
4868@c @fuindex chown
4869@prindex @code{chown}
4870@caindex func_chown_works
4871If the @code{chown} function is available and works (in particular, it
4872should accept @option{-1} for @code{uid} and @code{gid}), define
4873@code{HAVE_CHOWN}.  The result of this macro is cached in the
4874@code{ac_cv_func_chown_works} variable.
4875@end defmac
4876
4877@anchor{AC_FUNC_CLOSEDIR_VOID}
4878@defmac AC_FUNC_CLOSEDIR_VOID
4879@acindex{FUNC_CLOSEDIR_VOID}
4880@cvindex CLOSEDIR_VOID
4881@c @fuindex closedir
4882@prindex @code{closedir}
4883@caindex func_closedir_void
4884If the @code{closedir} function does not return a meaningful value,
4885define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4886return value for an error indicator.
4887
4888Currently this test is implemented by running a test program.  When
4889cross compiling the pessimistic assumption that @code{closedir} does not
4890return a meaningful value is made.
4891
4892The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4893variable.
4894
4895This macro is obsolescent, as @code{closedir} returns a meaningful value
4896on current systems.  New programs need not use this macro.
4897@end defmac
4898
4899@defmac AC_FUNC_ERROR_AT_LINE
4900@acindex{FUNC_ERROR_AT_LINE}
4901@c @fuindex error_at_line
4902@prindex @code{error_at_line}
4903@caindex lib_error_at_line
4904If the @code{error_at_line} function is not found, require an
4905@code{AC_LIBOBJ} replacement of @samp{error}.
4906
4907The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4908variable.
4909
4910The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4911should use Gnulib's @code{error} module.  @xref{Gnulib}.
4912@end defmac
4913
4914@defmac AC_FUNC_FNMATCH
4915@acindex{FUNC_FNMATCH}
4916@c @fuindex fnmatch
4917@prindex @code{fnmatch}
4918@caindex func_fnmatch_works
4919If the @code{fnmatch} function conforms to Posix, define
4920@code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4921the bugs in Solaris 2.4.
4922
4923Unlike the other specific
4924@code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4925broken/missing @code{fnmatch}.  This is for historical reasons.
4926See @code{AC_REPLACE_FNMATCH} below.
4927
4928The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4929variable.
4930
4931This macro is obsolescent.  New programs should use Gnulib's
4932@code{fnmatch-posix} module.  @xref{Gnulib}.
4933@end defmac
4934
4935@defmac AC_FUNC_FNMATCH_GNU
4936@acindex{FUNC_FNMATCH_GNU}
4937@c @fuindex fnmatch
4938@prindex @code{fnmatch}
4939@caindex func_fnmatch_gnu
4940Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4941whether @code{fnmatch} supports GNU extensions.  Detect common
4942implementation bugs, for example, the bugs in the GNU C
4943Library 2.1.
4944
4945The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4946variable.
4947
4948This macro is obsolescent.  New programs should use Gnulib's
4949@code{fnmatch-gnu} module.  @xref{Gnulib}.
4950@end defmac
4951
4952@anchor{AC_FUNC_FORK}
4953@defmac AC_FUNC_FORK
4954@acindex{FUNC_FORK}
4955@cvindex HAVE_VFORK_H
4956@cvindex HAVE_WORKING_FORK
4957@cvindex HAVE_WORKING_VFORK
4958@cvindex vfork
4959@c @fuindex fork
4960@prindex @code{fork}
4961@c @fuindex vfork
4962@prindex @code{vfork}
4963@hdrindex{vfork.h}
4964@c @caindex func_fork
4965@c @caindex func_fork_works
4966This macro checks for the @code{fork} and @code{vfork} functions.  If a
4967working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4968checks whether @code{fork} is just a stub by trying to run it.
4969
4970If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4971@code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4972define @code{vfork} to be @code{fork} for backward compatibility with
4973previous versions of @command{autoconf}.  This macro checks for several known
4974errors in implementations of @code{vfork} and considers the system to not
4975have a working @code{vfork} if it detects any of them.  It is not considered
4976to be an implementation error if a child's invocation of @code{signal}
4977modifies the parent's signal handler, since child processes rarely change
4978their signal handlers.
4979
4980Since this macro defines @code{vfork} only for backward compatibility with
4981previous versions of @command{autoconf} you're encouraged to define it
4982yourself in new code:
4983@example
4984@group
4985#ifndef HAVE_WORKING_VFORK
4986# define vfork fork
4987#endif
4988@end group
4989@end example
4990
4991The results of this macro are cached in the @code{ac_cv_func_fork_works}
4992and @code{ac_cv_func_vfork_works} variables.  In order to override the
4993test, you also need to set the @code{ac_cv_func_fork} and
4994@code{ac_cv_func_vfork} variables.
4995@end defmac
4996
4997@defmac AC_FUNC_FSEEKO
4998@acindex{FUNC_FSEEKO}
4999@cvindex _LARGEFILE_SOURCE
5000@cvindex HAVE_FSEEKO
5001@c @fuindex fseeko
5002@prindex @code{fseeko}
5003@c @fuindex ftello
5004@prindex @code{ftello}
5005@c @caindex sys_largefile_source
5006If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5007Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5008visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5009may occur when compiling with @code{AC_SYS_LARGEFILE} on
5010largefile-sensitive systems where @code{off_t} does not default to a
501164bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5012@end defmac
5013
5014@defmac AC_FUNC_GETGROUPS
5015@acindex{FUNC_GETGROUPS}
5016@cvindex HAVE_GETGROUPS
5017@ovindex GETGROUPS_LIBS
5018@c @fuindex getgroups
5019@prindex @code{getgroups}
5020@caindex func_getgroups_works
5021If the @code{getgroups} function is available and works (unlike on
5022Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5023@code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5024needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5025@end defmac
5026
5027@anchor{AC_FUNC_GETLOADAVG}
5028@defmac AC_FUNC_GETLOADAVG
5029@acindex{FUNC_GETLOADAVG}
5030@cvindex SVR4
5031@cvindex DGUX
5032@cvindex UMAX
5033@cvindex UMAX4_3
5034@cvindex HAVE_NLIST_H
5035@cvindex NLIST_NAME_UNION
5036@cvindex GETLOADAVG_PRIVILEGED
5037@cvindex NEED_SETGID
5038@cvindex C_GETLOADAVG
5039@ovindex LIBOBJS
5040@ovindex NEED_SETGID
5041@ovindex KMEM_GROUP
5042@ovindex GETLOADAVG_LIBS
5043@c @fuindex getloadavg
5044@prindex @code{getloadavg}
5045Check how to get the system load averages.  To perform its tests
5046properly, this macro needs the file @file{getloadavg.c}; therefore, be
5047sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5048@ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5049
5050If the system has the @code{getloadavg} function, define
5051@code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5052necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5053@code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5054@samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5055possibly define several other C preprocessor macros and output
5056variables:
5057
5058@enumerate
5059@item
5060Define @code{C_GETLOADAVG}.
5061
5062@item
5063Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5064those systems.
5065
5066@item
5067@hdrindex{nlist.h}
5068If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5069
5070@item
5071If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5072@code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5073@code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5074
5075@item
5076Programs may need to be installed set-group-ID (or set-user-ID) for
5077@code{getloadavg} to work.  In this case, define
5078@code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5079to @samp{true} (and otherwise to @samp{false}), and set
5080@code{KMEM_GROUP} to the name of the group that should own the installed
5081program.
5082@end enumerate
5083
5084The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5085use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5086@end defmac
5087
5088@anchor{AC_FUNC_GETMNTENT}
5089@defmac AC_FUNC_GETMNTENT
5090@acindex{FUNC_GETMNTENT}
5091@cvindex HAVE_GETMNTENT
5092@c @fuindex getmntent
5093@prindex @code{getmntent}
5094@caindex search_getmntent
5095Check for @code{getmntent} in the standard C library, and then in the
5096@file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5097IRIX 4, PTX, and UnixWare, respectively.  Then, if
5098@code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5099@code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5100@code{ac_cv_func_getmntent} to @code{no}.
5101
5102The result of this macro can be overridden by setting the cache variable
5103@code{ac_cv_search_getmntent}.
5104@end defmac
5105
5106@defmac AC_FUNC_GETPGRP
5107@acindex{FUNC_GETPGRP}
5108@cvindex GETPGRP_VOID
5109@c @fuindex getpgid
5110@c @fuindex getpgrp
5111@prindex @code{getpgid}
5112@prindex @code{getpgrp}
5113@caindex func_getpgrp_void
5114Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5115@code{getpgrp}; this is the Posix behavior.  On older BSD
5116systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5117behaves like Posix's @code{getpgid}.
5118
5119@example
5120#ifdef GETPGRP_VOID
5121  pid = getpgrp ();
5122#else
5123  pid = getpgrp (0);
5124#endif
5125@end example
5126
5127This macro does not check whether
5128@code{getpgrp} exists at all; if you need to work in that situation,
5129first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5130
5131The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5132variable.
5133
5134This macro is obsolescent, as current systems have a @code{getpgrp}
5135whose signature conforms to Posix.  New programs need not use this macro.
5136@end defmac
5137
5138@defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5139@acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5140@cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5141@c @fuindex lstat
5142@prindex @code{lstat}
5143@caindex func_lstat_dereferences_slashed_symlink
5144If @file{link} is a symbolic link, then @code{lstat} should treat
5145@file{link/} the same as @file{link/.}.  However, many older
5146@code{lstat} implementations incorrectly ignore trailing slashes.
5147
5148It is safe to assume that if @code{lstat} incorrectly ignores
5149trailing slashes, then other symbolic-link-aware functions like
5150@code{unlink} also incorrectly ignore trailing slashes.
5151
5152If @code{lstat} behaves properly, define
5153@code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5154@code{AC_LIBOBJ} replacement of @code{lstat}.
5155
5156The result of this macro is cached in the
5157@code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5158
5159The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5160New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5161@end defmac
5162
5163@defmac AC_FUNC_MALLOC
5164@acindex{FUNC_MALLOC}
5165@cvindex HAVE_MALLOC
5166@cvindex malloc
5167@c @fuindex malloc
5168@prindex @code{malloc}
5169@caindex func_malloc_0_nonnull
5170If the @code{malloc} function is compatible with the GNU C
5171library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5172pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5173@code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5174@samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5175native @code{malloc} is not used in the main project.
5176
5177Typically, the replacement file @file{malloc.c} should look like (note
5178the @samp{#undef malloc}):
5179
5180@verbatim
5181#include <config.h>
5182#undef malloc
5183
5184#include <sys/types.h>
5185
5186void *malloc ();
5187
5188/* Allocate an N-byte block of memory from the heap.
5189   If N is zero, allocate a 1-byte block.  */
5190
5191void *
5192rpl_malloc (size_t n)
5193{
5194  if (n == 0)
5195    n = 1;
5196  return malloc (n);
5197}
5198@end verbatim
5199
5200The result of this macro is cached in the
5201@code{ac_cv_func_malloc_0_nonnull} variable.
5202@end defmac
5203
5204@defmac AC_FUNC_MBRTOWC
5205@acindex{FUNC_MBRTOWC}
5206@cvindex HAVE_MBRTOWC
5207@c @fuindex mbrtowc
5208@prindex @code{mbrtowc}
5209@caindex func_mbrtowc
5210Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5211type @code{mbstate_t} are properly declared.
5212
5213The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5214variable.
5215@end defmac
5216
5217@defmac AC_FUNC_MEMCMP
5218@acindex{FUNC_MEMCMP}
5219@ovindex LIBOBJS
5220@c @fuindex memcmp
5221@prindex @code{memcmp}
5222@caindex func_memcmp_working
5223If the @code{memcmp} function is not available, or does not work on
52248-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5225bytes or more and with at least one buffer not starting on a 4-byte
5226boundary (such as the one on NeXT x86 OpenStep), require an
5227@code{AC_LIBOBJ} replacement for @samp{memcmp}.
5228
5229The result of this macro is cached in the
5230@code{ac_cv_func_memcmp_working} variable.
5231
5232This macro is obsolescent, as current systems have a working
5233@code{memcmp}.  New programs need not use this macro.
5234@end defmac
5235
5236@defmac AC_FUNC_MKTIME
5237@acindex{FUNC_MKTIME}
5238@ovindex LIBOBJS
5239@c @fuindex mktime
5240@prindex @code{mktime}
5241@caindex func_working_mktime
5242If the @code{mktime} function is not available, or does not work
5243correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5244For the purposes of this test, @code{mktime} should conform to the
5245Posix standard and should be the inverse of
5246@code{localtime}.
5247
5248The result of this macro is cached in the
5249@code{ac_cv_func_working_mktime} variable.
5250
5251The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5252use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5253@end defmac
5254
5255@anchor{AC_FUNC_MMAP}
5256@defmac AC_FUNC_MMAP
5257@acindex{FUNC_MMAP}
5258@cvindex HAVE_MMAP
5259@c @fuindex mmap
5260@prindex @code{mmap}
5261@caindex func_mmap_fixed_mapped
5262If the @code{mmap} function exists and works correctly, define
5263@code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5264memory.
5265
5266The result of this macro is cached in the
5267@code{ac_cv_func_mmap_fixed_mapped} variable.
5268@end defmac
5269
5270@defmac AC_FUNC_OBSTACK
5271@acindex{FUNC_OBSTACK}
5272@cvindex HAVE_OBSTACK
5273@cindex obstack
5274@caindex func_obstack
5275If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5276@code{AC_LIBOBJ} replacement for @samp{obstack}.
5277
5278The result of this macro is cached in the @code{ac_cv_func_obstack}
5279variable.
5280@end defmac
5281
5282@defmac AC_FUNC_REALLOC
5283@acindex{FUNC_REALLOC}
5284@cvindex HAVE_REALLOC
5285@cvindex realloc
5286@c @fuindex realloc
5287@prindex @code{realloc}
5288@caindex func_realloc_0_nonnull
5289If the @code{realloc} function is compatible with the GNU C
5290library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5291valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5292@code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5293@samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5294the native @code{realloc} is not used in the main project.  See
5295@code{AC_FUNC_MALLOC} for details.
5296
5297The result of this macro is cached in the
5298@code{ac_cv_func_realloc_0_nonnull} variable.
5299@end defmac
5300
5301@defmac AC_FUNC_SELECT_ARGTYPES
5302@acindex{FUNC_SELECT_ARGTYPES}
5303@cvindex SELECT_TYPE_ARG1
5304@cvindex SELECT_TYPE_ARG234
5305@cvindex SELECT_TYPE_ARG5
5306@c @fuindex select
5307@prindex @code{select}
5308@c @caindex func_select_args
5309Determines the correct type to be passed for each of the
5310@code{select} function's arguments, and defines those types
5311in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5312@code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5313to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5314and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5315
5316This macro is obsolescent, as current systems have a @code{select} whose
5317signature conforms to Posix.  New programs need not use this macro.
5318@end defmac
5319
5320@defmac AC_FUNC_SETPGRP
5321@acindex{FUNC_SETPGRP}
5322@cvindex SETPGRP_VOID
5323@c @fuindex setpgrp
5324@prindex @code{setpgrp}
5325@caindex func_setpgrp_void
5326If @code{setpgrp} takes no argument (the Posix version), define
5327@code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5328two process IDs as arguments.  This macro does not check whether
5329@code{setpgrp} exists at all; if you need to work in that situation,
5330first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5331
5332The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5333variable.
5334
5335This macro is obsolescent, as current systems have a @code{setpgrp}
5336whose signature conforms to Posix.  New programs need not use this macro.
5337@end defmac
5338
5339@defmac AC_FUNC_STAT
5340@defmacx AC_FUNC_LSTAT
5341@acindex{FUNC_STAT}
5342@acindex{FUNC_LSTAT}
5343@cvindex HAVE_STAT_EMPTY_STRING_BUG
5344@cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5345@c @fuindex stat
5346@prindex @code{stat}
5347@c @fuindex lstat
5348@prindex @code{lstat}
5349@caindex func_stat_empty_string_bug
5350@caindex func_lstat_empty_string_bug
5351Determine whether @code{stat} or @code{lstat} have the bug that it
5352succeeds when given the zero-length file name as argument.  The @code{stat}
5353and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5354this.
5355
5356If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5357@code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5358replacement of it.
5359
5360The results of these macros are cached in the
5361@code{ac_cv_func_stat_empty_string_bug} and the
5362@code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5363
5364These macros are obsolescent, as no current systems have the bug.
5365New programs need not use these macros.
5366@end defmac
5367
5368@anchor{AC_FUNC_STRCOLL}
5369@defmac AC_FUNC_STRCOLL
5370@acindex{FUNC_STRCOLL}
5371@cvindex HAVE_STRCOLL
5372@c @fuindex strcoll
5373@prindex @code{strcoll}
5374@caindex func_strcoll_works
5375If the @code{strcoll} function exists and works correctly, define
5376@code{HAVE_STRCOLL}.  This does a bit more than
5377@samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5378definitions of @code{strcoll} that should not be used.
5379
5380The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5381variable.
5382@end defmac
5383
5384@defmac AC_FUNC_STRERROR_R
5385@acindex{FUNC_STRERROR_R}
5386@cvindex HAVE_STRERROR_R
5387@cvindex HAVE_DECL_STRERROR_R
5388@cvindex STRERROR_R_CHAR_P
5389@c @fuindex strerror_r
5390@caindex func_strerror_r_char_p
5391@prindex @code{strerror_r}
5392If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5393it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5394@code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5395returns an @code{int} error number.  The Thread-Safe Functions option of
5396Posix requires @code{strerror_r} to return @code{int}, but
5397many systems (including, for example, version 2.2.4 of the GNU C
5398Library) return a @code{char *} value that is not necessarily equal to
5399the buffer argument.
5400
5401The result of this macro is cached in the
5402@code{ac_cv_func_strerror_r_char_p} variable.
5403@end defmac
5404
5405@anchor{AC_FUNC_STRFTIME}
5406@defmac AC_FUNC_STRFTIME
5407@acindex{FUNC_STRFTIME}
5408@cvindex HAVE_STRFTIME
5409@c @fuindex strftime
5410@prindex @code{strftime}
5411Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5412Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5413
5414This macro is obsolescent, as no current systems require the @file{intl}
5415library for @code{strftime}.  New programs need not use this macro.
5416@end defmac
5417
5418@defmac AC_FUNC_STRTOD
5419@acindex{FUNC_STRTOD}
5420@ovindex POW_LIB
5421@c @fuindex strtod
5422@prindex @code{strtod}
5423@caindex func_strtod
5424@caindex func_pow
5425If the @code{strtod} function does not exist or doesn't work correctly,
5426ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5427because @file{strtod.c} is likely to need @samp{pow}, set the output
5428variable @code{POW_LIB} to the extra library needed.
5429
5430This macro caches its result in the @code{ac_cv_func_strtod} variable
5431and depends upon the result in the @code{ac_cv_func_pow} variable.
5432
5433The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5434use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5435@end defmac
5436
5437@defmac AC_FUNC_STRTOLD
5438@acindex{FUNC_STRTOLD}
5439@cvindex HAVE_STRTOLD
5440@prindex @code{strtold}
5441@caindex func_strtold
5442If the @code{strtold} function exists and conforms to C99, define
5443@code{HAVE_STRTOLD}.
5444
5445This macro caches its result in the @code{ac_cv_func_strtold} variable.
5446@end defmac
5447
5448@defmac AC_FUNC_STRNLEN
5449@acindex{FUNC_STRNLEN}
5450@cvindex HAVE_STRNLEN
5451@c @fuindex strnlen
5452@prindex @code{strnlen}
5453@caindex func_strnlen_working
5454If the @code{strnlen} function is not available, or is buggy (like the one
5455from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5456
5457This macro caches its result in the @code{ac_cv_func_strnlen_working}
5458variable.
5459@end defmac
5460
5461@anchor{AC_FUNC_UTIME_NULL}
5462@defmac AC_FUNC_UTIME_NULL
5463@acindex{FUNC_UTIME_NULL}
5464@cvindex HAVE_UTIME_NULL
5465@c @fuindex utime
5466@prindex @code{utime}
5467@caindex func_utime_null
5468If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5469the present, define @code{HAVE_UTIME_NULL}.
5470
5471This macro caches its result in the @code{ac_cv_func_utime_null}
5472variable.
5473
5474This macro is obsolescent, as all current systems have a @code{utime}
5475that behaves this way.  New programs need not use this macro.
5476@end defmac
5477
5478@anchor{AC_FUNC_VPRINTF}
5479@defmac AC_FUNC_VPRINTF
5480@acindex{FUNC_VPRINTF}
5481@cvindex HAVE_VPRINTF
5482@cvindex HAVE_DOPRNT
5483@c @fuindex vprintf
5484@prindex @code{vprintf}
5485@c @fuindex vsprintf
5486@prindex @code{vsprintf}
5487If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5488@code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5489is available, you may assume that @code{vfprintf} and @code{vsprintf}
5490are also available.)
5491
5492This macro is obsolescent, as all current systems have @code{vprintf}.
5493New programs need not use this macro.
5494@end defmac
5495
5496@defmac AC_REPLACE_FNMATCH
5497@acindex{REPLACE_FNMATCH}
5498@c @fuindex fnmatch
5499@prindex @code{fnmatch}
5500@hdrindex{fnmatch.h}
5501@caindex func_fnmatch_works
5502If the @code{fnmatch} function does not conform to Posix (see
5503@code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5504
5505The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5506in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5507copy of the source code of GNU @code{fnmatch}.  If necessary,
5508this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5509@file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5510included in place of the system @code{<fnmatch.h>}.
5511
5512This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5513variable.
5514
5515This macro is obsolescent, as it assumes the use of particular source
5516files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5517which provides this macro along with the source files.  @xref{Gnulib}.
5518@end defmac
5519
5520
5521
5522@node Generic Functions
5523@subsection Generic Function Checks
5524
5525These macros are used to find functions not covered by the ``particular''
5526test macros.  If the functions might be in libraries other than the
5527default C library, first call @code{AC_CHECK_LIB} for those libraries.
5528If you need to check the behavior of a function as well as find out
5529whether it is present, you have to write your own test for
5530it (@pxref{Writing Tests}).
5531
5532@anchor{AC_CHECK_FUNC}
5533@defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5534  @ovar{action-if-not-found})
5535@acindex{CHECK_FUNC}
5536@caindex func_@var{function}
5537If C function @var{function} is available, run shell commands
5538@var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5539want to define a symbol if the function is available, consider using
5540@code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5541linkage even when @code{AC_LANG(C++)} has been called, since C is more
5542standardized than C++.  (@pxref{Language Choice}, for more information
5543about selecting the language for checks.)
5544
5545This macro caches its result in the @code{ac_cv_func_@var{function}}
5546variable.
5547@end defmac
5548
5549@anchor{AC_CHECK_FUNCS}
5550@defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5551  @ovar{action-if-not-found})
5552@acindex{CHECK_FUNCS}
5553@cvindex HAVE_@var{function}
5554For each @var{function} enumerated in the blank-or-newline-separated argument
5555list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5556If @var{action-if-found} is given, it is additional shell code to
5557execute when one of the functions is found.  You can give it a value of
5558@samp{break} to break out of the loop on the first match.  If
5559@var{action-if-not-found} is given, it is executed when one of the
5560functions is not found.
5561
5562Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5563@end defmac
5564
5565@defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5566@acindex{CHECK_FUNCS_ONCE}
5567@cvindex HAVE_@var{function}
5568For each @var{function} enumerated in the blank-or-newline-separated argument
5569list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5570This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5571checking code at most once, so that @command{configure} is smaller and
5572faster; but the checks cannot be conditionalized and are always done once,
5573early during the @command{configure} run.
5574@end defmac
5575
5576@sp 1
5577
5578Autoconf follows a philosophy that was formed over the years by those
5579who have struggled for portability: isolate the portability issues in
5580specific files, and then program as if you were in a Posix
5581environment.  Some functions may be missing or unfixable, and your
5582package must be ready to replace them.
5583
5584Suitable replacements for many such problem functions are available from
5585Gnulib (@pxref{Gnulib}).
5586
5587@defmac AC_LIBOBJ (@var{function})
5588@acindex{LIBOBJ}
5589@ovindex LIBOBJS
5590Specify that @samp{@var{function}.c} must be included in the executables
5591to replace a missing or broken implementation of @var{function}.
5592
5593@vrindex ac_objext
5594Technically, it adds @samp{@var{function}.$ac_objext} to the output
5595variable @code{LIBOBJS} if it is not already in, and calls
5596@code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5597directly change @code{LIBOBJS}, since this is not traceable.
5598@end defmac
5599
5600@defmac AC_LIBSOURCE (@var{file})
5601@acindex{LIBSOURCE}
5602Specify that @var{file} might be needed to compile the project.  If you
5603need to know what files might be needed by a @file{configure.ac}, you
5604should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5605
5606This macro is called automatically from @code{AC_LIBOBJ}, but you must
5607call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5608that case, since shell variables cannot be traced statically, you must
5609pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5610might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5611a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5612@code{"foo"} or @code{"bar"}, you should do:
5613
5614@example
5615AC_LIBSOURCE([foo.c])
5616AC_LIBSOURCE([bar.c])
5617AC_LIBOBJ([$foo_or_bar])
5618@end example
5619
5620@noindent
5621There is usually a way to avoid this, however, and you are encouraged to
5622simply call @code{AC_LIBOBJ} with literal arguments.
5623
5624Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5625slightly different semantics: the old macro took the function name,
5626e.g., @code{foo}, as its argument rather than the file name.
5627@end defmac
5628
5629@defmac AC_LIBSOURCES (@var{files})
5630@acindex{LIBSOURCES}
5631Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5632comma-separated M4 list.  Thus, the above example might be rewritten:
5633
5634@example
5635AC_LIBSOURCES([foo.c, bar.c])
5636AC_LIBOBJ([$foo_or_bar])
5637@end example
5638@end defmac
5639
5640@defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5641@acindex{CONFIG_LIBOBJ_DIR}
5642Specify that @code{AC_LIBOBJ} replacement files are to be found in
5643@var{directory}, a name relative to the top level of the
5644source tree.  The replacement directory defaults to @file{.}, the top
5645level directory, and the most typical value is @file{lib}, corresponding
5646to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5647
5648@command{configure} might need to know the replacement directory for the
5649following reasons: (i) some checks use the replacement files, (ii) some
5650macros bypass broken system headers by installing links to the
5651replacement headers (iii) when used in conjunction with Automake,
5652within each makefile, @var{directory} is used as a relative path
5653from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5654@code{LTLIBOBJS}, etc.
5655@end defmac
5656
5657@sp 1
5658
5659It is common to merely check for the existence of a function, and ask
5660for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5661a convenient shorthand.
5662
5663@defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5664@acindex{REPLACE_FUNCS}
5665@cvindex HAVE_@var{function}
5666@ovindex LIBOBJS
5667Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5668@var{action-if-not-found}.  You can declare your replacement function by
5669enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5670system has the function, it probably declares it in a header file you
5671should be including, so you shouldn't redeclare it lest your declaration
5672conflict.
5673@end defmac
5674
5675@node Header Files
5676@section Header Files
5677@cindex Header, checking
5678
5679The following macros check for the presence of certain C header files.
5680If there is no macro specifically defined to check for a header file you need,
5681and you don't need to check for any special properties of
5682it, then you can use one of the general header-file check macros.
5683
5684@menu
5685* Header Portability::          Collected knowledge on common headers
5686* Particular Headers::          Special handling to find certain headers
5687* Generic Headers::             How to find other headers
5688@end menu
5689
5690@node Header Portability
5691@subsection Portability of Headers
5692@cindex Portability of headers
5693@cindex Header portability
5694
5695This section documents some collected knowledge about common headers,
5696and the problems they cause.  By definition, this list always requires
5697additions.  A much more complete list is maintained by the Gnulib
5698project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5699Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5700Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5701the gnulib list as complete as possible.
5702
5703@table @asis
5704
5705@item @file{limits.h}
5706C99 says that @file{limits.h} defines @code{LLONG_MIN},
5707@code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5708environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5709define them.
5710
5711@item @file{inttypes.h} vs.@: @file{stdint.h}
5712@hdrindex{inttypes.h}
5713@hdrindex{stdint.h}
5714The C99 standard says that @file{inttypes.h} includes
5715@file{stdint.h}, so there's no need to include @file{stdint.h}
5716separately in a standard environment.  Some implementations have
5717@file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5718know of any implementation that has @file{stdint.h} but not
5719@file{inttypes.h}.
5720
5721@item @file{linux/irda.h}
5722@hdrindex{linux/irda.h}
5723It requires @file{linux/types.h} and @file{sys/socket.h}.
5724
5725@item @file{linux/random.h}
5726@hdrindex{linux/random.h}
5727It requires @file{linux/types.h}.
5728
5729@item @file{net/if.h}
5730@hdrindex{net/if.h}
5731On Darwin, this file requires that @file{sys/socket.h} be included
5732beforehand.  One should run:
5733
5734@example
5735AC_CHECK_HEADERS([sys/socket.h])
5736AC_CHECK_HEADERS([net/if.h], [], [],
5737[#include <stdio.h>
5738#ifdef STDC_HEADERS
5739# include <stdlib.h>
5740# include <stddef.h>
5741#else
5742# ifdef HAVE_STDLIB_H
5743#  include <stdlib.h>
5744# endif
5745#endif
5746#ifdef HAVE_SYS_SOCKET_H
5747# include <sys/socket.h>
5748#endif
5749])
5750@end example
5751
5752@item @file{netinet/if_ether.h}
5753@hdrindex{netinet/if_ether.h}
5754On Darwin, this file requires that @file{stdio.h} and
5755@file{sys/socket.h} be included beforehand.  One should run:
5756
5757@example
5758AC_CHECK_HEADERS([sys/socket.h])
5759AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5760[#include <stdio.h>
5761#ifdef STDC_HEADERS
5762# include <stdlib.h>
5763# include <stddef.h>
5764#else
5765# ifdef HAVE_STDLIB_H
5766#  include <stdlib.h>
5767# endif
5768#endif
5769#ifdef HAVE_SYS_SOCKET_H
5770# include <sys/socket.h>
5771#endif
5772])
5773@end example
5774
5775@item @file{stdint.h}
5776See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5777
5778@item @file{stdlib.h}
5779@hdrindex{stdlib.h}
5780On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5781
5782@item @file{sys/mount.h}
5783@hdrindex{sys/mount.h}
5784On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5785@file{sys/params.h} is a prerequisite.
5786
5787@item @file{sys/ptem.h}
5788@hdrindex{sys/ptem.h}
5789On Solaris 8, @file{sys/stream.h} is a prerequisite.
5790
5791@item @file{sys/socket.h}
5792@hdrindex{sys/socket.h}
5793On Darwin, @file{stdlib.h} is a prerequisite.
5794
5795@item @file{sys/ucred.h}
5796@hdrindex{sys/ucred.h}
5797On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5798
5799@item @file{X11/extensions/scrnsaver.h}
5800@hdrindex{X11/extensions/scrnsaver.h}
5801Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5802so required that you might not even consider looking for it.
5803
5804@example
5805AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5806[[#include <X11/Xlib.h>
5807]])
5808@end example
5809@end table
5810
5811
5812@node Particular Headers
5813@subsection Particular Header Checks
5814
5815These macros check for particular system header files---whether they
5816exist, and in some cases whether they declare certain symbols.
5817
5818@defmac AC_CHECK_HEADER_STDBOOL
5819@acindex{CHECK_HEADER_STDBOOL}
5820@cvindex HAVE__BOOL
5821@hdrindex{stdbool.h}
5822@caindex header_stdbool_h
5823Check whether @file{stdbool.h} exists and conforms to C99, and cache the
5824result in the @code{ac_cv_header_stdbool_h} variable.  If the type
5825@code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5826
5827This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5828packages that supply a substitute @file{stdbool.h} on platforms lacking
5829a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5830that explicitly checks for @file{stdbool.h}.
5831@end defmac
5832
5833@defmac AC_HEADER_ASSERT
5834@acindex{HEADER_ASSERT}
5835@cvindex NDEBUG
5836@hdrindex{assert.h}
5837Check whether to enable assertions in the style of @file{assert.h}.
5838Assertions are enabled by default, but the user can override this by
5839invoking @command{configure} with the @option{--disable-assert} option.
5840@end defmac
5841
5842@anchor{AC_HEADER_DIRENT}
5843@defmac AC_HEADER_DIRENT
5844@acindex{HEADER_DIRENT}
5845@cvindex HAVE_DIRENT_H
5846@cvindex HAVE_NDIR_H
5847@cvindex HAVE_SYS_DIR_H
5848@cvindex HAVE_SYS_NDIR_H
5849@hdrindex{dirent.h}
5850@hdrindex{sys/ndir.h}
5851@hdrindex{sys/dir.h}
5852@hdrindex{ndir.h}
5853Check for the following header files.  For the first one that is
5854found and defines @samp{DIR}, define the listed C preprocessor macro:
5855
5856@multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5857@item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5858@item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5859@item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5860@item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5861@end multitable
5862
5863The directory-library declarations in your source code should look
5864something like the following:
5865
5866@example
5867@group
5868#include <sys/types.h>
5869#ifdef HAVE_DIRENT_H
5870# include <dirent.h>
5871# define NAMLEN(dirent) strlen ((dirent)->d_name)
5872#else
5873# define dirent direct
5874# define NAMLEN(dirent) ((dirent)->d_namlen)
5875# ifdef HAVE_SYS_NDIR_H
5876#  include <sys/ndir.h>
5877# endif
5878# ifdef HAVE_SYS_DIR_H
5879#  include <sys/dir.h>
5880# endif
5881# ifdef HAVE_NDIR_H
5882#  include <ndir.h>
5883# endif
5884#endif
5885@end group
5886@end example
5887
5888Using the above declarations, the program would declare variables to be
5889of type @code{struct dirent}, not @code{struct direct}, and would access
5890the length of a directory entry name by passing a pointer to a
5891@code{struct dirent} to the @code{NAMLEN} macro.
5892
5893This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5894
5895This macro is obsolescent, as all current systems with directory
5896libraries have @code{<dirent.h>}.  New programs need not use this macro.
5897
5898Also see @code{AC_STRUCT_DIRENT_D_INO} and
5899@code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5900@end defmac
5901
5902@anchor{AC_HEADER_MAJOR}
5903@defmac AC_HEADER_MAJOR
5904@acindex{HEADER_MAJOR}
5905@cvindex MAJOR_IN_MKDEV
5906@cvindex MAJOR_IN_SYSMACROS
5907@hdrindex{sys/mkdev.h}
5908@hdrindex{sys/sysmacros.h}
5909If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5910@code{makedev}, but @file{sys/mkdev.h} does, define
5911@code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5912@code{MAJOR_IN_SYSMACROS}.
5913@end defmac
5914
5915@defmac AC_HEADER_RESOLV
5916@acindex{HEADER_RESOLV}
5917@cvindex HAVE_RESOLV_H
5918@hdrindex{resolv.h}
5919Checks for header @file{resolv.h}, checking for prerequisites first.
5920To properly use @file{resolv.h}, your code should contain something like
5921the following:
5922
5923@verbatim
5924#ifdef HAVE_SYS_TYPES_H
5925#  include <sys/types.h>
5926#endif
5927#ifdef HAVE_NETINET_IN_H
5928#  include <netinet/in.h>   /* inet_ functions / structs */
5929#endif
5930#ifdef HAVE_ARPA_NAMESER_H
5931#  include <arpa/nameser.h> /* DNS HEADER struct */
5932#endif
5933#ifdef HAVE_NETDB_H
5934#  include <netdb.h>
5935#endif
5936#include <resolv.h>
5937@end verbatim
5938@end defmac
5939
5940@anchor{AC_HEADER_STAT}
5941@defmac AC_HEADER_STAT
5942@acindex{HEADER_STAT}
5943@cvindex STAT_MACROS_BROKEN
5944@hdrindex{sys/stat.h}
5945If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5946@file{sys/stat.h} do not work properly (returning false positives),
5947define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5948Amdahl UTS and Motorola System V/88.
5949
5950This macro is obsolescent, as no current systems have the bug.
5951New programs need not use this macro.
5952@end defmac
5953
5954@defmac AC_HEADER_STDBOOL
5955@acindex{HEADER_STDBOOL}
5956@cvindex HAVE_STDBOOL_H
5957@cvindex HAVE__BOOL
5958@hdrindex{stdbool.h}
5959@caindex header_stdbool_h
5960If @file{stdbool.h} exists and conforms to C99, define
5961@code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5962@code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5963program could contain the following code:
5964
5965@example
5966@group
5967#ifdef HAVE_STDBOOL_H
5968# include <stdbool.h>
5969#else
5970# ifndef HAVE__BOOL
5971#  ifdef __cplusplus
5972typedef bool _Bool;
5973#  else
5974#   define _Bool signed char
5975#  endif
5976# endif
5977# define bool _Bool
5978# define false 0
5979# define true 1
5980# define __bool_true_false_are_defined 1
5981#endif
5982@end group
5983@end example
5984
5985Alternatively you can use the @samp{stdbool} package of Gnulib
5986(@pxref{Gnulib}).  It simplifies your code so that it can say just
5987@code{#include <stdbool.h>}, and it adds support for less-common
5988platforms.
5989
5990This macro caches its result in the @code{ac_cv_header_stdbool_h}
5991variable.
5992
5993This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
5994defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
5995does not.
5996@end defmac
5997
5998@anchor{AC_HEADER_STDC}
5999@defmac AC_HEADER_STDC
6000@acindex{HEADER_STDC}
6001@cvindex STDC_HEADERS
6002@hdrindex{stdlib.h}
6003@hdrindex{stdarg.h}
6004@hdrindex{string.h}
6005@hdrindex{float.h}
6006@hdrindex{ctype.h}
6007@caindex header_stdc
6008Define @code{STDC_HEADERS} if the system has C header files
6009conforming to ANSI C89 (ISO C90).
6010Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
6011@file{string.h}, and @file{float.h}; if the system has those, it
6012probably has the rest of the C89 header files.  This macro also
6013checks whether @file{string.h} declares @code{memchr} (and thus
6014presumably the other @code{mem} functions), whether @file{stdlib.h}
6015declare @code{free} (and thus presumably @code{malloc} and other related
6016functions), and whether the @file{ctype.h} macros work on characters
6017with the high bit set, as the C standard requires.
6018
6019If you use this macro, your code can refer to @code{STDC_HEADERS} to
6020determine whether the system has conforming header files (and probably C
6021library functions).
6022
6023This macro caches its result in the @code{ac_cv_header_stdc} variable.
6024
6025This macro is obsolescent, as current systems have conforming header
6026files.  New programs need not use this macro.
6027
6028@hdrindex{string.h}
6029@hdrindex{strings.h}
6030Nowadays @file{string.h} is part of the C standard and declares functions like
6031@code{strcpy}, and @file{strings.h} is standardized by Posix and declares
6032BSD functions like @code{bcopy}; but
6033historically, string functions were a major sticking point in this area.
6034If you still want to worry about portability to ancient systems without
6035standard headers, there is so much variation
6036that it is probably easier to declare the functions you use than to
6037figure out exactly what the system header files declare.  Some ancient systems
6038contained a mix of functions from the C standard and from BSD;
6039some were mostly standard but lacked @samp{memmove}; some defined the
6040BSD functions as macros in @file{string.h} or
6041@file{strings.h}; some had only the BSD functions but
6042@file{string.h}; some declared the memory functions in @file{memory.h},
6043some in @file{string.h}; etc.  It is probably sufficient to check for
6044one string function and one memory function; if the library had the
6045standard versions of those then it probably had most of the others.
6046If you put the following in @file{configure.ac}:
6047
6048@example
6049# This example is obsolescent.
6050# Nowadays you can omit these macro calls.
6051AC_HEADER_STDC
6052AC_CHECK_FUNCS([strchr memcpy])
6053@end example
6054
6055@noindent
6056then, in your code, you can use declarations like this:
6057
6058@example
6059@group
6060/* This example is obsolescent.
6061   Nowadays you can just #include <string.h>.  */
6062#ifdef STDC_HEADERS
6063# include <string.h>
6064#else
6065# ifndef HAVE_STRCHR
6066#  define strchr index
6067#  define strrchr rindex
6068# endif
6069char *strchr (), *strrchr ();
6070# ifndef HAVE_MEMCPY
6071#  define memcpy(d, s, n) bcopy ((s), (d), (n))
6072#  define memmove(d, s, n) bcopy ((s), (d), (n))
6073# endif
6074#endif
6075@end group
6076@end example
6077
6078@noindent
6079If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6080or @code{strspn}, which have no BSD equivalent, then macros don't
6081suffice to port to ancient hosts; you must provide an implementation of
6082each function.  An easy
6083way to incorporate your implementations only when needed (since the ones
6084in system C libraries may be hand optimized) is to, taking @code{memchr}
6085for example, put it in @file{memchr.c} and use
6086@samp{AC_REPLACE_FUNCS([memchr])}.
6087@end defmac
6088
6089@defmac AC_HEADER_SYS_WAIT
6090@acindex{HEADER_SYS_WAIT}
6091@cvindex HAVE_SYS_WAIT_H
6092@hdrindex{sys/wait.h}
6093@caindex header_sys_wait_h
6094If @file{sys/wait.h} exists and is compatible with Posix, define
6095@code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6096does not exist, or if it uses the old BSD @code{union wait} instead
6097of @code{int} to store a status value.  If @file{sys/wait.h} is not
6098Posix compatible, then instead of including it, define the
6099Posix macros with their usual interpretations.  Here is an
6100example:
6101
6102@example
6103@group
6104#include <sys/types.h>
6105#ifdef HAVE_SYS_WAIT_H
6106# include <sys/wait.h>
6107#endif
6108#ifndef WEXITSTATUS
6109# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6110#endif
6111#ifndef WIFEXITED
6112# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6113#endif
6114@end group
6115@end example
6116
6117@noindent
6118This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6119variable.
6120
6121This macro is obsolescent, as current systems are compatible with Posix.
6122New programs need not use this macro.
6123@end defmac
6124
6125@cvindex _POSIX_VERSION
6126@hdrindex{unistd.h}
6127@code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6128Posix systems.  If there is no @file{unistd.h}, it is definitely
6129not a Posix system.  However, some non-Posix systems do
6130have @file{unistd.h}.
6131
6132The way to check whether the system supports Posix is:
6133
6134@example
6135@group
6136#ifdef HAVE_UNISTD_H
6137# include <sys/types.h>
6138# include <unistd.h>
6139#endif
6140
6141#ifdef _POSIX_VERSION
6142/* Code for Posix systems.  */
6143#endif
6144@end group
6145@end example
6146
6147@anchor{AC_HEADER_TIME}
6148@defmac AC_HEADER_TIME
6149@acindex{HEADER_TIME}
6150@cvindex TIME_WITH_SYS_TIME
6151@hdrindex{time.h}
6152@hdrindex{sys/time.h}
6153@caindex header_time
6154If a program may include both @file{time.h} and @file{sys/time.h},
6155define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6156@file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6157protected against multiple inclusion, so programs could not explicitly
6158include both files.  This macro is useful in programs that use, for
6159example, @code{struct timeval} as well as
6160@code{struct tm}.  It is best used in conjunction with
6161@code{HAVE_SYS_TIME_H}, which can be checked for using
6162@code{AC_CHECK_HEADERS([sys/time.h])}.
6163
6164@example
6165@group
6166#ifdef TIME_WITH_SYS_TIME
6167# include <sys/time.h>
6168# include <time.h>
6169#else
6170# ifdef HAVE_SYS_TIME_H
6171#  include <sys/time.h>
6172# else
6173#  include <time.h>
6174# endif
6175#endif
6176@end group
6177@end example
6178
6179@noindent
6180This macro caches its result in the @code{ac_cv_header_time} variable.
6181
6182This macro is obsolescent, as current systems can include both files
6183when they exist.  New programs need not use this macro.
6184@end defmac
6185
6186
6187@defmac AC_HEADER_TIOCGWINSZ
6188@acindex{HEADER_TIOCGWINSZ}
6189@cvindex GWINSZ_IN_SYS_IOCTL
6190@hdrindex{sys/ioctl.h}
6191@hdrindex{termios.h}
6192@c FIXME: I need clarifications from Jim.
6193If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6194define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6195found in @file{<termios.h>}.
6196
6197Use:
6198
6199@example
6200@group
6201#ifdef HAVE_TERMIOS_H
6202# include <termios.h>
6203#endif
6204
6205#ifdef GWINSZ_IN_SYS_IOCTL
6206# include <sys/ioctl.h>
6207#endif
6208@end group
6209@end example
6210@end defmac
6211
6212@node Generic Headers
6213@subsection Generic Header Checks
6214
6215These macros are used to find system header files not covered by the
6216``particular'' test macros.  If you need to check the contents of a header
6217as well as find out whether it is present, you have to write your own
6218test for it (@pxref{Writing Tests}).
6219
6220@anchor{AC_CHECK_HEADER}
6221@defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6222  @ovar{action-if-not-found}, @ovar{includes})
6223@acindex{CHECK_HEADER}
6224@caindex header_@var{header-file}
6225If the system header file @var{header-file} is compilable, execute shell
6226commands @var{action-if-found}, otherwise execute
6227@var{action-if-not-found}.  If you just want to define a symbol if the
6228header file is available, consider using @code{AC_CHECK_HEADERS}
6229instead.
6230
6231@var{includes} is decoded to determine the appropriate include
6232directives.  If omitted or empty, @file{configure} will check for both header
6233existence (with the preprocessor) and usability (with the compiler),
6234using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6235there is a discrepancy between the results, a warning is issued to the
6236user, and the compiler results are favored (@pxref{Present But
6237Cannot Be Compiled}).  In general, favoring the compiler results means
6238that a header will be treated as not found even though the file exists,
6239because you did not provide enough prerequisites.
6240
6241Providing a non-empty @var{includes} argument allows the code to provide
6242any prerequisites prior to including the header under test; it is common
6243to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6244Includes}).  With an explicit fourth argument, no preprocessor test is
6245needed.  As a special case, an @var{includes} of exactly @samp{-}
6246triggers the older preprocessor check, which merely determines existence
6247of the file in the preprocessor search path; this should only be used as
6248a last resort (it is safer to determine the actual prerequisites and
6249perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6250it obvious that only a preprocessor check is desired).
6251
6252This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6253variable, with characters not suitable for a variable name mapped to
6254underscores.
6255@end defmac
6256
6257@anchor{AC_CHECK_HEADERS}
6258@defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6259  @ovar{action-if-found}, @ovar{action-if-not-found}, @
6260  @ovar{includes})
6261@acindex{CHECK_HEADERS}
6262@cvindex HAVE_@var{header}
6263@caindex header_@var{header-file}
6264For each given system header file @var{header-file} in the
6265blank-separated argument list that exists, define
6266@code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6267is given, it is additional shell code to execute when one of the header
6268files is found.  You can give it a value of @samp{break} to break out of
6269the loop on the first match.  If @var{action-if-not-found} is given, it
6270is executed when one of the header files is not found.
6271
6272@var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6273choose the set of preprocessor directives supplied before the header
6274under test.
6275
6276This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6277variable, with characters not suitable for a variable name mapped to
6278underscores.
6279@end defmac
6280
6281Previous versions of Autoconf merely checked whether the header was
6282accepted by the preprocessor.  This was changed because the old test was
6283inappropriate for typical uses.  Headers are typically used to compile,
6284not merely to preprocess, and the old behavior sometimes accepted
6285headers that clashed at compile-time (@pxref{Present But Cannot Be
6286Compiled}).  If you need to check whether a header is preprocessable,
6287you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6288
6289Actually requiring a header to compile improves the robustness of the
6290test, but it also requires
6291that you make sure that headers that must be included before the
6292@var{header-file} be part of the @var{includes}, (@pxref{Default
6293Includes}).  If looking for @file{bar.h}, which requires that
6294@file{foo.h} be included before if it exists, we suggest the following
6295scheme:
6296
6297@verbatim
6298AC_CHECK_HEADERS([foo.h])
6299AC_CHECK_HEADERS([bar.h], [], [],
6300[#ifdef HAVE_FOO_H
6301# include <foo.h>
6302#endif
6303])
6304@end verbatim
6305
6306The following variant generates smaller, faster @command{configure}
6307files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6308
6309@defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6310@acindex{CHECK_HEADERS_ONCE}
6311@cvindex HAVE_@var{header}
6312For each given system header file @var{header-file} in the
6313blank-separated argument list that exists, define
6314@code{HAVE_@var{header-file}} (in all capitals).
6315This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6316checking code at most once, so that @command{configure} is smaller and
6317faster; but the checks cannot be conditionalized and are always done once,
6318early during the @command{configure} run.  Thus, this macro is only safe
6319for checking headers that do not have prerequisites beyond what
6320@code{AC_INCLUDES_DEFAULT} provides.
6321@end defmac
6322
6323@node Declarations
6324@section Declarations
6325@cindex Declaration, checking
6326
6327The following macros check for the declaration of variables and
6328functions.  If there is no macro specifically defined to check for a
6329symbol you need, then you can use the general macros (@pxref{Generic
6330Declarations}) or, for more complex tests, you may use
6331@code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6332
6333@menu
6334* Particular Declarations::     Macros to check for certain declarations
6335* Generic Declarations::        How to find other declarations
6336@end menu
6337
6338@node Particular Declarations
6339@subsection Particular Declaration Checks
6340
6341There are no specific macros for declarations.
6342
6343@node Generic Declarations
6344@subsection Generic Declaration Checks
6345
6346These macros are used to find declarations not covered by the ``particular''
6347test macros.
6348
6349@defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6350  @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6351@acindex{CHECK_DECL}
6352@caindex have_decl_@var{symbol}
6353If @var{symbol} (a function, variable, or constant) is not declared in
6354@var{includes} and a declaration is needed, run the shell commands
6355@var{action-if-not-found}, otherwise @var{action-if-found}.
6356@var{includes} is a series of include directives, defaulting to
6357@code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6358prior to the declaration under test.
6359
6360This macro actually tests whether @var{symbol} is defined as a macro or
6361can be used as an r-value, not whether it is really declared, because it
6362is much safer to avoid introducing extra declarations when they are not
6363needed.  In order to facilitate use of C++ and overloaded function
6364declarations, it is possible to specify function argument types in
6365parentheses for types which can be zero-initialized:
6366
6367@example
6368AC_CHECK_DECL([basename(char *)])
6369@end example
6370
6371This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6372variable, with characters not suitable for a variable name mapped to
6373underscores.
6374@end defmac
6375
6376@anchor{AC_CHECK_DECLS}
6377@defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6378  @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6379@acindex{CHECK_DECLS}
6380@cvindex HAVE_DECL_@var{symbol}
6381@caindex have_decl_@var{symbol}
6382For each of the @var{symbols} (@emph{comma}-separated list with optional
6383function argument types for C++ overloads), define
6384@code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6385@var{symbol} is declared, otherwise to @samp{0}.  If
6386@var{action-if-not-found} is given, it is additional shell code to
6387execute when one of the function declarations is needed, otherwise
6388@var{action-if-found} is executed.
6389
6390@var{includes} is a series of include directives, defaulting to
6391@code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6392prior to the declarations under test.
6393
6394This macro uses an M4 list as first argument:
6395@example
6396AC_CHECK_DECLS([strdup])
6397AC_CHECK_DECLS([strlen])
6398AC_CHECK_DECLS([malloc, realloc, calloc, free])
6399AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6400AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6401@end example
6402
6403Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6404declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6405of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6406@emph{sure} that the check was performed, use
6407@code{HAVE_DECL_@var{symbol}} in @code{#if}:
6408
6409@example
6410#if !HAVE_DECL_SYMBOL
6411extern char *symbol;
6412#endif
6413@end example
6414
6415@noindent
6416If the test may have not been performed, however, because it is safer
6417@emph{not} to declare a symbol than to use a declaration that conflicts
6418with the system's one, you should use:
6419
6420@example
6421#if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6422void *malloc (size_t *s);
6423#endif
6424@end example
6425
6426@noindent
6427You fall into the second category only in extreme situations: either
6428your files may be used without being configured, or they are used during
6429the configuration.  In most cases the traditional approach is enough.
6430
6431This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6432variables, with characters not suitable for a variable name mapped to
6433underscores.
6434@end defmac
6435
6436@defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6437@acindex{CHECK_DECLS_ONCE}
6438@cvindex HAVE_DECL_@var{symbol}
6439For each of the @var{symbols} (@emph{comma}-separated list), define
6440@code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6441@var{symbol} is declared in the default include files, otherwise to
6442@samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6443generates the checking code at most once, so that @command{configure} is
6444smaller and faster; but the checks cannot be conditionalized and are
6445always done once, early during the @command{configure} run.
6446@end defmac
6447
6448
6449@node Structures
6450@section Structures
6451@cindex Structure, checking
6452
6453The following macros check for the presence of certain members in C
6454structures.  If there is no macro specifically defined to check for a
6455member you need, then you can use the general structure-member macros
6456(@pxref{Generic Structures}) or, for more complex tests, you may use
6457@code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6458
6459@menu
6460* Particular Structures::       Macros to check for certain structure members
6461* Generic Structures::          How to find other structure members
6462@end menu
6463
6464@node Particular Structures
6465@subsection Particular Structure Checks
6466
6467The following macros check for certain structures or structure members.
6468
6469@defmac AC_STRUCT_DIRENT_D_INO
6470@acindex{STRUCT_DIRENT_D_INO}
6471@cvindex HAVE_STRUCT_DIRENT_D_INO
6472@c @caindex header_dirent_dirent_h
6473@c @caindex member_struct_dirent_d_ino
6474Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6475Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6476member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6477
6478@code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6479@code{d_ino}, not whether its contents are always reliable.
6480Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6481though current systems hide this detail from the user and never return
6482zero @code{d_ino} values.
6483Many current systems report an incorrect @code{d_ino} for a directory
6484entry that is a mount point.
6485@end defmac
6486
6487@defmac AC_STRUCT_DIRENT_D_TYPE
6488@acindex{STRUCT_DIRENT_D_TYPE}
6489@cvindex HAVE_STRUCT_DIRENT_D_TYPE
6490@c @caindex header_dirent_dirent_h
6491@c @caindex member_struct_dirent_d_type
6492Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6493Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6494member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6495@end defmac
6496
6497@anchor{AC_STRUCT_ST_BLOCKS}
6498@defmac AC_STRUCT_ST_BLOCKS
6499@acindex{STRUCT_ST_BLOCKS}
6500@cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6501@cvindex HAVE_ST_BLOCKS
6502@ovindex LIBOBJS
6503@caindex member_struct_stat_st_blocks
6504If @code{struct stat} contains an @code{st_blocks} member, define
6505@code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6506@code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6507@code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6508future.
6509
6510This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6511variable.
6512@end defmac
6513
6514@defmac AC_STRUCT_TM
6515@acindex{STRUCT_TM}
6516@cvindex TM_IN_SYS_TIME
6517@hdrindex{time.h}
6518@hdrindex{sys/time.h}
6519If @file{time.h} does not define @code{struct tm}, define
6520@code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6521had better define @code{struct tm}.
6522
6523This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6524current systems.  New programs need not use this macro.
6525@end defmac
6526
6527@anchor{AC_STRUCT_TIMEZONE}
6528@defmac AC_STRUCT_TIMEZONE
6529@acindex{STRUCT_TIMEZONE}
6530@cvindex HAVE_DECL_TZNAME
6531@cvindex HAVE_STRUCT_TM_TM_ZONE
6532@cvindex HAVE_TM_ZONE
6533@cvindex HAVE_TZNAME
6534@c @caindex member_struct_tm_tm_zone
6535@c @caindex struct_tm
6536Figure out how to get the current timezone.  If @code{struct tm} has a
6537@code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6538obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6539@code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6540define @code{HAVE_DECL_TZNAME}.
6541@end defmac
6542
6543@node Generic Structures
6544@subsection Generic Structure Checks
6545
6546These macros are used to find structure members not covered by the
6547``particular'' test macros.
6548
6549@defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6550  @ovar{action-if-found}, @ovar{action-if-not-found}, @
6551  @dvar{includes, AC_INCLUDES_DEFAULT})
6552@acindex{CHECK_MEMBER}
6553@caindex member_@var{aggregate}_@var{member}
6554Check whether @var{member} is a member of the aggregate @var{aggregate}.
6555If no @var{includes} are specified, the default includes are used
6556(@pxref{Default Includes}).
6557
6558@example
6559AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6560                [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6561                [[#include <pwd.h>]])
6562@end example
6563
6564You can use this macro for submembers:
6565
6566@example
6567AC_CHECK_MEMBER(struct top.middle.bot)
6568@end example
6569
6570This macro caches its result in the
6571@code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6572characters not suitable for a variable name mapped to underscores.
6573@end defmac
6574
6575@anchor{AC_CHECK_MEMBERS}
6576@defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6577  @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6578@acindex{CHECK_MEMBERS}
6579@cvindex HAVE_@var{aggregate}_@var{member}
6580Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6581@var{members} using the previous macro.  When @var{member} belongs to
6582@var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6583capitals, with spaces and dots replaced by underscores).  If
6584@var{action-if-found} is given, it is executed for each of the found
6585members.  If @var{action-if-not-found} is given, it is executed for each
6586of the members that could not be found.
6587
6588@var{includes} is a series of include directives, defaulting to
6589@code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6590prior to the members under test.
6591
6592This macro uses M4 lists:
6593@example
6594AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6595@end example
6596@end defmac
6597
6598
6599@node Types
6600@section Types
6601@cindex Types
6602@cindex C types
6603
6604The following macros check for C types, either builtin or typedefs.  If
6605there is no macro specifically defined to check for a type you need, and
6606you don't need to check for any special properties of it, then you can
6607use a general type-check macro.
6608
6609@menu
6610* Particular Types::            Special handling to find certain types
6611* Generic Types::               How to find other types
6612@end menu
6613
6614@node Particular Types
6615@subsection Particular Type Checks
6616
6617@hdrindex{sys/types.h}
6618@hdrindex{stdlib.h}
6619@hdrindex{stdint.h}
6620@hdrindex{inttypes.h}
6621These macros check for particular C types in @file{sys/types.h},
6622@file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6623exist.
6624
6625The Gnulib @code{stdint} module is an alternate way to define many of
6626these symbols; it is useful if you prefer your code to assume a
6627C99-or-better environment.  @xref{Gnulib}.
6628
6629@anchor{AC_TYPE_GETGROUPS}
6630@defmac AC_TYPE_GETGROUPS
6631@acindex{TYPE_GETGROUPS}
6632@cvindex GETGROUPS_T
6633@caindex type_getgroups
6634Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6635is the base type of the array argument to @code{getgroups}.
6636
6637This macro caches the base type in the @code{ac_cv_type_getgroups}
6638variable.
6639@end defmac
6640
6641@defmac AC_TYPE_INT8_T
6642@acindex{TYPE_INT8_T}
6643@cvindex HAVE_INT8_T
6644@cvindex int8_t
6645@caindex c_int8_t
6646If @file{stdint.h} or @file{inttypes.h} does not define the type
6647@code{int8_t}, define @code{int8_t} to a signed
6648integer type that is exactly 8 bits wide and that uses two's complement
6649representation, if such a type exists.
6650If you are worried about porting to hosts that lack such a type, you can
6651use the results of this macro in C89-or-later code as follows:
6652
6653@example
6654#if HAVE_STDINT_H
6655# include <stdint.h>
6656#endif
6657#if defined INT8_MAX || defined int8_t
6658 @emph{code using int8_t}
6659#else
6660 @emph{complicated alternative using >8-bit 'signed char'}
6661#endif
6662@end example
6663
6664This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6665@end defmac
6666
6667@defmac AC_TYPE_INT16_T
6668@acindex{TYPE_INT16_T}
6669@cvindex HAVE_INT16_T
6670@cvindex int16_t
6671@caindex c_int16_t
6672This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6673@end defmac
6674
6675@defmac AC_TYPE_INT32_T
6676@acindex{TYPE_INT32_T}
6677@cvindex HAVE_INT32_T
6678@cvindex int32_t
6679@caindex c_int32_t
6680This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6681@end defmac
6682
6683@defmac AC_TYPE_INT64_T
6684@acindex{TYPE_INT64_T}
6685@cvindex HAVE_INT64_T
6686@cvindex int64_t
6687@caindex c_int64_t
6688This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6689@end defmac
6690
6691@defmac AC_TYPE_INTMAX_T
6692@acindex{TYPE_INTMAX_T}
6693@cvindex HAVE_INTMAX_T
6694@cvindex intmax_t
6695@c @caindex type_intmax_t
6696If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6697define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6698widest signed integer type.
6699@end defmac
6700
6701@defmac AC_TYPE_INTPTR_T
6702@acindex{TYPE_INTPTR_T}
6703@cvindex HAVE_INTPTR_T
6704@cvindex intptr_t
6705@c @caindex type_intptr_t
6706If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6707define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6708signed integer type wide enough to hold a pointer, if such a type
6709exists.
6710@end defmac
6711
6712@defmac AC_TYPE_LONG_DOUBLE
6713@acindex{TYPE_LONG_DOUBLE}
6714@cvindex HAVE_LONG_DOUBLE
6715@caindex type_long_double
6716If the C compiler supports a working @code{long double} type, define
6717@code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6718same range and precision as @code{double}.
6719
6720This macro caches its result in the @code{ac_cv_type_long_double}
6721variable.
6722
6723This macro is obsolescent, as current C compilers support @code{long
6724double}.  New programs need not use this macro.
6725@end defmac
6726
6727@defmac AC_TYPE_LONG_DOUBLE_WIDER
6728@acindex{TYPE_LONG_DOUBLE_WIDER}
6729@cvindex HAVE_LONG_DOUBLE_WIDER
6730@caindex type_long_double_wider
6731If the C compiler supports a working @code{long double} type with more
6732range or precision than the @code{double} type, define
6733@code{HAVE_LONG_DOUBLE_WIDER}.
6734
6735This macro caches its result in the @code{ac_cv_type_long_double_wider}
6736variable.
6737@end defmac
6738
6739@defmac AC_TYPE_LONG_LONG_INT
6740@acindex{TYPE_LONG_LONG_INT}
6741@cvindex HAVE_LONG_LONG_INT
6742@caindex type_long_long_int
6743If the C compiler supports a working @code{long long int} type, define
6744@code{HAVE_LONG_LONG_INT}.  However, this test does not test
6745@code{long long int} values in preprocessor @code{#if} expressions,
6746because too many compilers mishandle such expressions.
6747@xref{Preprocessor Arithmetic}.
6748
6749This macro caches its result in the @code{ac_cv_type_long_long_int}
6750variable.
6751@end defmac
6752
6753@defmac AC_TYPE_MBSTATE_T
6754@acindex{TYPE_MBSTATE_T}
6755@cvindex mbstate_t
6756@hdrindex{wchar.h}
6757@caindex type_mbstate_t
6758Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6759@code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6760@code{<wchar.h>} does not declare it.
6761
6762This macro caches its result in the @code{ac_cv_type_mbstate_t}
6763variable.
6764@end defmac
6765
6766@anchor{AC_TYPE_MODE_T}
6767@defmac AC_TYPE_MODE_T
6768@acindex{TYPE_MODE_T}
6769@cvindex mode_t
6770@caindex type_mode_t
6771Define @code{mode_t} to a suitable type, if standard headers do not
6772define it.
6773
6774This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6775@end defmac
6776
6777@anchor{AC_TYPE_OFF_T}
6778@defmac AC_TYPE_OFF_T
6779@acindex{TYPE_OFF_T}
6780@cvindex off_t
6781@caindex type_off_t
6782Define @code{off_t} to a suitable type, if standard headers do not
6783define it.
6784
6785This macro caches its result in the @code{ac_cv_type_off_t} variable.
6786@end defmac
6787
6788@anchor{AC_TYPE_PID_T}
6789@defmac AC_TYPE_PID_T
6790@acindex{TYPE_PID_T}
6791@cvindex pid_t
6792@caindex type_pid_t
6793Define @code{pid_t} to a suitable type, if standard headers do not
6794define it.
6795
6796This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6797@end defmac
6798
6799@anchor{AC_TYPE_SIZE_T}
6800@defmac AC_TYPE_SIZE_T
6801@acindex{TYPE_SIZE_T}
6802@cvindex size_t
6803@caindex type_size_t
6804Define @code{size_t} to a suitable type, if standard headers do not
6805define it.
6806
6807This macro caches its result in the @code{ac_cv_type_size_t} variable.
6808@end defmac
6809
6810@defmac AC_TYPE_SSIZE_T
6811@acindex{TYPE_SSIZE_T}
6812@cvindex ssize_t
6813@caindex type_ssize_t
6814Define @code{ssize_t} to a suitable type, if standard headers do not
6815define it.
6816
6817This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6818@end defmac
6819
6820@anchor{AC_TYPE_UID_T}
6821@defmac AC_TYPE_UID_T
6822@acindex{TYPE_UID_T}
6823@cvindex uid_t
6824@cvindex gid_t
6825@caindex type_uid_t
6826Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6827headers do not define them.
6828
6829This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6830@end defmac
6831
6832@defmac AC_TYPE_UINT8_T
6833@acindex{TYPE_UINT8_T}
6834@cvindex HAVE_UINT8_T
6835@cvindex uint8_t
6836@caindex c_uint8_t
6837If @file{stdint.h} or @file{inttypes.h} does not define the type
6838@code{uint8_t}, define @code{uint8_t} to an
6839unsigned integer type that is exactly 8 bits wide, if such a type
6840exists.
6841This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6842@end defmac
6843
6844@defmac AC_TYPE_UINT16_T
6845@acindex{TYPE_UINT16_T}
6846@cvindex HAVE_UINT16_T
6847@cvindex uint16_t
6848@caindex c_uint16_t
6849This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6850@end defmac
6851
6852@defmac AC_TYPE_UINT32_T
6853@acindex{TYPE_UINT32_T}
6854@cvindex HAVE_UINT32_T
6855@cvindex uint32_t
6856@caindex c_uint32_t
6857This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6858@end defmac
6859
6860@defmac AC_TYPE_UINT64_T
6861@acindex{TYPE_UINT64_T}
6862@cvindex HAVE_UINT64_T
6863@cvindex uint64_t
6864@caindex c_uint64_t
6865This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6866@end defmac
6867
6868@defmac AC_TYPE_UINTMAX_T
6869@acindex{TYPE_UINTMAX_T}
6870@cvindex HAVE_UINTMAX_T
6871@cvindex uintmax_t
6872@c @caindex type_uintmax_t
6873If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6874define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6875widest unsigned integer type.
6876@end defmac
6877
6878@defmac AC_TYPE_UINTPTR_T
6879@acindex{TYPE_UINTPTR_T}
6880@cvindex HAVE_UINTPTR_T
6881@cvindex uintptr_t
6882@c @caindex type_uintptr_t
6883If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6884define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6885unsigned integer type wide enough to hold a pointer, if such a type
6886exists.
6887@end defmac
6888
6889@defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6890@acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6891@cvindex HAVE_UNSIGNED_LONG_LONG_INT
6892@caindex type_unsigned_long_long_int
6893If the C compiler supports a working @code{unsigned long long int} type,
6894define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6895@code{unsigned long long int} values in preprocessor @code{#if} expressions,
6896because too many compilers mishandle such expressions.
6897@xref{Preprocessor Arithmetic}.
6898
6899This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6900variable.
6901@end defmac
6902
6903@node Generic Types
6904@subsection Generic Type Checks
6905
6906These macros are used to check for types not covered by the ``particular''
6907test macros.
6908
6909@defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6910  @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6911@acindex{CHECK_TYPE}
6912@caindex type_@var{type}
6913Check whether @var{type} is defined.  It may be a compiler builtin type
6914or defined by the @var{includes}.  @var{includes} is a series of include
6915directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6916Includes}), which are used prior to the type under test.
6917
6918In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6919(@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6920same test is applied when compiling for C++, which means that in C++
6921@var{type} should be a type-id and should not be an anonymous
6922@samp{struct} or @samp{union}.
6923
6924This macro caches its result in the @code{ac_cv_type_@var{type}}
6925variable, with @samp{*} mapped to @samp{p} and other characters not
6926suitable for a variable name mapped to underscores.
6927@end defmac
6928
6929
6930@defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6931  @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6932@acindex{CHECK_TYPES}
6933@cvindex HAVE_@var{type}
6934For each @var{type} of the @var{types} that is defined, define
6935@code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6936the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6937specified, the default includes are used (@pxref{Default Includes}).  If
6938@var{action-if-found} is given, it is additional shell code to execute
6939when one of the types is found.  If @var{action-if-not-found} is given,
6940it is executed when one of the types is not found.
6941
6942This macro uses M4 lists:
6943@example
6944AC_CHECK_TYPES([ptrdiff_t])
6945AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6946AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6947@end example
6948
6949@end defmac
6950
6951Autoconf, up to 2.13, used to provide to another version of
6952@code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6953compatibility, a simple heuristic, quite safe but not totally, is
6954implemented.  In case of doubt, read the documentation of the former
6955@code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6956
6957
6958@node Compilers and Preprocessors
6959@section Compilers and Preprocessors
6960@cindex Compilers
6961@cindex Preprocessors
6962
6963@ovindex EXEEXT
6964All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6965@code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6966the output of the compiler, typically to the empty string if
6967Posix and @samp{.exe} if a DOS variant.
6968
6969@ovindex OBJEXT
6970They also define the output variable @code{OBJEXT} based on the
6971output of the compiler, after @file{.c} files have been excluded, typically
6972to @samp{o} if Posix, @samp{obj} if a DOS variant.
6973
6974If the compiler being used does not produce executables, the tests fail.  If
6975the executables can't be run, and cross-compilation is not enabled, they
6976fail too.  @xref{Manual Configuration}, for more on support for cross
6977compiling.
6978
6979@menu
6980* Specific Compiler Characteristics::  Some portability issues
6981* Generic Compiler Characteristics::  Language independent tests and features
6982* C Compiler::                  Checking its characteristics
6983* C++ Compiler::                Likewise
6984* Objective C Compiler::        Likewise
6985* Objective C++ Compiler::      Likewise
6986* Erlang Compiler and Interpreter::  Likewise
6987* Fortran Compiler::            Likewise
6988* Go Compiler::                 Likewise
6989@end menu
6990
6991@node Specific Compiler Characteristics
6992@subsection Specific Compiler Characteristics
6993
6994Some compilers exhibit different behaviors.
6995
6996@table @asis
6997@item Static/Dynamic Expressions
6998Autoconf relies on a trick to extract one bit of information from the C
6999compiler: using negative array sizes.  For instance the following
7000excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7001bytes wide:
7002
7003@example
7004static int test_array[sizeof (int) == 4 ? 1 : -1];
7005@end example
7006
7007@noindent
7008To our knowledge, there is a single compiler that does not support this
7009trick: the HP C compilers (the real ones, not only the
7010``bundled'') on HP-UX 11.00.
7011They incorrectly reject the above program with the diagnostic
7012``Variable-length arrays cannot have static storage.''
7013This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7014not from the @code{? 1 : -1}, and
7015Autoconf works around this problem by casting @code{sizeof (int)} to
7016@code{long int} before comparing it.
7017@end table
7018
7019@node Generic Compiler Characteristics
7020@subsection Generic Compiler Characteristics
7021
7022@anchor{AC_CHECK_SIZEOF}
7023@defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7024  @dvar{includes, AC_INCLUDES_DEFAULT})
7025@acindex{CHECK_SIZEOF}
7026@cvindex SIZEOF_@var{type-or-expr}
7027@caindex sizeof_@var{type-or-expr}
7028Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7029the size in bytes of @var{type-or-expr}, which may be either a type or
7030an expression returning a value that has a size.  If the expression
7031@samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7032@var{includes} is a series of include directives, defaulting to
7033@code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7034prior to the expression under test.
7035
7036This macro now works even when cross-compiling.  The @var{unused}
7037argument was used when cross-compiling.
7038
7039For example, the call
7040
7041@example
7042@c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7043AC_CHECK_SIZEOF([int *])
7044@end example
7045
7046@noindent
7047defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7048
7049This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7050variable, with @samp{*} mapped to @samp{p} and other characters not
7051suitable for a variable name mapped to underscores.
7052@end defmac
7053
7054@defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7055@acindex{CHECK_ALIGNOF}
7056@cvindex ALIGNOF_@var{type}
7057@caindex alignof_@var{type-or-expr}
7058Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7059alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7060a structure member declaration.  If @samp{type} is unknown, the result
7061is 0.  If no @var{includes} are specified, the default includes are used
7062(@pxref{Default Includes}).
7063
7064This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7065variable, with @samp{*} mapped to @samp{p} and other characters not
7066suitable for a variable name mapped to underscores.
7067@end defmac
7068
7069@defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7070  @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7071@acindex{COMPUTE_INT}
7072Store into the shell variable @var{var} the value of the integer
7073@var{expression}.  The
7074value should fit in an initializer in a C variable of type @code{signed
7075long}.  To support cross compilation (in which case, the macro only works on
7076hosts that use twos-complement arithmetic), it should be possible to evaluate
7077the expression at compile-time.  If no @var{includes} are specified, the
7078default includes are used (@pxref{Default Includes}).
7079
7080Execute @var{action-if-fails} if the value cannot be determined correctly.
7081@end defmac
7082
7083@defmac AC_LANG_WERROR
7084@acindex{LANG_WERROR}
7085Normally Autoconf ignores warnings generated by the compiler, linker, and
7086preprocessor.  If this macro is used, warnings count as fatal
7087errors for the current language.  This macro is useful when the
7088results of configuration are used where warnings are unacceptable; for
7089instance, if parts of a program are built with the GCC
7090@option{-Werror}
7091option.  If the whole program is built using @option{-Werror} it is
7092often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7093etc.).
7094@end defmac
7095
7096@defmac AC_OPENMP
7097@acindex{OPENMP}
7098@cvindex _OPENMP
7099@ovindex OPENMP_CFLAGS
7100@ovindex OPENMP_CXXFLAGS
7101@ovindex OPENMP_FFLAGS
7102@ovindex OPENMP_FCFLAGS
7103@caindex prog_c_openmp
7104@caindex prog_cxx_openmp
7105@caindex prog_f77_openmp
7106@caindex prog_fc_openmp
7107@uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7108and Fortran that simplify optimization of shared memory parallelism,
7109which is a common problem on multicore CPUs.
7110
7111If the current language is C, the macro @code{AC_OPENMP} sets the
7112variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7113supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7114compiler already supports OpenMP, if it has no way to activate OpenMP
7115support, or if the user rejects OpenMP support by invoking
7116@samp{configure} with the @samp{--disable-openmp} option.
7117
7118@code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7119preprocessing program source, and when linking programs.  Therefore you
7120need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7121that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7122need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7123OpenMP support is revealed at compile time by the preprocessor macro
7124@code{_OPENMP}.
7125
7126Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7127shared library to the program's dependencies, so its use is recommended
7128only on programs that actually require OpenMP.
7129
7130If the current language is C++, @code{AC_OPENMP} sets the variable
7131@code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7132hold as for C.
7133
7134If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7135the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7136respectively.  Similar remarks as for C hold, except that
7137@code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7138signals OpenMP support.
7139
7140For portability, it is best to avoid spaces between @samp{#} and
7141@samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7142@samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7143latter.
7144
7145This macro caches its result in the @code{ac_cv_prog_c_openmp},
7146@code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7147@code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7148@end defmac
7149
7150@node C Compiler
7151@subsection C Compiler Characteristics
7152
7153The following macros provide ways to find and exercise a C Compiler.
7154There are a few constructs that ought to be avoided, but do not deserve
7155being checked for, since they can easily be worked around.
7156
7157@table @asis
7158@item Don't use lines containing solitary backslashes
7159They tickle a bug in the HP-UX C compiler (checked on
7160HP-UX 10.20,
716111.00, and 11i).  When given the following source:
7162
7163@example
7164#ifdef __STDC__
7165/\
7166* A comment with backslash-newlines in it.  %@{ %@} *\
7167\
7168/
7169char str[] = "\\
7170" A string with backslash-newlines in it %@{ %@} \\
7171"";
7172char apostrophe = '\\
7173\
7174'\
7175';
7176#endif
7177@end example
7178
7179@noindent
7180the compiler incorrectly fails with the diagnostics ``Non-terminating
7181comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7182Removing the lines with solitary backslashes solves the problem.
7183
7184@item Don't compile several files at once if output matters to you
7185Some compilers, such as HP's, report names of files being
7186compiled when given more than one file operand.  For instance:
7187
7188@example
7189$ @kbd{cc a.c b.c}
7190a.c:
7191b.c:
7192@end example
7193
7194@noindent
7195This can cause problems if you observe the output of the compiler to
7196detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7197b.o} solves the issue.
7198
7199@item Don't rely on @code{#error} failing
7200The IRIX C compiler does not fail when #error is preprocessed; it
7201simply emits a diagnostic and continues, exiting successfully.  So,
7202instead of an error directive like @code{#error "Unsupported word size"}
7203it is more portable to use an invalid directive like @code{#Unsupported
7204word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7205OK, since installers with inadequate compilers like IRIX can simply
7206examine these compilers' diagnostic output.
7207
7208@item Don't rely on correct @code{#line} support
7209On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7210diagnoses @code{#line} directives whose line
7211numbers are greater than 32767.  Nothing in Posix
7212makes this invalid.  That is why Autoconf stopped issuing
7213@code{#line} directives.
7214@end table
7215
7216@defmac AC_PROG_CC (@ovar{compiler-search-list})
7217@acindex{PROG_CC}
7218@evindex CC
7219@evindex CFLAGS
7220@ovindex CC
7221@ovindex CFLAGS
7222@caindex prog_cc_c89
7223Determine a C compiler to use.  If @code{CC} is not already set in the
7224environment, check for @code{gcc} and @code{cc}, then for other C
7225compilers.  Set output variable @code{CC} to the name of the compiler
7226found.
7227
7228This macro may, however, be invoked with an optional first argument
7229which, if specified, must be a blank-separated list of C compilers to
7230search for.  This just gives the user an opportunity to specify an
7231alternative search list for the C compiler.  For example, if you didn't
7232like the default order, then you could invoke @code{AC_PROG_CC} like
7233this:
7234
7235@example
7236AC_PROG_CC([gcc cl cc])
7237@end example
7238
7239If the C compiler does not handle function prototypes correctly by
7240default, try to add an option to output variable @code{CC} to make it
7241so.  This macro tries various options that select standard-conformance
7242modes on various systems.
7243
7244After calling this macro you can check whether the C compiler has been
7245set to accept ANSI C89 (ISO C90); if not, the shell
7246variable
7247@code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7248@code{AC_C_PROTOTYPES} below.
7249
7250If using the GNU C compiler, set shell variable @code{GCC} to
7251@samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7252it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7253where GCC does not accept @option{-g}), or @option{-g} for
7254other compilers.  If your package does not like this default, then it is
7255acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7256and before @code{AC_PROG_CC} to select an empty default instead.
7257
7258Many Autoconf macros use a compiler, and thus call
7259@samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7260determined before the body of the outermost @code{AC_DEFUN} macro.
7261Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7262performs certain checks (such as the proper value of @env{EXEEXT}) only
7263on the first invocation.  Therefore, care must be used when invoking
7264this macro from within another macro rather than at the top level
7265(@pxref{Expanded Before Required}).
7266@end defmac
7267
7268@anchor{AC_PROG_CC_C_O}
7269@defmac AC_PROG_CC_C_O
7270@acindex{PROG_CC_C_O}
7271@cvindex NO_MINUS_C_MINUS_O
7272@caindex prog_cc_@var{compiler}_c_o
7273If the C compiler does not accept the @option{-c} and @option{-o} options
7274simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7275tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7276the first @code{cc} in the path.  The test fails if one fails.  This
7277macro was created for GNU Make to choose the default C compilation
7278rule.
7279
7280For the compiler @var{compiler}, this macro caches its result in the
7281@code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7282@end defmac
7283
7284
7285@defmac AC_PROG_CPP
7286@acindex{PROG_CPP}
7287@evindex CPP
7288@ovindex CPP
7289Set output variable @code{CPP} to a command that runs the
7290C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7291It is only portable to run @code{CPP} on files with a @file{.c}
7292extension.
7293
7294Some preprocessors don't indicate missing include files by the error
7295status.  For such preprocessors an internal variable is set that causes
7296other macros to check the standard error from the preprocessor and
7297consider the test failed if any warnings have been reported.
7298For most preprocessors, though, warnings do not cause include-file
7299tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7300@end defmac
7301
7302@defmac AC_PROG_CPP_WERROR
7303@acindex{PROG_CPP_WERROR}
7304@ovindex CPP
7305This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7306preprocessor as errors even if the preprocessor exit status indicates
7307success.  This is useful for avoiding headers that generate mandatory
7308warnings, such as deprecation notices.
7309@end defmac
7310
7311
7312The following macros check for C compiler or machine architecture
7313features.  To check for characteristics not listed here, use
7314@code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7315@code{AC_RUN_IFELSE} (@pxref{Runtime}).
7316
7317@defmac AC_PROG_CC_STDC
7318@acindex{PROG_CC_STDC}
7319@caindex prog_cc_stdc
7320If the C compiler cannot compile ISO Standard C (currently
7321C99), try to add an option to output variable @code{CC} to make it work.
7322If the compiler does not support C99, fall back to supporting
7323ANSI C89 (ISO C90).
7324
7325After calling this macro you can check whether the C compiler has been
7326set to accept Standard C; if not, the shell variable
7327@code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7328@end defmac
7329
7330@defmac AC_PROG_CC_C89
7331@acindex{PROG_CC_C89}
7332@caindex prog_cc_c89
7333If the C compiler is not in ANSI C89 (ISO C90) mode by
7334default, try to add an option to output variable @code{CC} to make it
7335so.  This macro tries various options that select ANSI C89 on
7336some system or another, preferring extended functionality modes over
7337strict conformance modes.  It considers the compiler to be in
7338ANSI C89 mode if it handles function prototypes correctly.
7339
7340After calling this macro you can check whether the C compiler has been
7341set to accept ANSI C89; if not, the shell variable
7342@code{ac_cv_prog_cc_c89} is set to @samp{no}.
7343
7344This macro is called automatically by @code{AC_PROG_CC}.
7345@end defmac
7346
7347@defmac AC_PROG_CC_C99
7348@acindex{PROG_CC_C99}
7349@caindex prog_cc_c99
7350If the C compiler is not in C99 mode by default, try to add an
7351option to output variable @code{CC} to make it so.  This macro tries
7352various options that select C99 on some system or another, preferring
7353extended functionality modes over strict conformance modes.  It
7354considers the compiler to be in C99 mode if it handles @code{_Bool},
7355@code{//} comments, flexible array members, @code{inline}, signed and
7356unsigned @code{long long int}, mixed code and declarations, named
7357initialization of structs,
7358@code{restrict}, @code{va_copy}, varargs macros, variable declarations
7359in @code{for} loops, and variable length arrays.
7360
7361After calling this macro you can check whether the C compiler has been
7362set to accept C99; if not, the shell variable
7363@code{ac_cv_prog_cc_c99} is set to @samp{no}.
7364@end defmac
7365
7366@defmac AC_C_BACKSLASH_A
7367@acindex{C_BACKSLASH_A}
7368@cvindex HAVE_C_BACKSLASH_A
7369Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7370@samp{\a}.
7371
7372This macro is obsolescent, as current C compilers understand @samp{\a}.
7373New programs need not use this macro.
7374@end defmac
7375
7376@anchor{AC_C_BIGENDIAN}
7377@defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7378  @ovar{action-if-unknown}, @ovar{action-if-universal})
7379@acindex{C_BIGENDIAN}
7380@cvindex WORDS_BIGENDIAN
7381@cindex Endianness
7382If words are stored with the most significant byte first (like Motorola
7383and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7384the least significant byte first (like Intel and VAX CPUs), execute
7385@var{action-if-false}.
7386
7387This macro runs a test-case if endianness cannot be determined from the
7388system header files.  When cross-compiling, the test-case is not run but
7389grep'ed for some magic values.  @var{action-if-unknown} is executed if
7390the latter case fails to determine the byte sex of the host system.
7391
7392In some cases a single run of a compiler can generate code for multiple
7393architectures.  This can happen, for example, when generating Mac OS X
7394universal binary files, which work on both PowerPC and Intel
7395architectures.  In this case, the different variants might be for
7396different architectures whose endiannesses differ.  If
7397@command{configure} detects this, it executes @var{action-if-universal}
7398instead of @var{action-if-unknown}.
7399
7400The default for @var{action-if-true} is to define
7401@samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7402nothing.  The default for @var{action-if-unknown} is to
7403abort configure and tell the installer how to bypass this test.
7404And finally, the default for @var{action-if-universal} is to ensure that
7405@samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7406detected and the current code is big-endian; this default works only if
7407@command{autoheader} is used (@pxref{autoheader Invocation}).
7408
7409If you use this macro without specifying @var{action-if-universal}, you
7410should also use @code{AC_CONFIG_HEADERS}; otherwise
7411@samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7412binary files.
7413@end defmac
7414
7415@anchor{AC_C_CONST}
7416@defmac AC_C_CONST
7417@acindex{C_CONST}
7418@cvindex const
7419@caindex c_const
7420If the C compiler does not fully support the @code{const} keyword,
7421define @code{const} to be empty.  Some C compilers that do
7422not define @code{__STDC__} do support @code{const}; some compilers that
7423define @code{__STDC__} do not completely support @code{const}.  Programs
7424can simply use @code{const} as if every C compiler supported it; for
7425those that don't, the makefile or configuration header file
7426defines it as empty.
7427
7428Occasionally installers use a C++ compiler to compile C code, typically
7429because they lack a C compiler.  This causes problems with @code{const},
7430because C and C++ treat @code{const} differently.  For example:
7431
7432@example
7433const int foo;
7434@end example
7435
7436@noindent
7437is valid in C but not in C++.  These differences unfortunately cannot be
7438papered over by defining @code{const} to be empty.
7439
7440If @command{autoconf} detects this situation, it leaves @code{const} alone,
7441as this generally yields better results in practice.  However, using a
7442C++ compiler to compile C code is not recommended or supported, and
7443installers who run into trouble in this area should get a C compiler
7444like GCC to compile their C code.
7445
7446This macro caches its result in the @code{ac_cv_c_const} variable.
7447
7448This macro is obsolescent, as current C compilers support @code{const}.
7449New programs need not use this macro.
7450@end defmac
7451
7452@defmac AC_C_RESTRICT
7453@acindex{C_RESTRICT}
7454@cvindex restrict
7455@caindex c_restrict
7456If the C compiler recognizes a variant spelling for the @code{restrict}
7457keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7458then define @code{restrict} to that; this is more likely to do the right
7459thing with compilers that support language variants where plain
7460@code{restrict} is not a keyword.  Otherwise, if the C compiler
7461recognizes the @code{restrict} keyword, don't do anything.
7462Otherwise, define @code{restrict} to be empty.
7463Thus, programs may simply use @code{restrict} as if every C compiler
7464supported it; for those that do not, the makefile
7465or configuration header defines it away.
7466
7467Although support in C++ for the @code{restrict} keyword is not
7468required, several C++ compilers do accept the keyword.
7469This macro works for them, too.
7470
7471This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7472if @code{restrict} is not supported, and a supported spelling otherwise.
7473@end defmac
7474
7475@defmac AC_C_VOLATILE
7476@acindex{C_VOLATILE}
7477@cvindex volatile
7478If the C compiler does not understand the keyword @code{volatile},
7479define @code{volatile} to be empty.  Programs can simply use
7480@code{volatile} as if every C compiler supported it; for those that do
7481not, the makefile or configuration header defines it as
7482empty.
7483
7484If the correctness of your program depends on the semantics of
7485@code{volatile}, simply defining it to be empty does, in a sense, break
7486your code.  However, given that the compiler does not support
7487@code{volatile}, you are at its mercy anyway.  At least your
7488program compiles, when it wouldn't before.
7489@xref{Volatile Objects}, for more about @code{volatile}.
7490
7491In general, the @code{volatile} keyword is a standard C feature, so
7492you might expect that @code{volatile} is available only when
7493@code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7494support volatile, but does not define @code{__STDC__}.
7495
7496This macro is obsolescent, as current C compilers support @code{volatile}.
7497New programs need not use this macro.
7498@end defmac
7499
7500@anchor{AC_C_INLINE}
7501@defmac AC_C_INLINE
7502@acindex{C_INLINE}
7503@cvindex inline
7504If the C compiler supports the keyword @code{inline}, do nothing.
7505Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7506if it accepts one of those, otherwise define @code{inline} to be empty.
7507@end defmac
7508
7509@anchor{AC_C_CHAR_UNSIGNED}
7510@defmac AC_C_CHAR_UNSIGNED
7511@acindex{C_CHAR_UNSIGNED}
7512@cvindex __CHAR_UNSIGNED__
7513If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7514unless the C compiler predefines it.
7515
7516These days, using this macro is not necessary.  The same information can
7517be determined by this portable alternative, thus avoiding the use of
7518preprocessor macros in the namespace reserved for the implementation.
7519
7520@example
7521#include <limits.h>
7522#if CHAR_MIN == 0
7523# define CHAR_UNSIGNED 1
7524#endif
7525@end example
7526@end defmac
7527
7528@defmac AC_C_STRINGIZE
7529@acindex{C_STRINGIZE}
7530@cvindex HAVE_STRINGIZE
7531If the C preprocessor supports the stringizing operator, define
7532@code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7533found in macros such as this:
7534
7535@example
7536#define x(y) #y
7537@end example
7538
7539This macro is obsolescent, as current C compilers support the
7540stringizing operator.  New programs need not use this macro.
7541@end defmac
7542
7543@defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7544@acindex{C_FLEXIBLE_ARRAY_MEMBER}
7545@cvindex FLEXIBLE_ARRAY_MEMBER
7546If the C compiler supports flexible array members, define
7547@code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7548That way, a declaration like this:
7549
7550@example
7551struct s
7552  @{
7553    size_t n_vals;
7554    double val[FLEXIBLE_ARRAY_MEMBER];
7555  @};
7556@end example
7557
7558@noindent
7559will let applications use the ``struct hack'' even with compilers that
7560do not support flexible array members.  To allocate and use such an
7561object, you can use code like this:
7562
7563@example
7564size_t i;
7565size_t n = compute_value_count ();
7566struct s *p =
7567   malloc (offsetof (struct s, val)
7568           + n * sizeof (double));
7569p->n_vals = n;
7570for (i = 0; i < n; i++)
7571  p->val[i] = compute_value (i);
7572@end example
7573@end defmac
7574
7575@defmac AC_C_VARARRAYS
7576@acindex{C_VARARRAYS}
7577@cvindex HAVE_C_VARARRAYS
7578If the C compiler supports variable-length arrays, define
7579@code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7580storage duration whose length is determined at run time, when the array
7581is declared.
7582@end defmac
7583
7584@defmac AC_C_TYPEOF
7585@acindex{C_TYPEOF}
7586@cvindex HAVE_TYPEOF
7587@cvindex typeof
7588If the C compiler supports GCC's @code{typeof} syntax either
7589directly or
7590through a different spelling of the keyword (e.g., @code{__typeof__}),
7591define @code{HAVE_TYPEOF}.  If the support is available only through a
7592different spelling, define @code{typeof} to that spelling.
7593@end defmac
7594
7595@defmac AC_C_PROTOTYPES
7596@acindex{C_PROTOTYPES}
7597@cvindex PROTOTYPES
7598@cvindex __PROTOTYPES
7599@cvindex PARAMS
7600If function prototypes are understood by the compiler (as determined by
7601@code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7602Defining @code{__PROTOTYPES} is for the benefit of
7603header files that cannot use macros that infringe on user name space.
7604
7605This macro is obsolescent, as current C compilers support prototypes.
7606New programs need not use this macro.
7607@end defmac
7608
7609@anchor{AC_PROG_GCC_TRADITIONAL}
7610@defmac AC_PROG_GCC_TRADITIONAL
7611@acindex{PROG_GCC_TRADITIONAL}
7612@ovindex CC
7613Add @option{-traditional} to output variable @code{CC} if using the
7614GNU C compiler and @code{ioctl} does not work properly without
7615@option{-traditional}.  That usually happens when the fixed header files
7616have not been installed on an old system.
7617
7618This macro is obsolescent, since current versions of the GNU C
7619compiler fix the header files automatically when installed.
7620@end defmac
7621
7622
7623@node C++ Compiler
7624@subsection C++ Compiler Characteristics
7625
7626
7627@defmac AC_PROG_CXX (@ovar{compiler-search-list})
7628@acindex{PROG_CXX}
7629@evindex CXX
7630@evindex CXXFLAGS
7631@ovindex CXX
7632@ovindex CXXFLAGS
7633Determine a C++ compiler to use.  Check whether the environment variable
7634@code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7635variable @code{CXX} to its value.
7636
7637Otherwise, if the macro is invoked without an argument, then search for
7638a C++ compiler under the likely names (first @code{g++} and @code{c++}
7639then other names).  If none of those checks succeed, then as a last
7640resort set @code{CXX} to @code{g++}.
7641
7642This macro may, however, be invoked with an optional first argument
7643which, if specified, must be a blank-separated list of C++ compilers to
7644search for.  This just gives the user an opportunity to specify an
7645alternative search list for the C++ compiler.  For example, if you
7646didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7647like this:
7648
7649@example
7650AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7651@end example
7652
7653If using the GNU C++ compiler, set shell variable @code{GXX} to
7654@samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7655it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7656systems where G++ does not accept @option{-g}), or @option{-g} for other
7657compilers.  If your package does not like this default, then it is
7658acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7659and before @code{AC_PROG_CXX} to select an empty default instead.
7660
7661@end defmac
7662
7663@defmac AC_PROG_CXXCPP
7664@acindex{PROG_CXXCPP}
7665@evindex CXXCPP
7666@ovindex CXXCPP
7667Set output variable @code{CXXCPP} to a command that runs the C++
7668preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7669It is portable to run @code{CXXCPP} only on files with a @file{.c},
7670@file{.C}, @file{.cc}, or @file{.cpp} extension.
7671
7672Some preprocessors don't indicate missing include files by the error
7673status.  For such preprocessors an internal variable is set that causes
7674other macros to check the standard error from the preprocessor and
7675consider the test failed if any warnings have been reported.  However,
7676it is not known whether such broken preprocessors exist for C++.
7677@end defmac
7678
7679@defmac AC_PROG_CXX_C_O
7680@acindex{PROG_CXX_C_O}
7681@cvindex CXX_NO_MINUS_C_MINUS_O
7682Test whether the C++ compiler accepts the options @option{-c} and
7683@option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7684if it does not.
7685@end defmac
7686
7687
7688@node Objective C Compiler
7689@subsection Objective C Compiler Characteristics
7690
7691
7692@defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7693@acindex{PROG_OBJC}
7694@evindex OBJC
7695@evindex OBJCFLAGS
7696@ovindex OBJC
7697@ovindex OBJCFLAGS
7698Determine an Objective C compiler to use.  If @code{OBJC} is not already
7699set in the environment, check for Objective C compilers.  Set output
7700variable @code{OBJC} to the name of the compiler found.
7701
7702This macro may, however, be invoked with an optional first argument
7703which, if specified, must be a blank-separated list of Objective C compilers to
7704search for.  This just gives the user an opportunity to specify an
7705alternative search list for the Objective C compiler.  For example, if you
7706didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7707like this:
7708
7709@example
7710AC_PROG_OBJC([gcc objcc objc])
7711@end example
7712
7713If using the GNU Objective C compiler, set shell variable
7714@code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7715already set, set it to @option{-g -O2} for the GNU Objective C
7716compiler (@option{-O2} on systems where @command{gcc} does not accept
7717@option{-g}), or @option{-g} for other compilers.
7718@end defmac
7719
7720@defmac AC_PROG_OBJCPP
7721@acindex{PROG_OBJCPP}
7722@evindex OBJCPP
7723@ovindex OBJCPP
7724Set output variable @code{OBJCPP} to a command that runs the Objective C
7725preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7726@end defmac
7727
7728
7729@node Objective C++ Compiler
7730@subsection Objective C++ Compiler Characteristics
7731
7732
7733@defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7734@acindex{PROG_OBJCXX}
7735@evindex OBJCXX
7736@evindex OBJCXXFLAGS
7737@ovindex OBJCXX
7738@ovindex OBJCXXFLAGS
7739Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7740set in the environment, check for Objective C++ compilers.  Set output
7741variable @code{OBJCXX} to the name of the compiler found.
7742
7743This macro may, however, be invoked with an optional first argument
7744which, if specified, must be a blank-separated list of Objective C++ compilers
7745to search for.  This just gives the user an opportunity to specify an
7746alternative search list for the Objective C++ compiler.  For example, if you
7747didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7748like this:
7749
7750@example
7751AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7752@end example
7753
7754If using the GNU Objective C++ compiler, set shell variable
7755@code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7756already set, set it to @option{-g -O2} for the GNU Objective C++
7757compiler (@option{-O2} on systems where @command{gcc} does not accept
7758@option{-g}), or @option{-g} for other compilers.
7759@end defmac
7760
7761@defmac AC_PROG_OBJCXXCPP
7762@acindex{PROG_OBJCXXCPP}
7763@evindex OBJCXXCPP
7764@ovindex OBJCXXCPP
7765Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7766preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7767@end defmac
7768
7769
7770@node Erlang Compiler and Interpreter
7771@subsection Erlang Compiler and Interpreter Characteristics
7772@cindex Erlang
7773
7774Autoconf defines the following macros for determining paths to the essential
7775Erlang/OTP programs:
7776
7777@defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7778@acindex{ERLANG_PATH_ERLC}
7779@evindex ERLC
7780@evindex ERLCFLAGS
7781@ovindex ERLC
7782@ovindex ERLCFLAGS
7783Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7784environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7785complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7786is not set in the environment, set it to an empty value.
7787
7788The two optional arguments have the same meaning as the two last arguments of
7789macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7790example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7791directory:
7792
7793@example
7794AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7795@end example
7796@end defmac
7797
7798@defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7799@acindex{ERLANG_NEED_ERLC}
7800A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7801error message and exits the @command{configure} script if the @command{erlc}
7802program is not found.
7803@end defmac
7804
7805@defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7806@acindex{ERLANG_PATH_ERL}
7807@evindex ERL
7808@ovindex ERL
7809Determine an Erlang interpreter to use.  If @code{ERL} is not already
7810set in the
7811environment, check for @command{erl}.  Set output variable @code{ERL} to the
7812complete path of the interpreter command found.
7813
7814The two optional arguments have the same meaning as the two last arguments of
7815macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7816example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7817directory:
7818
7819@example
7820AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7821@end example
7822@end defmac
7823
7824@defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7825@acindex{ERLANG_NEED_ERL}
7826A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7827error message and exits the @command{configure} script if the @command{erl}
7828program is not found.
7829@end defmac
7830
7831
7832@node Fortran Compiler
7833@subsection Fortran Compiler Characteristics
7834@cindex Fortran
7835@cindex F77
7836
7837The Autoconf Fortran support is divided into two categories: legacy
7838Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7839The former are intended for traditional Fortran 77 code, and have output
7840variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7841are for newer programs that can (or must) compile under the newer
7842Fortran standards, and have output variables like @code{FC},
7843@code{FCFLAGS}, and @code{FCLIBS}.
7844
7845Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7846@code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7847@code{FC} and @code{F77} macros behave almost identically, and so they
7848are documented together in this section.
7849
7850
7851@defmac AC_PROG_F77 (@ovar{compiler-search-list})
7852@acindex{PROG_F77}
7853@evindex F77
7854@evindex FFLAGS
7855@ovindex F77
7856@ovindex FFLAGS
7857@caindex f77_compiler_gnu
7858@caindex prog_f77_g
7859Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7860set in the environment, then check for @code{g77} and @code{f77}, and
7861then some other names.  Set the output variable @code{F77} to the name
7862of the compiler found.
7863
7864This macro may, however, be invoked with an optional first argument
7865which, if specified, must be a blank-separated list of Fortran 77
7866compilers to search for.  This just gives the user an opportunity to
7867specify an alternative search list for the Fortran 77 compiler.  For
7868example, if you didn't like the default order, then you could invoke
7869@code{AC_PROG_F77} like this:
7870
7871@example
7872AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7873@end example
7874
7875If using @code{g77} (the GNU Fortran 77 compiler), then
7876set the shell variable @code{G77} to @samp{yes}.
7877If the output variable @code{FFLAGS} was not already set in the
7878environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7879where @code{g77} does not accept @option{-g}).  Otherwise, set
7880@code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7881
7882The result of the GNU test is cached in the
7883@code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7884@code{ac_cv_prog_f77_g} variable.
7885@end defmac
7886
7887@defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7888@acindex{PROG_FC}
7889@evindex FC
7890@evindex FCFLAGS
7891@ovindex FC
7892@ovindex FCFLAGS
7893@caindex fc_compiler_gnu
7894@caindex prog_fc_g
7895Determine a Fortran compiler to use.  If @code{FC} is not already set in
7896the environment, then @code{dialect} is a hint to indicate what Fortran
7897dialect to search for; the default is to search for the newest available
7898dialect.  Set the output variable @code{FC} to the name of the compiler
7899found.
7900
7901By default, newer dialects are preferred over older dialects, but if
7902@code{dialect} is specified then older dialects are preferred starting
7903with the specified dialect.  @code{dialect} can currently be one of
7904Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7905which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7906and no attempt is made to guarantee that a particular language standard
7907is actually supported.  Thus, it is preferable that you avoid the
7908@code{dialect} option, and use AC_PROG_FC only for code compatible with
7909the latest Fortran standard.
7910
7911This macro may, alternatively, be invoked with an optional first argument
7912which, if specified, must be a blank-separated list of Fortran
7913compilers to search for, just as in @code{AC_PROG_F77}.
7914
7915If using @code{gfortran} or @code{g77} (the GNU Fortran compilers), then
7916set the shell variable @code{GFC} to @samp{yes}.
7917If the output variable @code{FCFLAGS} was not already set in the
7918environment, then set it to @option{-g -02} for GNU @code{g77} (or
7919@option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7920set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7921
7922The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7923variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7924variable.
7925@end defmac
7926
7927@defmac AC_PROG_F77_C_O
7928@defmacx AC_PROG_FC_C_O
7929@acindex{PROG_F77_C_O}
7930@acindex{PROG_FC_C_O}
7931@cvindex F77_NO_MINUS_C_MINUS_O
7932@cvindex FC_NO_MINUS_C_MINUS_O
7933@caindex prog_f77_c_o
7934@caindex prog_fc_c_o
7935Test whether the Fortran compiler accepts the options @option{-c} and
7936@option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7937@code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7938
7939The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7940@code{ac_cv_prog_fc_c_o} variable, respectively.
7941@end defmac
7942
7943The following macros check for Fortran compiler characteristics.
7944To check for characteristics not listed here, use
7945@code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7946@code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7947current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7948or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7949
7950
7951@defmac AC_F77_LIBRARY_LDFLAGS
7952@defmacx AC_FC_LIBRARY_LDFLAGS
7953@acindex{F77_LIBRARY_LDFLAGS}
7954@ovindex FLIBS
7955@acindex{FC_LIBRARY_LDFLAGS}
7956@ovindex FCLIBS
7957@caindex prog_f77_v
7958@caindex prog_fc_v
7959@caindex f77_libs
7960@caindex fc_libs
7961Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7962@dfn{Fortran intrinsic and runtime libraries} that are required to
7963successfully link a Fortran program or shared library.  The output
7964variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7965should be included after @code{LIBS} when linking).
7966
7967This macro is intended to be used in those situations when it is
7968necessary to mix, e.g., C++ and Fortran source code in a single
7969program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7970automake, GNU Automake}).
7971
7972For example, if object files from a C++ and Fortran compiler must be
7973linked together, then the C++ compiler/linker must be used for linking
7974(since special C++-ish things need to happen at link time like calling
7975global constructors, instantiating templates, enabling exception
7976support, etc.).
7977
7978However, the Fortran intrinsic and runtime libraries must be linked in
7979as well, but the C++ compiler/linker doesn't know by default how to add
7980these Fortran 77 libraries.  Hence, this macro was created to determine
7981these Fortran libraries.
7982
7983The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7984@code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7985link C/C++ with Fortran; see below.  Further, it is highly recommended
7986that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7987because the complex defines that the function wrapper macros create
7988may not work with C/C++ compiler drivers.
7989
7990These macros internally compute the flag needed to verbose linking
7991output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
7992variables, respectively.  The computed linker flags are cached in
7993@code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
7994@end defmac
7995
7996@defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
7997  AC_MSG_FAILURE})
7998@defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
7999  AC_MSG_FAILURE})
8000@acindex{F77_DUMMY_MAIN}
8001@cvindex F77_DUMMY_MAIN
8002@acindex{FC_DUMMY_MAIN}
8003@cvindex FC_DUMMY_MAIN
8004@caindex f77_dummy_main
8005@caindex fc_dummy_main
8006With many compilers, the Fortran libraries detected by
8007@code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8008their own @code{main} entry function that initializes things like
8009Fortran I/O, and which then calls a user-provided entry function named
8010(say) @code{MAIN__} to run the user's program.  The
8011@code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8012@code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8013this interaction.
8014
8015When using Fortran for purely numerical functions (no I/O, etc.)@: often
8016one prefers to provide one's own @code{main} and skip the Fortran
8017library initializations.  In this case, however, one may still need to
8018provide a dummy @code{MAIN__} routine in order to prevent linking errors
8019on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8020detects whether any such routine is @emph{required} for linking, and
8021what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8022@code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8023was found, and @code{none} when no such dummy main is needed.
8024
8025By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8026@code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8027@emph{if} it is required.  @var{action-if-not-found} defaults to
8028exiting with an error.
8029
8030In order to link with Fortran routines, the user's C/C++ program should
8031then include the following code to define the dummy main if it is
8032needed:
8033
8034@example
8035@c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8036#ifdef F77_DUMMY_MAIN
8037#  ifdef __cplusplus
8038     extern "C"
8039#  endif
8040   int F77_DUMMY_MAIN () @{ return 1; @}
8041#endif
8042@end example
8043
8044(Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8045
8046Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8047or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8048explicitly unless one wants to change the default actions.
8049
8050The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8051@code{ac_cv_fc_dummy_main} variable, respectively.
8052@end defmac
8053
8054@defmac AC_F77_MAIN
8055@defmacx AC_FC_MAIN
8056@acindex{F77_MAIN}
8057@cvindex F77_MAIN
8058@acindex{FC_MAIN}
8059@cvindex FC_MAIN
8060@caindex f77_main
8061@caindex fc_main
8062As discussed above, many Fortran libraries allow you to provide an entry
8063point called (say) @code{MAIN__} instead of the usual @code{main}, which
8064is then called by a @code{main} function in the Fortran libraries that
8065initializes things like Fortran I/O@.  The
8066@code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8067@emph{possible} to utilize such an alternate main function, and defines
8068@code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8069alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8070simply defined to @code{main}.)
8071
8072Thus, when calling Fortran routines from C that perform things like I/O,
8073one should use this macro and declare the "main" function like so:
8074
8075@example
8076@c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8077#ifdef __cplusplus
8078  extern "C"
8079#endif
8080int F77_MAIN (int argc, char *argv[]);
8081@end example
8082
8083(Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8084
8085The result of this macro is cached in the @code{ac_cv_f77_main} or
8086@code{ac_cv_fc_main} variable, respectively.
8087@end defmac
8088
8089@defmac AC_F77_WRAPPERS
8090@defmacx AC_FC_WRAPPERS
8091@acindex{F77_WRAPPERS}
8092@cvindex F77_FUNC
8093@cvindex F77_FUNC_
8094@acindex{FC_WRAPPERS}
8095@cvindex FC_FUNC
8096@cvindex FC_FUNC_
8097@caindex f77_mangling
8098@caindex fc_mangling
8099Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8100@code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8101mangle the names of C/C++ identifiers, and identifiers with underscores,
8102respectively, so that they match the name-mangling scheme used by the
8103Fortran compiler.
8104
8105Fortran is case-insensitive, and in order to achieve this the Fortran
8106compiler converts all identifiers into a canonical case and format.  To
8107call a Fortran subroutine from C or to write a C function that is
8108callable from Fortran, the C program must explicitly use identifiers in
8109the format expected by the Fortran compiler.  In order to do this, one
8110simply wraps all C identifiers in one of the macros provided by
8111@code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8112you have the following Fortran 77 subroutine:
8113
8114@example
8115@c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8116      subroutine foobar (x, y)
8117      double precision x, y
8118      y = 3.14159 * x
8119      return
8120      end
8121@end example
8122
8123You would then declare its prototype in C or C++ as:
8124
8125@example
8126@c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8127#define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8128#ifdef __cplusplus
8129extern "C"  /* prevent C++ name mangling */
8130#endif
8131void FOOBAR_F77 (double *x, double *y);
8132@end example
8133
8134Note that we pass both the lowercase and uppercase versions of the
8135function name to @code{F77_FUNC} so that it can select the right one.
8136Note also that all parameters to Fortran 77 routines are passed as
8137pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8138Automake}).
8139
8140(Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8141
8142Although Autoconf tries to be intelligent about detecting the
8143name-mangling scheme of the Fortran compiler, there may be Fortran
8144compilers that it doesn't support yet.  In this case, the above code
8145generates a compile-time error, but some other behavior
8146(e.g., disabling Fortran-related features) can be induced by checking
8147whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8148
8149Now, to call that routine from a C program, we would do something like:
8150
8151@example
8152@c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8153@{
8154    double x = 2.7183, y;
8155    FOOBAR_F77 (&x, &y);
8156@}
8157@end example
8158
8159If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8160you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8161@code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8162because some Fortran compilers mangle names differently if they contain
8163an underscore.
8164
8165The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8166@code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8167the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8168@end defmac
8169
8170@defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8171@defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8172@acindex{F77_FUNC}
8173@acindex{FC_FUNC}
8174Given an identifier @var{name}, set the shell variable @var{shellvar} to
8175hold the mangled version @var{name} according to the rules of the
8176Fortran linker (see also @code{AC_F77_WRAPPERS} or
8177@code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8178supplied, the shell variable is simply @var{name}.  The purpose of
8179this macro is to give the caller a way to access the name-mangling
8180information other than through the C preprocessor as above, for example,
8181to call Fortran routines from some language other than C/C++.
8182@end defmac
8183
8184@defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8185  @dvar{action-if-failure, AC_MSG_FAILURE})
8186@defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8187  @dvar{action-if-failure, AC_MSG_FAILURE})
8188@acindex{FC_SRCEXT}
8189@acindex{FC_PP_SRCEXT}
8190@caindex fc_srcext_@var{ext}
8191@caindex fc_pp_srcext_@var{ext}
8192By default, the @code{FC} macros perform their tests using a @file{.f}
8193extension for source-code files.  Some compilers, however, only enable
8194newer language features for appropriately named files, e.g., Fortran 90
8195features only for @file{.f90} files, or preprocessing only with
8196@file{.F} files or maybe other upper-case extensions.  On the other
8197hand, some other compilers expect all source files to end in @file{.f}
8198and require special flags to support other file name extensions.  The
8199@code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8200issues.
8201
8202The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8203accept files ending with the extension @file{.@var{ext}} (i.e.,
8204@var{ext} does @emph{not} contain the dot).  If any special compiler
8205flags are needed for this, it stores them in the output variable
8206@code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8207for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8208@code{AC_FC_PP_SRCEXT} is called another time).
8209
8210For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8211@file{.f90} extension in future tests, and it would set the
8212@code{FCFLAGS_f90} output variable with any extra flags that are needed
8213to compile such files.
8214
8215Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8216compiler to preprocess and compile files with the extension
8217@file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8218preprocessing are provided, the former is preferred, as the latter may
8219treat continuation lines, @code{//} tokens, and white space differently
8220from what some Fortran dialects expect.  Conversely, if you do not want
8221files to be preprocessed, use only lower-case characters in the file
8222name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8223are stored in the @code{FCFLAGS_@var{ext}} variable.
8224
8225The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8226into @code{FCFLAGS}, for two reasons based on the limitations of some
8227compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8228time, so files with different extensions must be compiled separately.
8229Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8230the source-code file name when compiling.  So, continuing the example
8231above, you might compile a @file{foo.f90} file in your makefile with the
8232command:
8233
8234@example
8235foo.o: foo.f90
8236       $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8237@end example
8238
8239If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8240files with the @var{ext} extension, it calls @var{action-if-success}
8241(defaults to nothing).  If it fails, and cannot find a way to make the
8242@code{FC} compiler accept such files, it calls @var{action-if-failure}
8243(defaults to exiting with an error message).
8244
8245The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8246results in @code{ac_cv_fc_srcext_@var{ext}} and
8247@code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8248@end defmac
8249
8250@defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @dvar{action-if-failure, @
8251  AC_MSG_FAILURE})
8252@acindex{FC_PP_DEFINE}
8253@caindex fc_pp_define
8254
8255Find a flag to specify defines for preprocessed Fortran.  Not all
8256Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8257the result and call @var{action-if-success} (defaults to nothing) if
8258successful, and @var{action-if-failure} (defaults to failing with an
8259error message) if not.
8260
8261This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8262preprocess a @file{conftest.F} file, but restores a previously used
8263Fortran source file extension afterwards again.
8264
8265The result of this test is cached in the @code{ac_cv_fc_pp_define}
8266variable.
8267@end defmac
8268
8269@defmac AC_FC_FREEFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8270  AC_MSG_FAILURE})
8271@acindex{FC_FREEFORM}
8272@caindex fc_freeform
8273
8274Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8275source code (as opposed to the older fixed-format style from Fortran
827677).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8277
8278This macro is most important if you are using the default @file{.f}
8279extension, since many compilers interpret this extension as indicating
8280fixed-format source unless an additional flag is supplied.  If you
8281specify a different extension with @code{AC_FC_SRCEXT}, such as
8282@file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8283modifying @code{FCFLAGS}.  For extensions which the compiler does not
8284know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8285the compiler assume Fortran 77 by default, however.
8286
8287If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8288calls @var{action-if-success} (defaults to nothing).  If it fails, it
8289calls @var{action-if-failure} (defaults to exiting with an error
8290message).
8291
8292The result of this test, or @samp{none} or @samp{unknown}, is cached in
8293the @code{ac_cv_fc_freeform} variable.
8294@end defmac
8295
8296@defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8297  AC_MSG_FAILURE})
8298@acindex{FC_FIXEDFORM}
8299@caindex fc_fixedform
8300
8301Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8302fixed-format source code (as opposed to free-format style).  If
8303necessary, it may add some additional flags to @code{FCFLAGS}.
8304
8305This macro is needed for some compilers alias names like @command{xlf95}
8306which assume free-form source code by default, and in case you want to
8307use fixed-form source with an extension like @file{.f90} which many
8308compilers interpret as free-form by default.  If you specify a different
8309extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8310@code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8311@code{FCFLAGS}.
8312
8313If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8314calls @var{action-if-success} (defaults to nothing).  If it fails, it
8315calls @var{action-if-failure} (defaults to exiting with an error
8316message).
8317
8318The result of this test, or @samp{none} or @samp{unknown}, is cached in
8319the @code{ac_cv_fc_fixedform} variable.
8320@end defmac
8321
8322@defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8323  @dvar{action-if-failure, AC_MSG_FAILURE})
8324@acindex{FC_LINE_LENGTH}
8325@caindex fc_line_length
8326
8327Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8328code lines.  The @var{length} argument may be given as 80, 132, or
8329unlimited, and defaults to 132.  Note that line lengths above 254
8330columns are not portable, and some compilers do not accept more than 132
8331columns at least for fixed format source.  If necessary, it may add some
8332additional flags to @code{FCFLAGS}.
8333
8334If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8335calls @var{action-if-success} (defaults to nothing).  If it fails, it
8336calls @var{action-if-failure} (defaults to exiting with an error
8337message).
8338
8339The result of this test, or @samp{none} or @samp{unknown}, is cached in
8340the @code{ac_cv_fc_line_length} variable.
8341@end defmac
8342
8343@defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8344  @dvar{action-if-failure, AC_MSG_FAILURE})
8345@acindex{FC_CHECK_BOUNDS}
8346@caindex fc_check_bounds
8347
8348The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8349in the Fortran compiler.  If successful, the @var{action-if-success}
8350is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8351@var{action-if-failure} is called, which defaults to failing with an error
8352message.  The macro currently requires Fortran 90 or a newer dialect.
8353
8354The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8355variable.
8356@end defmac
8357
8358@defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8359  @dvar{action-if-failure, AC_MSG_FAILURE})
8360@defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8361  @dvar{action-if-failure, AC_MSG_FAILURE})
8362@acindex{F77_IMPLICIT_NONE}
8363@acindex{FC_IMPLICIT_NONE}
8364@caindex f77_implicit_none
8365@caindex fc_implicit_none
8366
8367Try to disallow implicit declarations in the Fortran compiler.  If
8368successful, @var{action-if-success} is called and any needed flags
8369are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8370@var{action-if-failure} is called, which defaults to failing with an error
8371message.
8372
8373The result of these macros are cached in the
8374@code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8375variables, respectively.
8376@end defmac
8377
8378@defmac AC_FC_MODULE_EXTENSION
8379@acindex{FC_MODULE_EXTENSION}
8380@caindex fc_module_ext
8381@ovindex FC_MODEXT
8382
8383Find the Fortran 90 module file name extension.  Most Fortran 90
8384compilers store module information in files separate from the object
8385files.  The module files are usually named after the name of the module
8386rather than the source file name, with characters possibly turned to
8387upper case, plus an extension, often @file{.mod}.
8388
8389Not all compilers use module files at all, or by default.  The Cray
8390Fortran compiler requires @option{-e m} in order to store and search
8391module information in @file{.mod} files rather than in object files.
8392Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8393indicate how module information is stored.
8394
8395The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8396without the leading dot, and stores that in the @code{FC_MODEXT}
8397variable.  If the compiler does not produce module files, or the
8398extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8399the result of this macro may be used in cleanup @command{make} rules as
8400follows:
8401
8402@example
8403clean-modules:
8404        -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8405@end example
8406
8407The extension, or @samp{unknown}, is cached in the
8408@code{ac_cv_fc_module_ext} variable.
8409@end defmac
8410
8411@defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8412  @dvar{action-if-failure, AC_MSG_FAILURE})
8413@acindex{FC_MODULE_FLAG}
8414@caindex fc_module_flag
8415@ovindex FC_MODINC
8416@ovindex ac_empty
8417
8418Find the compiler flag to include Fortran 90 module information from
8419another directory, and store that in the @code{FC_MODINC} variable.
8420Call @var{action-if-success} (defaults to nothing) if successful, and
8421set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8422to exiting with an error message) if not.
8423
8424Most Fortran 90 compilers provide a way to specify module directories.
8425Some have separate flags for the directory to write module files to,
8426and directories to search them in, whereas others only allow writing to
8427the current directory or to the first directory specified in the include
8428path.  Further, with some compilers, the module search path and the
8429preprocessor search path can only be modified with the same flag.  Thus,
8430for portability, write module files to the current directory only and
8431list that as first directory in the search path.
8432
8433There may be no whitespace between @code{FC_MODINC} and the following
8434directory name, but @code{FC_MODINC} may contain trailing white space.
8435For example, if you use Automake and would like to search @file{../lib}
8436for module files, you can use the following:
8437
8438@example
8439AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8440@end example
8441
8442Inside @command{configure} tests, you can use:
8443
8444@example
8445if test -n "$FC_MODINC"; then
8446  FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8447fi
8448@end example
8449
8450The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8451The substituted value of @code{FC_MODINC} may refer to the
8452@code{ac_empty} dummy placeholder empty variable, to avoid losing
8453the significant trailing whitespace in a @file{Makefile}.
8454@end defmac
8455
8456@defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8457  @dvar{action-if-failure, AC_MSG_FAILURE})
8458@acindex{FC_MODULE_OUTPUT_FLAG}
8459@caindex fc_module_output_flag
8460@ovindex FC_MODOUT
8461
8462Find the compiler flag to write Fortran 90 module information to
8463another directory, and store that in the @code{FC_MODOUT} variable.
8464Call @var{action-if-success} (defaults to nothing) if successful, and
8465set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8466to exiting with an error message) if not.
8467
8468Not all Fortran 90 compilers write module files, and of those that do,
8469not all allow writing to a directory other than the current one, nor
8470do all have separate flags for writing and reading; see the description
8471of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8472another directory, for maximum portability use @code{FC_MODOUT} before
8473any @code{FC_MODINC} and include both the current directory and the one
8474you write to in the search path:
8475
8476@example
8477AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8478@end example
8479
8480The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8481The substituted value of @code{FC_MODOUT} may refer to the
8482@code{ac_empty} dummy placeholder empty variable, to avoid losing
8483the significant trailing whitespace in a @file{Makefile}.
8484@end defmac
8485
8486
8487@node Go Compiler
8488@subsection Go Compiler Characteristics
8489@cindex Go
8490
8491Autoconf provides basic support for the Go programming language when
8492using the @code{gccgo} compiler (there is currently no support for the
8493@code{6g} and @code{8g} compilers).
8494
8495@defmac AC_PROG_GO (@ovar{compiler-search-list})
8496Find the Go compiler to use.  Check whether the environment variable
8497@code{GOC} is set; if so, then set output variable @code{GOC} to its
8498value.
8499
8500Otherwise, if the macro is invoked without an argument, then search for
8501a Go compiler named @code{gccgo}.  If it is not found, then as a last
8502resort set @code{GOC} to @code{gccgo}.
8503
8504This macro may be invoked with an optional first argument which, if
8505specified, must be a blank-separated list of Go compilers to search for.
8506
8507If output variable @code{GOFLAGS} was not already set, set it to
8508@option{-g -O2}.  If your package does not like this default,
8509@code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8510@end defmac
8511
8512
8513@node System Services
8514@section System Services
8515
8516The following macros check for operating system services or capabilities.
8517
8518@anchor{AC_PATH_X}
8519@defmac AC_PATH_X
8520@acindex{PATH_X}
8521@evindex XMKMF
8522@cindex X Window System
8523Try to locate the X Window System include files and libraries.  If the
8524user gave the command line options @option{--x-includes=@var{dir}} and
8525@option{--x-libraries=@var{dir}}, use those directories.
8526
8527If either or both were not given, get the missing values by running
8528@code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8529environment variable) on a trivial @file{Imakefile} and examining the
8530makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8531disables this method.
8532
8533If this method fails to find the X Window System, @command{configure}
8534looks for the files in several directories where they often reside.
8535If either method is successful, set the shell variables
8536@code{x_includes} and @code{x_libraries} to their locations, unless they
8537are in directories the compiler searches by default.
8538
8539If both methods fail, or the user gave the command line option
8540@option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8541otherwise set it to the empty string.
8542@end defmac
8543
8544@anchor{AC_PATH_XTRA}
8545@defmac AC_PATH_XTRA
8546@acindex{PATH_XTRA}
8547@ovindex X_CFLAGS
8548@ovindex X_LIBS
8549@ovindex X_EXTRA_LIBS
8550@ovindex X_PRE_LIBS
8551@cvindex X_DISPLAY_MISSING
8552An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8553that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8554to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8555available.
8556
8557This macro also checks for special libraries that some systems need in
8558order to compile X programs.  It adds any that the system needs to
8559output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8560libraries that need to be linked with before @option{-lX11}, and adds
8561any found to the output variable @code{X_PRE_LIBS}.
8562
8563@c This is an incomplete kludge.  Make a real way to do it.
8564@c If you need to check for other X functions or libraries yourself, then
8565@c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8566@c @code{LIBS} temporarily, like this: (FIXME - add example)
8567@end defmac
8568
8569@anchor{AC_SYS_INTERPRETER}
8570@defmac AC_SYS_INTERPRETER
8571@acindex{SYS_INTERPRETER}
8572Check whether the system supports starting scripts with a line of the
8573form @samp{#!/bin/sh} to select the interpreter to use for the script.
8574After running this macro, shell code in @file{configure.ac} can check
8575the shell variable @code{interpval}; it is set to @samp{yes}
8576if the system supports @samp{#!}, @samp{no} if not.
8577@end defmac
8578
8579@defmac AC_SYS_LARGEFILE
8580@acindex{SYS_LARGEFILE}
8581@cvindex _FILE_OFFSET_BITS
8582@cvindex _LARGE_FILES
8583@ovindex CC
8584@cindex Large file support
8585@cindex LFS
8586Arrange for 64-bit file offsets, known as
8587@uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8588large-file support}.  On some hosts, one must use special compiler
8589options to build programs that can access large files.  Append any such
8590options to the output variable @code{CC}.  Define
8591@code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8592
8593Large-file support can be disabled by configuring with the
8594@option{--disable-largefile} option.
8595
8596If you use this macro, check that your program works even when
8597@code{off_t} is wider than @code{long int}, since this is common when
8598large-file support is enabled.  For example, it is not correct to print
8599an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8600(long int) X)}.
8601
8602The LFS introduced the @code{fseeko} and @code{ftello} functions to
8603replace their C counterparts @code{fseek} and @code{ftell} that do not
8604use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8605prototypes available when using them and large-file support is
8606enabled.
8607@end defmac
8608
8609@anchor{AC_SYS_LONG_FILE_NAMES}
8610@defmac AC_SYS_LONG_FILE_NAMES
8611@acindex{SYS_LONG_FILE_NAMES}
8612@cvindex HAVE_LONG_FILE_NAMES
8613If the system supports file names longer than 14 characters, define
8614@code{HAVE_LONG_FILE_NAMES}.
8615@end defmac
8616
8617@defmac AC_SYS_POSIX_TERMIOS
8618@acindex{SYS_POSIX_TERMIOS}
8619@cindex Posix termios headers
8620@cindex termios Posix headers
8621@caindex sys_posix_termios
8622Check to see if the Posix termios headers and functions are available on the
8623system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8624@samp{yes}.  If not, set the variable to @samp{no}.
8625@end defmac
8626
8627@node Posix Variants
8628@section Posix Variants
8629
8630The following macro makes it possible to use features of Posix that are
8631extensions to C, as well as platform extensions not defined by Posix.
8632
8633@anchor{AC_USE_SYSTEM_EXTENSIONS}
8634@defmac AC_USE_SYSTEM_EXTENSIONS
8635@acindex{USE_SYSTEM_EXTENSIONS}
8636@cvindex _ALL_SOURCE
8637@cvindex _GNU_SOURCE
8638@cvindex _MINIX
8639@cvindex _POSIX_1_SOURCE
8640@cvindex _POSIX_PTHREAD_SEMANTICS
8641@cvindex _POSIX_SOURCE
8642@cvindex _TANDEM_SOURCE
8643@cvindex __EXTENSIONS__
8644This macro was introduced in Autoconf 2.60.  If possible, enable
8645extensions to C or Posix on hosts that normally disable the extensions,
8646typically due to standards-conformance namespace issues.  This should be
8647called before any macros that run the C compiler.  The following
8648preprocessor macros are defined where appropriate:
8649
8650@table @code
8651@item _GNU_SOURCE
8652Enable extensions on GNU/Linux.
8653@item __EXTENSIONS__
8654Enable general extensions on Solaris.
8655@item _POSIX_PTHREAD_SEMANTICS
8656Enable threading extensions on Solaris.
8657@item _TANDEM_SOURCE
8658Enable extensions for the HP NonStop platform.
8659@item _ALL_SOURCE
8660Enable extensions for AIX 3, and for Interix.
8661@item _POSIX_SOURCE
8662Enable Posix functions for Minix.
8663@item _POSIX_1_SOURCE
8664Enable additional Posix functions for Minix.
8665@item _MINIX
8666Identify Minix platform.  This particular preprocessor macro is
8667obsolescent, and may be removed in a future release of Autoconf.
8668@end table
8669@end defmac
8670
8671
8672@node Erlang Libraries
8673@section Erlang Libraries
8674@cindex Erlang, Library, checking
8675
8676The following macros check for an installation of Erlang/OTP, and for the
8677presence of certain Erlang libraries.  All those macros require the
8678configuration of an Erlang interpreter and an Erlang compiler
8679(@pxref{Erlang Compiler and Interpreter}).
8680
8681@defmac AC_ERLANG_SUBST_ERTS_VER
8682@acindex{ERLANG_SUBST_ERTS_VER}
8683@ovindex ERLANG_ERTS_VER
8684Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8685Erlang runtime system (as returned by Erlang's
8686@code{erlang:system_info(version)} function).  The result of this test
8687is cached if caching is enabled when running @command{configure}.  The
8688@code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8689for features of specific ERTS versions, but to be used for substituting
8690the ERTS version in Erlang/OTP release resource files (@code{.rel}
8691files), as shown below.
8692@end defmac
8693
8694@defmac AC_ERLANG_SUBST_ROOT_DIR
8695@acindex{ERLANG_SUBST_ROOT_DIR}
8696@ovindex ERLANG_ROOT_DIR
8697Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8698directory in which Erlang/OTP is installed (as returned by Erlang's
8699@code{code:root_dir/0} function).  The result of this test is cached if
8700caching is enabled when running @command{configure}.
8701@end defmac
8702
8703@defmac AC_ERLANG_SUBST_LIB_DIR
8704@acindex{ERLANG_SUBST_LIB_DIR}
8705@ovindex ERLANG_LIB_DIR
8706Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8707directory of Erlang/OTP (as returned by Erlang's
8708@code{code:lib_dir/0} function), which subdirectories each contain an installed
8709Erlang/OTP library.  The result of this test is cached if caching is enabled
8710when running @command{configure}.
8711@end defmac
8712
8713@defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8714  @ovar{action-if-not-found})
8715@acindex{ERLANG_CHECK_LIB}
8716@ovindex ERLANG_LIB_DIR_@var{library}
8717@ovindex ERLANG_LIB_VER_@var{library}
8718Test whether the Erlang/OTP library @var{library} is installed by
8719calling Erlang's @code{code:lib_dir/1} function.  The result of this
8720test is cached if caching is enabled when running @command{configure}.
8721@var{action-if-found} is a list of shell commands to run if the library
8722is installed; @var{action-if-not-found} is a list of shell commands to
8723run if it is not.  Additionally, if the library is installed, the output
8724variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8725library installation directory, and the output variable
8726@samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8727part of the subdirectory name, if it is in the standard form
8728(@code{@var{library}-@var{version}}).  If the directory name does not
8729have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8730empty string.  If the library is not installed,
8731@samp{ERLANG_LIB_DIR_@var{library}} and
8732@samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8733example, to check if library @code{stdlib} is installed:
8734
8735@example
8736AC_ERLANG_CHECK_LIB([stdlib],
8737  [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8738   echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8739  [AC_MSG_ERROR([stdlib was not found!])])
8740@end example
8741
8742The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8743@code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8744by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8745testing for features of specific versions of libraries or of the Erlang
8746runtime system.  Those variables are intended to be substituted in
8747Erlang release resource files (@code{.rel} files).  For instance, to
8748generate a @file{example.rel} file for an application depending on the
8749@code{stdlib} library, @file{configure.ac} could contain:
8750
8751@example
8752AC_ERLANG_SUBST_ERTS_VER
8753AC_ERLANG_CHECK_LIB([stdlib],
8754  [],
8755  [AC_MSG_ERROR([stdlib was not found!])])
8756AC_CONFIG_FILES([example.rel])
8757@end example
8758
8759@noindent
8760The @file{example.rel.in} file used to generate @file{example.rel}
8761should contain:
8762
8763@example
8764@{release,
8765    @{"@@PACKAGE@@", "@@VERSION@@"@},
8766    @{erts, "@@ERLANG_ERTS_VER@@"@},
8767    [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8768     @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8769@end example
8770@end defmac
8771
8772In addition to the above macros, which test installed Erlang libraries, the
8773following macros determine the paths to the directories into which newly built
8774Erlang libraries are to be installed:
8775
8776@defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8777@acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8778@ovindex ERLANG_INSTALL_LIB_DIR
8779
8780Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8781which every built Erlang library should be installed in a separate
8782subdirectory.
8783If this variable is not set in the environment when @command{configure} runs,
8784its default value is @code{$@{libdir@}/erlang/lib}.
8785@end defmac
8786
8787@defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8788@acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8789@ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8790
8791Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8792directory into which the built Erlang library @var{library} version
8793@var{version} should be installed.  If this variable is not set in the
8794environment when @command{configure} runs, its default value is
8795@samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8796@code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8797@code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8798@end defmac
8799
8800
8801
8802
8803
8804@c ========================================================= Writing Tests
8805
8806@node Writing Tests
8807@chapter Writing Tests
8808
8809If the existing feature tests don't do something you need, you have to
8810write new ones.  These macros are the building blocks.  They provide
8811ways for other macros to check whether various kinds of features are
8812available and report the results.
8813
8814This chapter contains some suggestions and some of the reasons why the
8815existing tests are written the way they are.  You can also learn a lot
8816about how to write Autoconf tests by looking at the existing ones.  If
8817something goes wrong in one or more of the Autoconf tests, this
8818information can help you understand the assumptions behind them, which
8819might help you figure out how to best solve the problem.
8820
8821These macros check the output of the compiler system of the current
8822language (@pxref{Language Choice}).  They do not cache the results of
8823their tests for future use (@pxref{Caching Results}), because they don't
8824know enough about the information they are checking for to generate a
8825cache variable name.  They also do not print any messages, for the same
8826reason.  The checks for particular kinds of features call these macros
8827and do cache their results and print messages about what they're
8828checking for.
8829
8830When you write a feature test that could be applicable to more than one
8831software package, the best thing to do is encapsulate it in a new macro.
8832@xref{Writing Autoconf Macros}, for how to do that.
8833
8834@menu
8835* Language Choice::             Selecting which language to use for testing
8836* Writing Test Programs::       Forging source files for compilers
8837* Running the Preprocessor::    Detecting preprocessor symbols
8838* Running the Compiler::        Detecting language or header features
8839* Running the Linker::          Detecting library features
8840* Runtime::                     Testing for runtime features
8841* Systemology::                 A zoology of operating systems
8842* Multiple Cases::              Tests for several possible values
8843@end menu
8844
8845@node Language Choice
8846@section Language Choice
8847@cindex Language
8848
8849Autoconf-generated @command{configure} scripts check for the C compiler and
8850its features by default.  Packages that use other programming languages
8851(maybe more than one, e.g., C and C++) need to test features of the
8852compilers for the respective languages.  The following macros determine
8853which programming language is used in the subsequent tests in
8854@file{configure.ac}.
8855
8856@anchor{AC_LANG}
8857@defmac AC_LANG (@var{language})
8858@acindex{LANG}
8859Do compilation tests using the compiler, preprocessor, and file
8860extensions for the specified @var{language}.
8861
8862Supported languages are:
8863
8864@table @samp
8865@item C
8866Do compilation tests using @code{CC} and @code{CPP} and use extension
8867@file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8868@code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8869
8870@item C++
8871Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8872extension @file{.C} for test programs.  Use compilation flags:
8873@code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8874@code{CXXFLAGS} with @code{CXX}.
8875
8876@item Fortran 77
8877Do compilation tests using @code{F77} and use extension @file{.f} for
8878test programs.  Use compilation flags: @code{FFLAGS}.
8879
8880@item Fortran
8881Do compilation tests using @code{FC} and use extension @file{.f} (or
8882whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8883compilation flags: @code{FCFLAGS}.
8884
8885@item Erlang
8886@ovindex ERLC
8887@ovindex ERL
8888@ovindex ERLCFLAGS
8889Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8890@file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8891
8892@item Objective C
8893Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8894extension @file{.m} for test programs.  Use compilation flags:
8895@code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8896@code{OBJCFLAGS} with @code{OBJC}.
8897
8898@item Objective C++
8899Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8900extension @file{.mm} for test programs.  Use compilation flags:
8901@code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8902@code{OBJCXXFLAGS} with @code{OBJCXX}.
8903
8904@item Go
8905Do compilation tests using @code{GOC} and use extension @file{.go} for
8906test programs.  Use compilation flags @code{GOFLAGS}.
8907@end table
8908@end defmac
8909
8910@anchor{AC_LANG_PUSH}
8911@defmac AC_LANG_PUSH (@var{language})
8912@acindex{LANG_PUSH}
8913Remember the current language (as set by @code{AC_LANG}) on a stack, and
8914then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8915in macros that need to temporarily switch to a particular language.
8916@end defmac
8917
8918@defmac AC_LANG_POP (@ovar{language})
8919@acindex{LANG_POP}
8920Select the language that is saved on the top of the stack, as set by
8921@code{AC_LANG_PUSH}, and remove it from the stack.
8922
8923If given, @var{language} specifies the language we just @emph{quit}.  It
8924is a good idea to specify it when it's known (which should be the
8925case@dots{}), since Autoconf detects inconsistencies.
8926
8927@example
8928AC_LANG_PUSH([Fortran 77])
8929# Perform some tests on Fortran 77.
8930# @dots{}
8931AC_LANG_POP([Fortran 77])
8932@end example
8933@end defmac
8934
8935@defmac AC_LANG_ASSERT (@var{language})
8936@acindex{LANG_ASSERT}
8937Check statically that the current language is @var{language}.
8938You should use this in your language specific macros
8939to avoid that they be called with an inappropriate language.
8940
8941This macro runs only at @command{autoconf} time, and incurs no cost at
8942@command{configure} time.  Sadly enough and because Autoconf is a two
8943layer language @footnote{Because M4 is not aware of Sh code,
8944especially conditionals, some optimizations that look nice statically
8945may produce incorrect results at runtime.}, the macros
8946@code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8947therefore as much as possible you ought to avoid using them to wrap
8948your code, rather, require from the user to run the macro with a
8949correct current language, and check it with @code{AC_LANG_ASSERT}.
8950And anyway, that may help the user understand she is running a Fortran
8951macro while expecting a result about her Fortran 77 compiler@enddots{}
8952@end defmac
8953
8954
8955@defmac AC_REQUIRE_CPP
8956@acindex{REQUIRE_CPP}
8957Ensure that whichever preprocessor would currently be used for tests has
8958been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8959argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8960depending on which language is current.
8961@end defmac
8962
8963
8964@node Writing Test Programs
8965@section Writing Test Programs
8966
8967Autoconf tests follow a common scheme: feed some program with some
8968input, and most of the time, feed a compiler with some source file.
8969This section is dedicated to these source samples.
8970
8971@menu
8972* Guidelines::                  General rules for writing test programs
8973* Test Functions::              Avoiding pitfalls in test programs
8974* Generating Sources::          Source program boilerplate
8975@end menu
8976
8977@node Guidelines
8978@subsection Guidelines for Test Programs
8979
8980The most important rule to follow when writing testing samples is:
8981
8982@center @emph{Look for realism.}
8983
8984This motto means that testing samples must be written with the same
8985strictness as real programs are written.  In particular, you should
8986avoid ``shortcuts'' and simplifications.
8987
8988Don't just play with the preprocessor if you want to prepare a
8989compilation.  For instance, using @command{cpp} to check whether a header is
8990functional might let your @command{configure} accept a header which
8991causes some @emph{compiler} error.  Do not hesitate to check a header with
8992other headers included before, especially required headers.
8993
8994Make sure the symbols you use are properly defined, i.e., refrain from
8995simply declaring a function yourself instead of including the proper
8996header.
8997
8998Test programs should not write to standard output.  They
8999should exit with status 0 if the test succeeds, and with status 1
9000otherwise, so that success
9001can be distinguished easily from a core dump or other failure;
9002segmentation violations and other failures produce a nonzero exit
9003status.  Unless you arrange for @code{exit} to be declared, test
9004programs should @code{return}, not @code{exit}, from @code{main},
9005because on many systems @code{exit} is not declared by default.
9006
9007Test programs can use @code{#if} or @code{#ifdef} to check the values of
9008preprocessor macros defined by tests that have already run.  For
9009example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9010@file{configure.ac} you can have a test program that includes
9011@file{stdbool.h} conditionally:
9012
9013@example
9014@group
9015#ifdef HAVE_STDBOOL_H
9016# include <stdbool.h>
9017#endif
9018@end group
9019@end example
9020
9021Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9022work with any standard C compiler.  Some developers prefer @code{#if}
9023because it is easier to read, while others prefer @code{#ifdef} because
9024it avoids diagnostics with picky compilers like GCC with the
9025@option{-Wundef} option.
9026
9027If a test program needs to use or create a data file, give it a name
9028that starts with @file{conftest}, such as @file{conftest.data}.  The
9029@command{configure} script cleans up by running @samp{rm -f -r conftest*}
9030after running test programs and if the script is interrupted.
9031
9032@node Test Functions
9033@subsection Test Functions
9034
9035These days it's safe to assume support for function prototypes
9036(introduced in C89).
9037
9038Functions that test programs declare should also be conditionalized for
9039C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9040include any header files containing clashing prototypes.
9041
9042@example
9043#ifdef __cplusplus
9044extern "C"
9045#endif
9046void *valloc (size_t);
9047@end example
9048
9049If a test program calls a function with invalid parameters (just to see
9050whether it exists), organize the program to ensure that it never invokes
9051that function.  You can do this by calling it in another function that is
9052never invoked.  You can't do it by putting it after a call to
9053@code{exit}, because GCC version 2 knows that @code{exit}
9054never returns
9055and optimizes out any code that follows it in the same block.
9056
9057If you include any header files, be sure to call the functions
9058relevant to them with the correct number of arguments, even if they are
9059just 0, to avoid compilation errors due to prototypes.  GCC
9060version 2
9061has internal prototypes for several functions that it automatically
9062inlines; for example, @code{memcpy}.  To avoid errors when checking for
9063them, either pass them the correct number of arguments or redeclare them
9064with a different return type (such as @code{char}).
9065
9066
9067@node Generating Sources
9068@subsection Generating Sources
9069
9070Autoconf provides a set of macros that can be used to generate test
9071source files.  They are written to be language generic, i.e., they
9072actually depend on the current language (@pxref{Language Choice}) to
9073``format'' the output properly.
9074
9075
9076@defmac AC_LANG_CONFTEST (@var{source})
9077@acindex{LANG_CONFTEST}
9078Save the @var{source} text in the current test source file:
9079@file{conftest.@var{extension}} where the @var{extension} depends on the
9080current language.  As of Autoconf 2.63b, the source file also contains
9081the results of all of the @code{AC_DEFINE} performed so far.
9082
9083Note that the @var{source} is evaluated exactly once, like regular
9084Autoconf macro arguments, and therefore (i) you may pass a macro
9085invocation, (ii) if not, be sure to double quote if needed.
9086
9087This macro issues a warning during @command{autoconf} processing if
9088@var{source} does not include an expansion of the macro
9089@code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9090@code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9091
9092This macro is seldom called directly, but is used under the hood by more
9093common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9094@end defmac
9095
9096@defmac AC_LANG_DEFINES_PROVIDED
9097@acindex{LANG_DEFINES_PROVIDED}
9098This macro is called as a witness that the file
9099@file{conftest.@var{extension}} appropriate for the current language is
9100complete, including all previously determined results from
9101@code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9102you have a compelling reason to write a conftest file without using
9103@code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9104@code{AC_LANG_CONFTEST}.
9105@end defmac
9106
9107@defmac AC_LANG_SOURCE (@var{source})
9108@acindex{LANG_SOURCE}
9109Expands into the @var{source}, with the definition of
9110all the @code{AC_DEFINE} performed so far.  This macro includes an
9111expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9112
9113In many cases, you may find it more convenient to use the wrapper
9114@code{AC_LANG_PROGRAM}.
9115@end defmac
9116
9117For instance, executing (observe the double quotation!):
9118
9119@example
9120@c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9121AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9122        [http://www.example.org/])
9123AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9124  [Greetings string.])
9125AC_LANG([C])
9126AC_LANG_CONFTEST(
9127   [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9128gcc -E -dD conftest.c
9129@end example
9130
9131@noindent
9132on a system with @command{gcc} installed, results in:
9133
9134@example
9135@c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9136@dots{}
9137# 1 "conftest.c"
9138
9139#define PACKAGE_NAME "Hello"
9140#define PACKAGE_TARNAME "hello"
9141#define PACKAGE_VERSION "1.0"
9142#define PACKAGE_STRING "Hello 1.0"
9143#define PACKAGE_BUGREPORT "bug-hello@@example.org"
9144#define PACKAGE_URL "http://www.example.org/"
9145#define HELLO_WORLD "Hello, World\n"
9146
9147const char hw[] = "Hello, World\n";
9148@end example
9149
9150When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9151definitions are not automatically translated into constants in the
9152source code by this macro.
9153
9154@defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9155@acindex{LANG_PROGRAM}
9156Expands into a source file which consists of the @var{prologue}, and
9157then @var{body} as body of the main function (e.g., @code{main} in
9158C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9159available.
9160@end defmac
9161
9162For instance:
9163
9164@example
9165@c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9166AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9167        [http://www.example.org/])
9168AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9169  [Greetings string.])
9170AC_LANG_CONFTEST(
9171[AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9172                 [[fputs (hw, stdout);]])])
9173gcc -E -dD conftest.c
9174@end example
9175
9176@noindent
9177on a system with @command{gcc} installed, results in:
9178
9179@example
9180@c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9181@dots{}
9182# 1 "conftest.c"
9183
9184#define PACKAGE_NAME "Hello"
9185#define PACKAGE_TARNAME "hello"
9186#define PACKAGE_VERSION "1.0"
9187#define PACKAGE_STRING "Hello 1.0"
9188#define PACKAGE_BUGREPORT "bug-hello@@example.org"
9189#define PACKAGE_URL "http://www.example.org/"
9190#define HELLO_WORLD "Hello, World\n"
9191
9192const char hw[] = "Hello, World\n";
9193int
9194main ()
9195@{
9196fputs (hw, stdout);
9197  ;
9198  return 0;
9199@}
9200@end example
9201
9202In Erlang tests, the created source file is that of an Erlang module called
9203@code{conftest} (@file{conftest.erl}).  This module defines and exports
9204at least
9205one @code{start/0} function, which is called to perform the test.  The
9206@var{prologue} is optional code that is inserted between the module header and
9207the @code{start/0} function definition.  @var{body} is the body of the
9208@code{start/0} function without the final period (@pxref{Runtime}, about
9209constraints on this function's behavior).
9210
9211For instance:
9212
9213@example
9214AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9215AC_LANG(Erlang)
9216AC_LANG_CONFTEST(
9217[AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9218                 [[io:format("~s~n", [?HELLO_WORLD])]])])
9219cat conftest.erl
9220@end example
9221
9222@noindent
9223results in:
9224
9225@example
9226-module(conftest).
9227-export([start/0]).
9228-define(HELLO_WORLD, "Hello, world!").
9229start() ->
9230io:format("~s~n", [?HELLO_WORLD])
9231.
9232@end example
9233
9234@defmac AC_LANG_CALL (@var{prologue}, @var{function})
9235@acindex{LANG_CALL}
9236Expands into a source file which consists of the @var{prologue}, and
9237then a call to the @var{function} as body of the main function (e.g.,
9238@code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9239of the latter are available.
9240
9241This function will probably be replaced in the future by a version
9242which would enable specifying the arguments.  The use of this macro is
9243not encouraged, as it violates strongly the typing system.
9244
9245This macro cannot be used for Erlang tests.
9246@end defmac
9247
9248@defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9249@acindex{LANG_FUNC_LINK_TRY}
9250Expands into a source file which uses the @var{function} in the body of
9251the main function (e.g., @code{main} in C).  Since it uses
9252@code{AC_LANG_PROGRAM}, the features of the latter are available.
9253
9254As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9255It is considered to be severely broken, and in the future will be
9256removed in favor of actual function calls (with properly typed
9257arguments).
9258
9259This macro cannot be used for Erlang tests.
9260@end defmac
9261
9262@node Running the Preprocessor
9263@section Running the Preprocessor
9264
9265Sometimes one might need to run the preprocessor on some source file.
9266@emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9267your project, not merely run the preprocessor on it; therefore you
9268certainly want to run the compiler, not the preprocessor.  Resist the
9269temptation of following the easiest path.
9270
9271Nevertheless, if you need to run the preprocessor, then use
9272@code{AC_PREPROC_IFELSE}.
9273
9274The macros described in this section cannot be used for tests in Erlang,
9275Fortran, or Go, since those languages require no preprocessor.
9276
9277@anchor{AC_PREPROC_IFELSE}
9278@defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9279  @ovar{action-if-false})
9280@acindex{PREPROC_IFELSE}
9281Run the preprocessor of the current language (@pxref{Language Choice})
9282on the @var{input}, run the shell commands @var{action-if-true} on
9283success, @var{action-if-false} otherwise.  The @var{input} can be made
9284by @code{AC_LANG_PROGRAM} and friends.
9285
9286This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9287@option{-g}, @option{-O}, etc.@: are not valid options to many C
9288preprocessors.
9289
9290It is customary to report unexpected failures with
9291@code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9292the preprocessed output in the file @file{conftest.i}.
9293@end defmac
9294
9295For instance:
9296
9297@example
9298AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9299AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9300  [Greetings string.])
9301AC_PREPROC_IFELSE(
9302   [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9303                    [[fputs (hw, stdout);]])],
9304   [AC_MSG_RESULT([OK])],
9305   [AC_MSG_FAILURE([unexpected preprocessor failure])])
9306@end example
9307
9308@noindent
9309results in:
9310
9311@example
9312checking for gcc... gcc
9313checking for C compiler default output file name... a.out
9314checking whether the C compiler works... yes
9315checking whether we are cross compiling... no
9316checking for suffix of executables...
9317checking for suffix of object files... o
9318checking whether we are using the GNU C compiler... yes
9319checking whether gcc accepts -g... yes
9320checking for gcc option to accept ISO C89... none needed
9321checking how to run the C preprocessor... gcc -E
9322OK
9323@end example
9324
9325@sp 1
9326
9327The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9328role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9329it impossible to use it to elaborate sources.  You are encouraged to
9330get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9331@code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9332to run the @emph{preprocessor} and not the compiler?
9333
9334@anchor{AC_EGREP_HEADER}
9335@defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9336  @var{action-if-found}, @ovar{action-if-not-found})
9337@acindex{EGREP_HEADER}
9338If the output of running the preprocessor on the system header file
9339@var{header-file} matches the extended regular expression
9340@var{pattern}, execute shell commands @var{action-if-found}, otherwise
9341execute @var{action-if-not-found}.
9342@end defmac
9343
9344@anchor{AC_EGREP_CPP}
9345@defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9346  @ovar{action-if-found}, @ovar{action-if-not-found})
9347@acindex{EGREP_CPP}
9348@var{program} is the text of a C or C++ program, on which shell
9349variable, back quote, and backslash substitutions are performed.  If the
9350output of running the preprocessor on @var{program} matches the
9351extended regular expression @var{pattern}, execute shell commands
9352@var{action-if-found}, otherwise execute @var{action-if-not-found}.
9353@end defmac
9354
9355
9356
9357@node Running the Compiler
9358@section Running the Compiler
9359
9360To check for a syntax feature of the current language's (@pxref{Language
9361Choice}) compiler, such as whether it recognizes a certain keyword, or
9362simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9363to compile a small program that uses that feature.
9364
9365@defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9366  @ovar{action-if-false})
9367@acindex{COMPILE_IFELSE}
9368Run the compiler and compilation flags of the current language
9369(@pxref{Language Choice}) on the @var{input}, run the shell commands
9370@var{action-if-true} on success, @var{action-if-false} otherwise.  The
9371@var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9372
9373It is customary to report unexpected failures with
9374@code{AC_MSG_FAILURE}.  This macro does not try to link; use
9375@code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9376Linker}).  If needed, @var{action-if-true} can further access the
9377just-compiled object file @file{conftest.$OBJEXT}.
9378
9379This macro uses @code{AC_REQUIRE} for the compiler associated with the
9380current language, which means that if the compiler has not yet been
9381determined, the compiler determination will be made prior to the body of
9382the outermost @code{AC_DEFUN} macro that triggered this macro to
9383expand (@pxref{Expanded Before Required}).
9384@end defmac
9385
9386@ovindex ERL
9387For tests in Erlang, the @var{input} must be the source code of a module named
9388@code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9389file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9390recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9391to ensure that the Erlang module has the right name.
9392
9393@node Running the Linker
9394@section Running the Linker
9395
9396To check for a library, a function, or a global variable, Autoconf
9397@command{configure} scripts try to compile and link a small program that
9398uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9399@code{ar} on the C library to try to figure out which functions are
9400available.  Trying to link with the function is usually a more reliable
9401approach because it avoids dealing with the variations in the options
9402and output formats of @code{nm} and @code{ar} and in the location of the
9403standard libraries.  It also allows configuring for cross-compilation or
9404checking a function's runtime behavior if needed.  On the other hand,
9405it can be slower than scanning the libraries once, but accuracy is more
9406important than speed.
9407
9408@code{AC_LINK_IFELSE} is used to compile test programs to test for
9409functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9410to check for libraries (@pxref{Libraries}), by adding the library being
9411checked for to @code{LIBS} temporarily and trying to link a small
9412program.
9413
9414@anchor{AC_LINK_IFELSE}
9415@defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9416  @ovar{action-if-false})
9417@acindex{LINK_IFELSE}
9418Run the compiler (and compilation flags) and the linker of the current
9419language (@pxref{Language Choice}) on the @var{input}, run the shell
9420commands @var{action-if-true} on success, @var{action-if-false}
9421otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9422friends.  If needed, @var{action-if-true} can further access the
9423just-linked program file @file{conftest$EXEEXT}.
9424
9425@code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9426current compilation flags.
9427
9428It is customary to report unexpected failures with
9429@code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9430use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9431@end defmac
9432
9433The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9434programs are interpreted and do not require linking.
9435
9436
9437
9438@node Runtime
9439@section Checking Runtime Behavior
9440
9441Sometimes you need to find out how a system performs at runtime, such
9442as whether a given function has a certain capability or bug.  If you
9443can, make such checks when your program runs instead of when it is
9444configured.  You can check for things like the machine's endianness when
9445your program initializes itself.
9446
9447If you really need to test for a runtime behavior while configuring,
9448you can write a test program to determine the result, and compile and
9449run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9450possible, because this prevents people from configuring your package for
9451cross-compiling.
9452
9453@anchor{AC_RUN_IFELSE}
9454@defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9455  @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9456@acindex{RUN_IFELSE}
9457Run the compiler (and compilation flags) and the linker of the current
9458language (@pxref{Language Choice}) on the @var{input}, then execute the
9459resulting program.  If the program returns an exit
9460status of 0 when executed, run shell commands @var{action-if-true}.
9461Otherwise, run shell commands @var{action-if-false}.
9462
9463The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9464@code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9465compilation flags of the current language (@pxref{Language Choice}).
9466Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9467for further testing.
9468
9469In the @var{action-if-false} section, the failing exit status is
9470available in the shell variable @samp{$?}.  This exit status might be
9471that of a failed compilation, or it might be that of a failed program
9472execution.
9473
9474If cross-compilation mode is enabled (this is the case if either the
9475compiler being used does not produce executables that run on the system
9476where @command{configure} is being run, or if the options @code{--build}
9477and @code{--host} were both specified and their values are different),
9478then the test program is
9479not run.  If the optional shell commands @var{action-if-cross-compiling}
9480are given, those commands are run instead; typically these commands
9481provide pessimistic defaults that allow cross-compilation to work even
9482if the guess was wrong.  If the fourth argument is empty or omitted, but
9483cross-compilation is detected, then @command{configure} prints an error
9484message and exits.  If you want your package to be useful in a
9485cross-compilation scenario, you @emph{should} provide a non-empty
9486@var{action-if-cross-compiling} clause, as well as wrap the
9487@code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9488(@pxref{Caching Results}) which allows the user to override the
9489pessimistic default if needed.
9490
9491It is customary to report unexpected failures with
9492@code{AC_MSG_FAILURE}.
9493@end defmac
9494
9495@command{autoconf} prints a warning message when creating
9496@command{configure} each time it encounters a call to
9497@code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9498given.  If you are not concerned about users configuring your package
9499for cross-compilation, you may ignore the warning.  A few of the macros
9500distributed with Autoconf produce this warning message; but if this is a
9501problem for you, please report it as a bug, along with an appropriate
9502pessimistic guess to use instead.
9503
9504To configure for cross-compiling you can also choose a value for those
9505parameters based on the canonical system name (@pxref{Manual
9506Configuration}).  Alternatively, set up a test results cache file with
9507the correct values for the host system (@pxref{Caching Results}).
9508
9509@ovindex cross_compiling
9510To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9511in other macros, including a few of the ones that come with Autoconf,
9512you can test whether the shell variable @code{cross_compiling} is set to
9513@samp{yes}, and then use an alternate method to get the results instead
9514of calling the macros.
9515
9516It is also permissible to temporarily assign to @code{cross_compiling}
9517in order to force tests to behave as though they are in a
9518cross-compilation environment, particularly since this provides a way to
9519test your @var{action-if-cross-compiling} even when you are not using a
9520cross-compiler.
9521
9522@example
9523# We temporarily set cross-compile mode to force AC_COMPUTE_INT
9524# to use the slow link-only method
9525save_cross_compiling=$cross_compiling
9526cross_compiling=yes
9527AC_COMPUTE_INT([@dots{}])
9528cross_compiling=$save_cross_compiling
9529@end example
9530
9531A C or C++ runtime test should be portable.
9532@xref{Portable C and C++}.
9533
9534Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9535function: the given status code is used to determine the success of the test
9536(status is @code{0}) or its failure (status is different than @code{0}), as
9537explained above.  It must be noted that data output through the standard output
9538(e.g., using @code{io:format/2}) may be truncated when halting the VM.
9539Therefore, if a test must output configuration information, it is recommended
9540to create and to output data into the temporary file named @file{conftest.out},
9541using the functions of module @code{file}.  The @code{conftest.out} file is
9542automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9543simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9544macro is:
9545
9546@example
9547AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9548AC_ERLANG_NEED_ERL
9549AC_LANG(Erlang)
9550AC_RUN_IFELSE(
9551  [AC_LANG_PROGRAM([], [dnl
9552    file:write_file("conftest.out", code:lib_dir()),
9553    halt(0)])],
9554  [echo "code:lib_dir() returned: `cat conftest.out`"],
9555  [AC_MSG_FAILURE([test Erlang program execution failed])])
9556@end example
9557
9558
9559@node Systemology
9560@section Systemology
9561@cindex Systemology
9562
9563This section aims at presenting some systems and pointers to
9564documentation.  It may help you addressing particular problems reported
9565by users.
9566
9567@uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9568derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9569operating system}.
9570
9571The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9572contains a table correlating the features of various Posix-conforming
9573systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9574simplified diagram of how many Unix systems were derived from each
9575other.
9576
9577@uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9578provides some variants of traditional implementations of Unix utilities.
9579
9580@table @asis
9581@item Darwin
9582@cindex Darwin
9583Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9584case-preserving, but case insensitive.  This can cause nasty problems,
9585since for instance the installation attempt for a package having an
9586@file{INSTALL} file can result in @samp{make install} report that
9587nothing was to be done!
9588
9589That's all dependent on whether the file system is a UFS (case
9590sensitive) or HFS+ (case preserving).  By default Apple wants you to
9591install the OS on HFS+.  Unfortunately, there are some pieces of
9592software which really need to be built on UFS@.  We may want to rebuild
9593Darwin to have both UFS and HFS+ available (and put the /local/build
9594tree on the UFS).
9595
9596@item QNX 4.25
9597@cindex QNX 4.25
9598@c FIXME: Please, if you feel like writing something more precise,
9599@c it'd be great.  In particular, I can't understand the difference with
9600@c QNX Neutrino.
9601QNX is a realtime operating system running on Intel architecture
9602meant to be scalable from the small embedded systems to the hundred
9603processor super-computer.  It claims to be Posix certified.  More
9604information is available on the
9605@uref{http://@/www.qnx.com/, QNX home page}.
9606
9607@item Tru64
9608@cindex Tru64
9609@uref{http://@/h30097.www3.hp.com/@/docs/,
9610Documentation of several versions of Tru64} is available in different
9611formats.
9612
9613@item Unix version 7
9614@cindex Unix version 7
9615@cindex V7
9616Officially this was called the ``Seventh Edition'' of ``the UNIX
9617time-sharing system'' but we use the more-common name ``Unix version 7''.
9618Documentation is available in the
9619@uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9620Previous versions of Unix are called ``Unix version 6'', etc., but
9621they were not as widely used.
9622@end table
9623
9624
9625@node Multiple Cases
9626@section Multiple Cases
9627
9628Some operations are accomplished in several possible ways, depending on
9629the OS variant.  Checking for them essentially requires a ``case
9630statement''.  Autoconf does not directly provide one; however, it is
9631easy to simulate by using a shell variable to keep track of whether a
9632way to perform the operation has been found yet.
9633
9634Here is an example that uses the shell variable @code{fstype} to keep
9635track of whether the remaining cases need to be checked.  Note that
9636since the value of @code{fstype} is under our control, we don't have to
9637use the longer @samp{test "x$fstype" = xno}.
9638
9639@example
9640@group
9641AC_MSG_CHECKING([how to get file system type])
9642fstype=no
9643# The order of these tests is important.
9644AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9645#include <sys/fstyp.h>]])],
9646                  [AC_DEFINE([FSTYPE_STATVFS], [1],
9647                     [Define if statvfs exists.])
9648                   fstype=SVR4])
9649if test $fstype = no; then
9650  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9651#include <sys/fstyp.h>]])],
9652                  [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9653                     [Define if USG statfs.])
9654                   fstype=SVR3])
9655fi
9656if test $fstype = no; then
9657  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9658#include <sys/vmount.h>]])]),
9659                  [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9660                     [Define if AIX statfs.])
9661                   fstype=AIX])
9662fi
9663# (more cases omitted here)
9664AC_MSG_RESULT([$fstype])
9665@end group
9666@end example
9667
9668@c ====================================================== Results of Tests.
9669
9670@node Results
9671@chapter Results of Tests
9672
9673Once @command{configure} has determined whether a feature exists, what can
9674it do to record that information?  There are four sorts of things it can
9675do: define a C preprocessor symbol, set a variable in the output files,
9676save the result in a cache file for future @command{configure} runs, and
9677print a message letting the user know the result of the test.
9678
9679@menu
9680* Defining Symbols::            Defining C preprocessor symbols
9681* Setting Output Variables::    Replacing variables in output files
9682* Special Chars in Variables::  Characters to beware of in variables
9683* Caching Results::             Speeding up subsequent @command{configure} runs
9684* Printing Messages::           Notifying @command{configure} users
9685@end menu
9686
9687@node Defining Symbols
9688@section Defining C Preprocessor Symbols
9689
9690A common action to take in response to a feature test is to define a C
9691preprocessor symbol indicating the results of the test.  That is done by
9692calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9693
9694By default, @code{AC_OUTPUT} places the symbols defined by these macros
9695into the output variable @code{DEFS}, which contains an option
9696@option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9697Autoconf version 1, there is no variable @code{DEFS} defined while
9698@command{configure} is running.  To check whether Autoconf macros have
9699already defined a certain C preprocessor symbol, test the value of the
9700appropriate cache variable, as in this example:
9701
9702@example
9703AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9704                          [Define if vprintf exists.])])
9705if test "x$ac_cv_func_vprintf" != xyes; then
9706  AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9707                            [Define if _doprnt exists.])])
9708fi
9709@end example
9710
9711If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9712@code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9713correct values into @code{#define} statements in a template file.
9714@xref{Configuration Headers}, for more information about this kind of
9715output.
9716
9717@defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9718@defmacx AC_DEFINE (@var{variable})
9719@cvindex @var{variable}
9720@acindex{DEFINE}
9721Define @var{variable} to @var{value} (verbatim), by defining a C
9722preprocessor macro for @var{variable}.  @var{variable} should be a C
9723identifier, optionally suffixed by a parenthesized argument list to
9724define a C preprocessor macro with arguments.  The macro argument list,
9725if present, should be a comma-separated list of C identifiers, possibly
9726terminated by an ellipsis @samp{...} if C99 syntax is employed.
9727@var{variable} should not contain comments, white space, trigraphs,
9728backslash-newlines, universal character names, or non-ASCII
9729characters.
9730
9731@var{value} may contain backslash-escaped newlines, which will be
9732preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9733via @code{@@DEFS@@} (with no effect on the compilation, since the
9734preprocessor sees only one line in the first place).  @var{value} should
9735not contain raw newlines.  If you are not using
9736@code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9737characters, as @command{make} tends to eat them.  To use a shell
9738variable, use @code{AC_DEFINE_UNQUOTED} instead.
9739
9740@var{description} is only useful if you are using
9741@code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9742the generated @file{config.h.in} as the comment before the macro define.
9743The following example defines the C preprocessor variable
9744@code{EQUATION} to be the string constant @samp{"$a > $b"}:
9745
9746@example
9747AC_DEFINE([EQUATION], ["$a > $b"],
9748  [Equation string.])
9749@end example
9750
9751If neither @var{value} nor @var{description} are given, then
9752@var{value} defaults to 1 instead of to the empty string.  This is for
9753backwards compatibility with older versions of Autoconf, but this usage
9754is obsolescent and may be withdrawn in future versions of Autoconf.
9755
9756If the @var{variable} is a literal string, it is passed to
9757@code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9758
9759If multiple @code{AC_DEFINE} statements are executed for the same
9760@var{variable} name (not counting any parenthesized argument list),
9761the last one wins.
9762@end defmac
9763
9764@defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9765@defmacx AC_DEFINE_UNQUOTED (@var{variable})
9766@acindex{DEFINE_UNQUOTED}
9767@cvindex @var{variable}
9768Like @code{AC_DEFINE}, but three shell expansions are
9769performed---once---on @var{variable} and @var{value}: variable expansion
9770(@samp{$}), command substitution (@samp{`}), and backslash escaping
9771(@samp{\}), as if in an unquoted here-document.  Single and double quote
9772characters in the value have no
9773special meaning.  Use this macro instead of @code{AC_DEFINE} when
9774@var{variable} or @var{value} is a shell variable.  Examples:
9775
9776@example
9777AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9778  [Configuration machine file.])
9779AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9780  [getgroups return type.])
9781AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9782  [Translated header name.])
9783@end example
9784@end defmac
9785
9786Due to a syntactical bizarreness of the Bourne shell, do not use
9787semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9788calls from other macro calls or shell code; that can cause syntax errors
9789in the resulting @command{configure} script.  Use either blanks or
9790newlines.  That is, do this:
9791
9792@example
9793AC_CHECK_HEADER([elf.h],
9794  [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9795@end example
9796
9797@noindent
9798or this:
9799
9800@example
9801AC_CHECK_HEADER([elf.h],
9802  [AC_DEFINE([SVR4], [1], [System V Release 4])
9803   LIBS="-lelf $LIBS"])
9804@end example
9805
9806@noindent
9807instead of this:
9808
9809@example
9810AC_CHECK_HEADER([elf.h],
9811  [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9812@end example
9813
9814@node Setting Output Variables
9815@section Setting Output Variables
9816@cindex Output variables
9817
9818Another way to record the results of tests is to set @dfn{output
9819variables}, which are shell variables whose values are substituted into
9820files that @command{configure} outputs.  The two macros below create new
9821output variables.  @xref{Preset Output Variables}, for a list of output
9822variables that are always available.
9823
9824@defmac AC_SUBST (@var{variable}, @ovar{value})
9825@acindex{SUBST}
9826Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9827substitute the variable @var{variable} into output files (typically one
9828or more makefiles).  This means that @code{AC_OUTPUT}
9829replaces instances of @samp{@@@var{variable}@@} in input files with the
9830value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9831is called.  The value can contain any non-@code{NUL} character, including
9832newline.  If you are using Automake 1.11 or newer, for newlines in values
9833you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9834@command{automake} from adding a line @code{@var{variable} =
9835@@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9836Automake, automake, Other things Automake recognizes}).
9837
9838Variable occurrences should not overlap: e.g., an input file should
9839not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9840are variable names.
9841The substituted value is not rescanned for more output variables;
9842occurrences of @samp{@@@var{variable}@@} in the value are inserted
9843literally into the output file.  (The algorithm uses the special marker
9844@code{|#_!!_#|} internally, so neither the substituted value nor the
9845output file may contain @code{|#_!!_#|}.)
9846
9847If @var{value} is given, in addition assign it to @var{variable}.
9848
9849The string @var{variable} is passed to @code{m4_pattern_allow}
9850(@pxref{Forbidden Patterns}).
9851@end defmac
9852
9853@defmac AC_SUBST_FILE (@var{variable})
9854@acindex{SUBST_FILE}
9855Another way to create an output variable from a shell variable.  Make
9856@code{AC_OUTPUT} insert (without substitutions) the contents of the file
9857named by shell variable @var{variable} into output files.  This means
9858that @code{AC_OUTPUT} replaces instances of
9859@samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9860with the contents of the file that the shell variable @var{variable}
9861names when @code{AC_OUTPUT} is called.  Set the variable to
9862@file{/dev/null} for cases that do not have a file to insert.
9863This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9864line by itself, optionally surrounded by spaces and tabs.  The
9865substitution replaces the whole line, including the spaces, tabs, and
9866the terminating newline.
9867
9868This macro is useful for inserting makefile fragments containing
9869special dependencies or other @command{make} directives for particular host
9870or target types into makefiles.  For example, @file{configure.ac}
9871could contain:
9872
9873@example
9874AC_SUBST_FILE([host_frag])
9875host_frag=$srcdir/conf/sun4.mh
9876@end example
9877
9878@noindent
9879and then a @file{Makefile.in} could contain:
9880
9881@example
9882@@host_frag@@
9883@end example
9884
9885The string @var{variable} is passed to @code{m4_pattern_allow}
9886(@pxref{Forbidden Patterns}).
9887@end defmac
9888
9889@cindex Precious Variable
9890@cindex Variable, Precious
9891Running @command{configure} in varying environments can be extremely
9892dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9893./configure}, then the cache, @file{config.h}, and many other output
9894files depend upon @command{bizarre-cc} being the C compiler.  If
9895for some reason the user runs @command{./configure} again, or if it is
9896run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9897and @pxref{config.status Invocation}), then the configuration can be
9898inconsistent, composed of results depending upon two different
9899compilers.
9900
9901Environment variables that affect this situation, such as @samp{CC}
9902above, are called @dfn{precious variables}, and can be declared as such
9903by @code{AC_ARG_VAR}.
9904
9905@defmac AC_ARG_VAR (@var{variable}, @var{description})
9906@acindex{ARG_VAR}
9907Declare @var{variable} is a precious variable, and include its
9908@var{description} in the variable section of @samp{./configure --help}.
9909
9910Being precious means that
9911@itemize @minus
9912@item
9913@var{variable} is substituted via @code{AC_SUBST}.
9914
9915@item
9916The value of @var{variable} when @command{configure} was launched is
9917saved in the cache, including if it was not specified on the command
9918line but via the environment.  Indeed, while @command{configure} can
9919notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9920it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9921which, unfortunately, is what most users do.
9922
9923We emphasize that it is the @emph{initial} value of @var{variable} which
9924is saved, not that found during the execution of @command{configure}.
9925Indeed, specifying @samp{./configure FOO=foo} and letting
9926@samp{./configure} guess that @code{FOO} is @code{foo} can be two
9927different things.
9928
9929@item
9930@var{variable} is checked for consistency between two
9931@command{configure} runs.  For instance:
9932
9933@example
9934$ @kbd{./configure --silent --config-cache}
9935$ @kbd{CC=cc ./configure --silent --config-cache}
9936configure: error: `CC' was not set in the previous run
9937configure: error: changes in the environment can compromise \
9938the build
9939configure: error: run `make distclean' and/or \
9940`rm config.cache' and start over
9941@end example
9942
9943@noindent
9944and similarly if the variable is unset, or if its content is changed.
9945If the content has white space changes only, then the error is degraded
9946to a warning only, but the old value is reused.
9947
9948@item
9949@var{variable} is kept during automatic reconfiguration
9950(@pxref{config.status Invocation}) as if it had been passed as a command
9951line argument, including when no cache is used:
9952
9953@example
9954$ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9955$ @kbd{./config.status --recheck}
9956running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9957  CC=/usr/bin/cc  --no-create --no-recursion
9958@end example
9959@end itemize
9960@end defmac
9961
9962@node Special Chars in Variables
9963@section Special Characters in Output Variables
9964@cindex Output variables, special characters in
9965
9966Many output variables are intended to be evaluated both by
9967@command{make} and by the shell.  Some characters are expanded
9968differently in these two contexts, so to avoid confusion these
9969variables' values should not contain any of the following characters:
9970
9971@example
9972" # $ & ' ( ) * ; < > ? [ \ ^ ` |
9973@end example
9974
9975Also, these variables' values should neither contain newlines, nor start
9976with @samp{~}, nor contain white space or @samp{:} immediately followed
9977by @samp{~}.  The values can contain nonempty sequences of white space
9978characters like tabs and spaces, but each such sequence might
9979arbitrarily be replaced by a single space during substitution.
9980
9981These restrictions apply both to the values that @command{configure}
9982computes, and to the values set directly by the user.  For example, the
9983following invocations of @command{configure} are problematic, since they
9984attempt to use special characters within @code{CPPFLAGS} and white space
9985within @code{$(srcdir)}:
9986
9987@example
9988CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9989
9990'../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9991@end example
9992
9993@node Caching Results
9994@section Caching Results
9995@cindex Cache
9996
9997To avoid checking for the same features repeatedly in various
9998@command{configure} scripts (or in repeated runs of one script),
9999@command{configure} can optionally save the results of many checks in a
10000@dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10001runs with caching enabled and finds a cache file, it reads the results
10002of previous runs from the cache and avoids rerunning those checks.  As a
10003result, @command{configure} can then run much faster than if it had to
10004perform all of the checks every time.
10005
10006@defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10007@acindex{CACHE_VAL}
10008Ensure that the results of the check identified by @var{cache-id} are
10009available.  If the results of the check were in the cache file that was
10010read, and @command{configure} was not given the @option{--quiet} or
10011@option{--silent} option, print a message saying that the result was
10012cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10013the shell commands are run to determine the value, the value is
10014saved in the cache file just before @command{configure} creates its output
10015files.  @xref{Cache Variable Names}, for how to choose the name of the
10016@var{cache-id} variable.
10017
10018The @var{commands-to-set-it} @emph{must have no side effects} except for
10019setting the variable @var{cache-id}, see below.
10020@end defmac
10021
10022@defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10023  @var{commands-to-set-it})
10024@acindex{CACHE_CHECK}
10025A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10026messages.  This macro provides a convenient shorthand for the most
10027common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10028@var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10029@var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10030
10031The @var{commands-to-set-it} @emph{must have no side effects} except for
10032setting the variable @var{cache-id}, see below.
10033@end defmac
10034
10035It is common to find buggy macros using @code{AC_CACHE_VAL} or
10036@code{AC_CACHE_CHECK}, because people are tempted to call
10037@code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10038@emph{follows} the call to @code{AC_CACHE_VAL} should call
10039@code{AC_DEFINE}, by examining the value of the cache variable.  For
10040instance, the following macro is broken:
10041
10042@example
10043@c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10044@group
10045AC_DEFUN([AC_SHELL_TRUE],
10046[AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10047                [my_cv_shell_true_works=no
10048                 (true) 2>/dev/null && my_cv_shell_true_works=yes
10049                 if test "x$my_cv_shell_true_works" = xyes; then
10050                   AC_DEFINE([TRUE_WORKS], [1],
10051                             [Define if `true(1)' works properly.])
10052                 fi])
10053])
10054@end group
10055@end example
10056
10057@noindent
10058This fails if the cache is enabled: the second time this macro is run,
10059@code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10060is:
10061
10062@example
10063@c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10064@group
10065AC_DEFUN([AC_SHELL_TRUE],
10066[AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10067                [my_cv_shell_true_works=no
10068                 (true) 2>/dev/null && my_cv_shell_true_works=yes])
10069 if test "x$my_cv_shell_true_works" = xyes; then
10070   AC_DEFINE([TRUE_WORKS], [1],
10071             [Define if `true(1)' works properly.])
10072 fi
10073])
10074@end group
10075@end example
10076
10077Also, @var{commands-to-set-it} should not print any messages, for
10078example with @code{AC_MSG_CHECKING}; do that before calling
10079@code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10080the results of the check are retrieved from the cache or determined by
10081running the shell commands.
10082
10083@menu
10084* Cache Variable Names::        Shell variables used in caches
10085* Cache Files::                 Files @command{configure} uses for caching
10086* Cache Checkpointing::         Loading and saving the cache file
10087@end menu
10088
10089@node Cache Variable Names
10090@subsection Cache Variable Names
10091@cindex Cache variable
10092
10093The names of cache variables should have the following format:
10094
10095@example
10096@var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10097@end example
10098
10099@noindent
10100for example, @samp{ac_cv_header_stat_broken} or
10101@samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10102
10103@table @asis
10104@item @var{package-prefix}
10105An abbreviation for your package or organization; the same prefix you
10106begin local Autoconf macros with, except lowercase by convention.
10107For cache values used by the distributed Autoconf macros, this value is
10108@samp{ac}.
10109
10110@item @code{_cv_}
10111Indicates that this shell variable is a cache value.  This string
10112@emph{must} be present in the variable name, including the leading
10113underscore.
10114
10115@item @var{value-type}
10116A convention for classifying cache values, to produce a rational naming
10117system.  The values used in Autoconf are listed in @ref{Macro Names}.
10118
10119@item @var{specific-value}
10120Which member of the class of cache values this test applies to.
10121For example, which function (@samp{alloca}), program (@samp{gcc}), or
10122output variable (@samp{INSTALL}).
10123
10124@item @var{additional-options}
10125Any particular behavior of the specific member that this test applies to.
10126For example, @samp{broken} or @samp{set}.  This part of the name may
10127be omitted if it does not apply.
10128@end table
10129
10130The values assigned to cache variables may not contain newlines.
10131Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10132names of files or functions; so this is not an important restriction.
10133@ref{Cache Variable Index} for an index of cache variables with
10134documented semantics.
10135
10136
10137@node Cache Files
10138@subsection Cache Files
10139
10140A cache file is a shell script that caches the results of configure
10141tests run on one system so they can be shared between configure scripts
10142and configure runs.  It is not useful on other systems.  If its contents
10143are invalid for some reason, the user may delete or edit it, or override
10144documented cache variables on the @command{configure} command line.
10145
10146By default, @command{configure} uses no cache file,
10147to avoid problems caused by accidental
10148use of stale cache files.
10149
10150To enable caching, @command{configure} accepts @option{--config-cache} (or
10151@option{-C}) to cache results in the file @file{config.cache}.
10152Alternatively, @option{--cache-file=@var{file}} specifies that
10153@var{file} be the cache file.  The cache file is created if it does not
10154exist already.  When @command{configure} calls @command{configure} scripts in
10155subdirectories, it uses the @option{--cache-file} argument so that they
10156share the same cache.  @xref{Subdirectories}, for information on
10157configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10158
10159@file{config.status} only pays attention to the cache file if it is
10160given the @option{--recheck} option, which makes it rerun
10161@command{configure}.
10162
10163It is wrong to try to distribute cache files for particular system types.
10164There is too much room for error in doing that, and too much
10165administrative overhead in maintaining them.  For any features that
10166can't be guessed automatically, use the standard method of the canonical
10167system type and linking files (@pxref{Manual Configuration}).
10168
10169The site initialization script can specify a site-wide cache file to
10170use, instead of the usual per-program cache.  In this case, the cache
10171file gradually accumulates information whenever someone runs a new
10172@command{configure} script.  (Running @command{configure} merges the new cache
10173results with the existing cache file.)  This may cause problems,
10174however, if the system configuration (e.g., the installed libraries or
10175compilers) changes and the stale cache file is not deleted.
10176
10177If @command{configure} is interrupted at the right time when it updates
10178a cache file outside of the build directory where the @command{configure}
10179script is run, it may leave behind a temporary file named after the
10180cache file with digits following it.  You may safely delete such a file.
10181
10182
10183@node Cache Checkpointing
10184@subsection Cache Checkpointing
10185
10186If your configure script, or a macro called from @file{configure.ac}, happens
10187to abort the configure process, it may be useful to checkpoint the cache
10188a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10189reduces the amount of time it takes to rerun the configure script with
10190(hopefully) the error that caused the previous abort corrected.
10191
10192@c FIXME: Do we really want to document this guy?
10193@defmac AC_CACHE_LOAD
10194@acindex{CACHE_LOAD}
10195Loads values from existing cache file, or creates a new cache file if a
10196cache file is not found.  Called automatically from @code{AC_INIT}.
10197@end defmac
10198
10199@defmac AC_CACHE_SAVE
10200@acindex{CACHE_SAVE}
10201Flushes all cached values to the cache file.  Called automatically from
10202@code{AC_OUTPUT}, but it can be quite useful to call
10203@code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10204@end defmac
10205
10206For instance:
10207
10208@example
10209@r{ @dots{} AC_INIT, etc. @dots{}}
10210@group
10211# Checks for programs.
10212AC_PROG_CC
10213AC_PROG_AWK
10214@r{ @dots{} more program checks @dots{}}
10215AC_CACHE_SAVE
10216@end group
10217
10218@group
10219# Checks for libraries.
10220AC_CHECK_LIB([nsl], [gethostbyname])
10221AC_CHECK_LIB([socket], [connect])
10222@r{ @dots{} more lib checks @dots{}}
10223AC_CACHE_SAVE
10224@end group
10225
10226@group
10227# Might abort@dots{}
10228AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10229AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10230@end group
10231@r{ @dots{} AC_OUTPUT, etc. @dots{}}
10232@end example
10233
10234@node Printing Messages
10235@section Printing Messages
10236@cindex Messages, from @command{configure}
10237
10238@command{configure} scripts need to give users running them several kinds
10239of information.  The following macros print messages in ways appropriate
10240for each kind.  The arguments to all of them get enclosed in shell
10241double quotes, so the shell performs variable and back-quote
10242substitution on them.
10243
10244These macros are all wrappers around the @command{echo} shell command.
10245They direct output to the appropriate file descriptor (@pxref{File
10246Descriptor Macros}).
10247@command{configure} scripts should rarely need to run @command{echo} directly
10248to print messages for the user.  Using these macros makes it easy to
10249change how and when each kind of message is printed; such changes need
10250only be made to the macro definitions and all the callers change
10251automatically.
10252
10253To diagnose static issues, i.e., when @command{autoconf} is run, see
10254@ref{Diagnostic Macros}.
10255
10256@defmac AC_MSG_CHECKING (@var{feature-description})
10257@acindex{MSG_CHECKING}
10258Notify the user that @command{configure} is checking for a particular
10259feature.  This macro prints a message that starts with @samp{checking }
10260and ends with @samp{...} and no newline.  It must be followed by a call
10261to @code{AC_MSG_RESULT} to print the result of the check and the
10262newline.  The @var{feature-description} should be something like
10263@samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10264c89}.
10265
10266This macro prints nothing if @command{configure} is run with the
10267@option{--quiet} or @option{--silent} option.
10268@end defmac
10269
10270@anchor{AC_MSG_RESULT}
10271@defmac AC_MSG_RESULT (@var{result-description})
10272@acindex{MSG_RESULT}
10273Notify the user of the results of a check.  @var{result-description} is
10274almost always the value of the cache variable for the check, typically
10275@samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10276to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10277the completion of the message printed by the call to
10278@code{AC_MSG_CHECKING}.
10279
10280This macro prints nothing if @command{configure} is run with the
10281@option{--quiet} or @option{--silent} option.
10282@end defmac
10283
10284@anchor{AC_MSG_NOTICE}
10285@defmac AC_MSG_NOTICE (@var{message})
10286@acindex{MSG_NOTICE}
10287Deliver the @var{message} to the user.  It is useful mainly to print a
10288general description of the overall purpose of a group of feature checks,
10289e.g.,
10290
10291@example
10292AC_MSG_NOTICE([checking if stack overflow is detectable])
10293@end example
10294
10295This macro prints nothing if @command{configure} is run with the
10296@option{--quiet} or @option{--silent} option.
10297@end defmac
10298
10299@anchor{AC_MSG_ERROR}
10300@defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10301@acindex{MSG_ERROR}
10302Notify the user of an error that prevents @command{configure} from
10303completing.  This macro prints an error message to the standard error
10304output and exits @command{configure} with @var{exit-status} (@samp{$?}
10305by default, except that @samp{0} is converted to @samp{1}).
10306@var{error-description} should be something like @samp{invalid value
10307$HOME for \$HOME}.
10308
10309The @var{error-description} should start with a lower-case letter, and
10310``cannot'' is preferred to ``can't''.
10311@end defmac
10312
10313@defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10314@acindex{MSG_FAILURE}
10315This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10316prevents @command{configure} from completing @emph{and} that additional
10317details are provided in @file{config.log}.  This is typically used when
10318abnormal results are found during a compilation.
10319@end defmac
10320
10321@anchor{AC_MSG_WARN}
10322@defmac AC_MSG_WARN (@var{problem-description})
10323@acindex{MSG_WARN}
10324Notify the @command{configure} user of a possible problem.  This macro
10325prints the message to the standard error output; @command{configure}
10326continues running afterward, so macros that call @code{AC_MSG_WARN} should
10327provide a default (back-up) behavior for the situations they warn about.
10328@var{problem-description} should be something like @samp{ln -s seems to
10329make hard links}.
10330@end defmac
10331
10332
10333
10334@c ====================================================== Programming in M4.
10335
10336@node Programming in M4
10337@chapter Programming in M4
10338@cindex M4
10339
10340Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10341convenient macros for pure M4 programming, and @dfn{M4sh}, which
10342provides macros dedicated to shell script generation.
10343
10344As of this version of Autoconf, these two layers still contain
10345experimental macros, whose interface might change in the future.  As a
10346matter of fact, @emph{anything that is not documented must not be used}.
10347
10348@menu
10349* M4 Quotation::                Protecting macros from unwanted expansion
10350* Using autom4te::              The Autoconf executables backbone
10351* Programming in M4sugar::      Convenient pure M4 macros
10352* Debugging via autom4te::      Figuring out what M4 was doing
10353@end menu
10354
10355@node M4 Quotation
10356@section M4 Quotation
10357@cindex M4 quotation
10358@cindex quotation
10359
10360The most common problem with existing macros is an improper quotation.
10361This section, which users of Autoconf can skip, but which macro writers
10362@emph{must} read, first justifies the quotation scheme that was chosen
10363for Autoconf and then ends with a rule of thumb.  Understanding the
10364former helps one to follow the latter.
10365
10366@menu
10367* Active Characters::           Characters that change the behavior of M4
10368* One Macro Call::              Quotation and one macro call
10369* Quoting and Parameters::      M4 vs. shell parameters
10370* Quotation and Nested Macros::  Macros calling macros
10371* Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10372* Quadrigraphs::                Another way to escape special characters
10373* Balancing Parentheses::       Dealing with unbalanced parentheses
10374* Quotation Rule Of Thumb::     One parenthesis, one quote
10375@end menu
10376
10377@node Active Characters
10378@subsection Active Characters
10379
10380To fully understand where proper quotation is important, you first need
10381to know what the special characters are in Autoconf: @samp{#} introduces
10382a comment inside which no macro expansion is performed, @samp{,}
10383separates arguments, @samp{[} and @samp{]} are the quotes
10384themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10385M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10386@samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10387@samp{$} inside a macro definition.
10388
10389In order to understand the delicate case of macro calls, we first have
10390to present some obvious failures.  Below they are ``obvious-ified'',
10391but when you find them in real life, they are usually in disguise.
10392
10393Comments, introduced by a hash and running up to the newline, are opaque
10394tokens to the top level: active characters are turned off, and there is
10395no macro expansion:
10396
10397@example
10398# define([def], ine)
10399@result{}# define([def], ine)
10400@end example
10401
10402Each time there can be a macro expansion, there is a quotation
10403expansion, i.e., one level of quotes is stripped:
10404
10405@example
10406int tab[10];
10407@result{}int tab10;
10408[int tab[10];]
10409@result{}int tab[10];
10410@end example
10411
10412Without this in mind, the reader might try hopelessly to use her macro
10413@code{array}:
10414
10415@example
10416define([array], [int tab[10];])
10417array
10418@result{}int tab10;
10419[array]
10420@result{}array
10421@end example
10422
10423@noindent
10424How can you correctly output the intended results@footnote{Using
10425@code{defn}.}?
10426
10427
10428@node One Macro Call
10429@subsection One Macro Call
10430
10431Let's proceed on the interaction between active characters and macros
10432with this small macro, which just returns its first argument:
10433
10434@example
10435define([car], [$1])
10436@end example
10437
10438@noindent
10439The two pairs of quotes above are not part of the arguments of
10440@code{define}; rather, they are understood by the top level when it
10441tries to find the arguments of @code{define}.  Therefore, assuming
10442@code{car} is not already defined, it is equivalent to write:
10443
10444@example
10445define(car, $1)
10446@end example
10447
10448@noindent
10449But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10450quotes, it is bad practice for Autoconf macros which must both be more
10451robust and also advocate perfect style.
10452
10453At the top level, there are only two possibilities: either you
10454quote or you don't:
10455
10456@example
10457car(foo, bar, baz)
10458@result{}foo
10459[car(foo, bar, baz)]
10460@result{}car(foo, bar, baz)
10461@end example
10462
10463Let's pay attention to the special characters:
10464
10465@example
10466car(#)
10467@error{}EOF in argument list
10468@end example
10469
10470The closing parenthesis is hidden in the comment; with a hypothetical
10471quoting, the top level understood it this way:
10472
10473@example
10474car([#)]
10475@end example
10476
10477@noindent
10478Proper quotation, of course, fixes the problem:
10479
10480@example
10481car([#])
10482@result{}#
10483@end example
10484
10485Here are more examples:
10486
10487@example
10488car(foo, bar)
10489@result{}foo
10490car([foo, bar])
10491@result{}foo, bar
10492car((foo, bar))
10493@result{}(foo, bar)
10494car([(foo], [bar)])
10495@result{}(foo
10496define([a], [b])
10497@result{}
10498car(a)
10499@result{}b
10500car([a])
10501@result{}b
10502car([[a]])
10503@result{}a
10504car([[[a]]])
10505@result{}[a]
10506@end example
10507
10508@node Quoting and Parameters
10509@subsection Quoting and Parameters
10510
10511When M4 encounters @samp{$} within a macro definition, followed
10512immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10513@samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10514expansion.  This happens regardless of how many layers of quotes the
10515parameter expansion is nested within, or even if it occurs in text that
10516will be rescanned as a comment.
10517
10518@example
10519define([none], [$1])
10520@result{}
10521define([one], [[$1]])
10522@result{}
10523define([two], [[[$1]]])
10524@result{}
10525define([comment], [# $1])
10526@result{}
10527define([active], [ACTIVE])
10528@result{}
10529none([active])
10530@result{}ACTIVE
10531one([active])
10532@result{}active
10533two([active])
10534@result{}[active]
10535comment([active])
10536@result{}# active
10537@end example
10538
10539On the other hand, since autoconf generates shell code, you often want
10540to output shell variable expansion, rather than performing M4 parameter
10541expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10542from the next character in the definition of your macro.  If the macro
10543definition occurs in single-quoted text, then insert another level of
10544quoting; if the usage is already inside a double-quoted string, then
10545split it into concatenated strings.
10546
10547@example
10548define([single], [a single-quoted $[]1 definition])
10549@result{}
10550define([double], [[a double-quoted $][1 definition]])
10551@result{}
10552single
10553@result{}a single-quoted $1 definition
10554double
10555@result{}a double-quoted $1 definition
10556@end example
10557
10558Posix states that M4 implementations are free to provide implementation
10559extensions when @samp{$@{} is encountered in a macro definition.
10560Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10561extensions that will be available in the future GNU M4 2.0,
10562but guarantees that all other instances of @samp{$@{} will be output
10563literally.  Therefore, this idiom can also be used to output shell code
10564parameter references:
10565
10566@example
10567define([first], [$@{1@}])first
10568@result{}$@{1@}
10569@end example
10570
10571Posix also states that @samp{$11} should expand to the first parameter
10572concatenated with a literal @samp{1}, although some versions of
10573GNU M4 expand the eleventh parameter instead.  For
10574portability, you should only use single-digit M4 parameter expansion.
10575
10576With this in mind, we can explore the cases where macros invoke
10577macros@enddots{}
10578
10579@node Quotation and Nested Macros
10580@subsection Quotation and Nested Macros
10581
10582The examples below use the following macros:
10583
10584@example
10585define([car], [$1])
10586define([active], [ACT, IVE])
10587define([array], [int tab[10]])
10588@end example
10589
10590Each additional embedded macro call introduces other possible
10591interesting quotations:
10592
10593@example
10594car(active)
10595@result{}ACT
10596car([active])
10597@result{}ACT, IVE
10598car([[active]])
10599@result{}active
10600@end example
10601
10602In the first case, the top level looks for the arguments of @code{car},
10603and finds @samp{active}.  Because M4 evaluates its arguments
10604before applying the macro, @samp{active} is expanded, which results in:
10605
10606@example
10607car(ACT, IVE)
10608@result{}ACT
10609@end example
10610
10611@noindent
10612In the second case, the top level gives @samp{active} as first and only
10613argument of @code{car}, which results in:
10614
10615@example
10616active
10617@result{}ACT, IVE
10618@end example
10619
10620@noindent
10621i.e., the argument is evaluated @emph{after} the macro that invokes it.
10622In the third case, @code{car} receives @samp{[active]}, which results in:
10623
10624@example
10625[active]
10626@result{}active
10627@end example
10628
10629@noindent
10630exactly as we already saw above.
10631
10632The example above, applied to a more realistic example, gives:
10633
10634@example
10635car(int tab[10];)
10636@result{}int tab10;
10637car([int tab[10];])
10638@result{}int tab10;
10639car([[int tab[10];]])
10640@result{}int tab[10];
10641@end example
10642
10643@noindent
10644Huh?  The first case is easily understood, but why is the second wrong,
10645and the third right?  To understand that, you must know that after
10646M4 expands a macro, the resulting text is immediately subjected
10647to macro expansion and quote removal.  This means that the quote removal
10648occurs twice---first before the argument is passed to the @code{car}
10649macro, and second after the @code{car} macro expands to the first
10650argument.
10651
10652As the author of the Autoconf macro @code{car}, you then consider it to
10653be incorrect that your users have to double-quote the arguments of
10654@code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10655quoted car:
10656
10657@example
10658define([qar], [[$1]])
10659@end example
10660
10661@noindent
10662and check that @code{qar} is properly fixed:
10663
10664@example
10665qar([int tab[10];])
10666@result{}int tab[10];
10667@end example
10668
10669@noindent
10670Ahhh!  That's much better.
10671
10672But note what you've done: now that the result of @code{qar} is always
10673a literal string, the only time a user can use nested macros is if she
10674relies on an @emph{unquoted} macro call:
10675
10676@example
10677qar(active)
10678@result{}ACT
10679qar([active])
10680@result{}active
10681@end example
10682
10683@noindent
10684leaving no way for her to reproduce what she used to do with @code{car}:
10685
10686@example
10687car([active])
10688@result{}ACT, IVE
10689@end example
10690
10691@noindent
10692Worse yet: she wants to use a macro that produces a set of @code{cpp}
10693macros:
10694
10695@example
10696define([my_includes], [#include <stdio.h>])
10697car([my_includes])
10698@result{}#include <stdio.h>
10699qar(my_includes)
10700@error{}EOF in argument list
10701@end example
10702
10703This macro, @code{qar}, because it double quotes its arguments, forces
10704its users to leave their macro calls unquoted, which is dangerous.
10705Commas and other active symbols are interpreted by M4 before
10706they are given to the macro, often not in the way the users expect.
10707Also, because @code{qar} behaves differently from the other macros,
10708it's an exception that should be avoided in Autoconf.
10709
10710@node Changequote is Evil
10711@subsection @code{changequote} is Evil
10712@cindex @code{changequote}
10713
10714The temptation is often high to bypass proper quotation, in particular
10715when it's late at night.  Then, many experienced Autoconf hackers
10716finally surrender to the dark side of the force and use the ultimate
10717weapon: @code{changequote}.
10718
10719The M4 builtin @code{changequote} belongs to a set of primitives that
10720allow one to adjust the syntax of the language to adjust it to one's
10721needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10722quotes, but in the context of shell programming (and actually of most
10723programming languages), that's about the worst choice one can make:
10724because of strings and back-quoted expressions in shell code (such as
10725@samp{'this'} and @samp{`that`}), and because of literal characters in usual
10726programming languages (as in @samp{'0'}), there are many unbalanced
10727@samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10728not impossible.  In order to make M4 useful in such a context, its
10729designers have equipped it with @code{changequote}, which makes it
10730possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10731Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10732because they are unlikely characters, but @emph{because they are
10733characters unlikely to be unbalanced}.
10734
10735There are other magic primitives, such as @code{changecom} to specify
10736what syntactic forms are comments (it is common to see
10737@samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10738@code{changeword} and @code{changesyntax} to change other syntactic
10739details (such as the character to denote the @var{n}th argument, @samp{$} by
10740default, the parentheses around arguments, etc.).
10741
10742These primitives are really meant to make M4 more useful for specific
10743domains: they should be considered like command line options:
10744@option{--quotes}, @option{--comments}, @option{--words}, and
10745@option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10746it makes M4 libraries self contained (no need for additional options).
10747
10748There lies the problem@enddots{}
10749
10750@sp 1
10751
10752The problem is that it is then tempting to use them in the middle of an
10753M4 script, as opposed to its initialization.  This, if not carefully
10754thought out, can lead to disastrous effects: @emph{you are changing the
10755language in the middle of the execution}.  Changing and restoring the
10756syntax is often not enough: if you happened to invoke macros in between,
10757these macros are lost, as the current syntax is probably not
10758the one they were implemented with.
10759
10760@c FIXME: I've been looking for a short, real case example, but I
10761@c lost them all :(
10762
10763
10764@node Quadrigraphs
10765@subsection Quadrigraphs
10766@cindex quadrigraphs
10767@cindex @samp{@@S|@@}
10768@cindex @samp{@@&t@@}
10769@c Info cannot handle `:' in index entries.
10770@ifnotinfo
10771@cindex @samp{@@<:@@}
10772@cindex @samp{@@:>@@}
10773@cindex @samp{@@%:@@}
10774@cindex @samp{@@@{:@@}
10775@cindex @samp{@@:@}@@}
10776@end ifnotinfo
10777
10778When writing an Autoconf macro you may occasionally need to generate
10779special characters that are difficult to express with the standard
10780Autoconf quoting rules.  For example, you may need to output the regular
10781expression @samp{[^[]}, which matches any character other than @samp{[}.
10782This expression contains unbalanced brackets so it cannot be put easily
10783into an M4 macro.
10784
10785Additionally, there are a few m4sugar macros (such as @code{m4_split}
10786and @code{m4_expand}) which internally use special markers in addition
10787to the regular quoting characters.  If the arguments to these macros
10788contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10789might behave incorrectly.
10790
10791You can work around these problems by using one of the following
10792@dfn{quadrigraphs}:
10793
10794@table @samp
10795@item @@<:@@
10796@samp{[}
10797@item @@:>@@
10798@samp{]}
10799@item @@S|@@
10800@samp{$}
10801@item @@%:@@
10802@samp{#}
10803@item @@@{:@@
10804@samp{(}
10805@item @@:@}@@
10806@samp{)}
10807@item @@&t@@
10808Expands to nothing.
10809@end table
10810
10811Quadrigraphs are replaced at a late stage of the translation process,
10812after @command{m4} is run, so they do not get in the way of M4 quoting.
10813For example, the string @samp{^@@<:@@}, independently of its quotation,
10814appears as @samp{^[} in the output.
10815
10816The empty quadrigraph can be used:
10817
10818@itemize @minus
10819@item to mark trailing spaces explicitly
10820
10821Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10822
10823@item to produce quadrigraphs and other strings reserved by m4sugar
10824
10825For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10826contrived example:
10827
10828@example
10829m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10830m4_split([a )@}>=- b -=<@{( c])
10831@result{}[a], [], [B], [], [c]
10832m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10833@result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10834@end example
10835
10836@item to escape @emph{occurrences} of forbidden patterns
10837
10838For instance you might want to mention @code{AC_FOO} in a comment, while
10839still being sure that @command{autom4te} still catches unexpanded
10840@samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10841@end itemize
10842
10843The name @samp{@@&t@@} was suggested by Paul Eggert:
10844
10845@quotation
10846I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10847own invention, but the @samp{t} came from the source code of the
10848ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10849and which used @samp{mt} to denote the empty string.  In C, it would
10850have looked like something like:
10851
10852@example
10853char const mt[] = "";
10854@end example
10855
10856@noindent
10857but of course the source code was written in Algol 68.
10858
10859I don't know where he got @samp{mt} from: it could have been his own
10860invention, and I suppose it could have been a common pun around the
10861Cambridge University computer lab at the time.
10862@end quotation
10863
10864
10865@node Balancing Parentheses
10866@subsection Dealing with unbalanced parentheses
10867@cindex balancing parentheses
10868@cindex parentheses, balancing
10869@cindex unbalanced parentheses, managing
10870
10871One of the pitfalls of portable shell programming is that @command{case}
10872statements require unbalanced parentheses (@pxref{case, , Limitations of
10873Shell Builtins}).  With syntax highlighting
10874editors, the presence of unbalanced @samp{)} can interfere with editors
10875that perform syntax highlighting of macro contents based on finding the
10876matching @samp{(}.  Another concern is how much editing must be done
10877when transferring code snippets between shell scripts and macro
10878definitions.  But most importantly, the presence of unbalanced
10879parentheses can introduce expansion bugs.
10880
10881For an example, here is an underquoted attempt to use the macro
10882@code{my_case}, which happens to expand to a portable @command{case}
10883statement:
10884
10885@example
10886AC_DEFUN([my_case],
10887[case $file_name in
10888  *.c) echo "C source code";;
10889esac])
10890AS_IF(:, my_case)
10891@end example
10892
10893@noindent
10894In the above example, the @code{AS_IF} call underquotes its arguments.
10895As a result, the unbalanced @samp{)} generated by the premature
10896expansion of @code{my_case} results in expanding @code{AS_IF} with a
10897truncated parameter, and the expansion is syntactically invalid:
10898
10899@example
10900if :; then
10901  case $file_name in
10902  *.c
10903fi echo "C source code";;
10904esac)
10905@end example
10906
10907If nothing else, this should emphasize the importance of the quoting
10908arguments to macro calls.  On the other hand, there are several
10909variations for defining @code{my_case} to be more robust, even when used
10910without proper quoting, each with some benefits and some drawbacks.
10911
10912@itemize @w{}
10913@item Creative literal shell comment
10914@example
10915AC_DEFUN([my_case],
10916[case $file_name in #(
10917  *.c) echo "C source code";;
10918esac])
10919@end example
10920@noindent
10921This version provides balanced parentheses to several editors, and can
10922be copied and pasted into a terminal as is.  Unfortunately, it is still
10923unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10924that masks the normal properties of @samp{(}.
10925
10926@item Quadrigraph shell comment
10927@example
10928AC_DEFUN([my_case],
10929[case $file_name in @@%:@@(
10930  *.c) echo "C source code";;
10931esac])
10932@end example
10933@noindent
10934This version provides balanced parentheses to even more editors, and can
10935be used as a balanced Autoconf argument.  Unfortunately, it requires
10936some editing before it can be copied and pasted into a terminal, and the
10937use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10938
10939@item Quoting just the parenthesis
10940@example
10941AC_DEFUN([my_case],
10942[case $file_name in
10943  *.c[)] echo "C source code";;
10944esac])
10945@end example
10946@noindent
10947This version quotes the @samp{)}, so that it can be used as a balanced
10948Autoconf argument.  As written, this is not balanced to an editor, but
10949it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10950still requires some edits before it can be copied and pasted into a
10951terminal.
10952
10953@item Double-quoting the entire statement
10954@example
10955AC_DEFUN([my_case],
10956[[case $file_name in #(
10957  *.c) echo "C source code";;
10958esac]])
10959@end example
10960@noindent
10961Since the entire macro is double-quoted, there is no problem with using
10962this as an Autoconf argument; and since the double-quoting is over the
10963entire statement, this code can be easily copied and pasted into a
10964terminal.  However, the double quoting prevents the expansion of any
10965macros inside the case statement, which may cause its own set of
10966problems.
10967
10968@item Using @code{AS_CASE}
10969@example
10970AC_DEFUN([my_case],
10971[AS_CASE([$file_name],
10972  [*.c], [echo "C source code"])])
10973@end example
10974@noindent
10975This version avoids the balancing issue altogether, by relying on
10976@code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10977expansion of @code{AC_REQUIRE} to occur prior to the entire case
10978statement, rather than within a branch of the case statement that might
10979not be taken.  However, the abstraction comes with a penalty that it is
10980no longer a quick copy, paste, and edit to get back to shell code.
10981@end itemize
10982
10983
10984@node Quotation Rule Of Thumb
10985@subsection Quotation Rule Of Thumb
10986
10987To conclude, the quotation rule of thumb is:
10988
10989@center @emph{One pair of quotes per pair of parentheses.}
10990
10991Never over-quote, never under-quote, in particular in the definition of
10992macros.  In the few places where the macros need to use brackets
10993(usually in C program text or regular expressions), properly quote
10994@emph{the arguments}!
10995
10996It is common to read Autoconf programs with snippets like:
10997
10998@example
10999AC_TRY_LINK(
11000changequote(<<, >>)dnl
11001<<#include <time.h>
11002#ifndef tzname /* For SGI.  */
11003extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11004#endif>>,
11005changequote([, ])dnl
11006[atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11007@end example
11008
11009@noindent
11010which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11011double quoting, so you just need:
11012
11013@example
11014AC_TRY_LINK(
11015[#include <time.h>
11016#ifndef tzname /* For SGI.  */
11017extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11018#endif],
11019            [atoi (*tzname);],
11020            [ac_cv_var_tzname=yes],
11021            [ac_cv_var_tzname=no])
11022@end example
11023
11024@noindent
11025The M4-fluent reader might note that these two examples are rigorously
11026equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11027and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11028quotes are not part of the arguments!
11029
11030Simplified, the example above is just doing this:
11031
11032@example
11033changequote(<<, >>)dnl
11034<<[]>>
11035changequote([, ])dnl
11036@end example
11037
11038@noindent
11039instead of simply:
11040
11041@example
11042[[]]
11043@end example
11044
11045With macros that do not double quote their arguments (which is the
11046rule), double-quote the (risky) literals:
11047
11048@example
11049AC_LINK_IFELSE([AC_LANG_PROGRAM(
11050[[#include <time.h>
11051#ifndef tzname /* For SGI.  */
11052extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11053#endif]],
11054                                [atoi (*tzname);])],
11055               [ac_cv_var_tzname=yes],
11056               [ac_cv_var_tzname=no])
11057@end example
11058
11059Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11060should be using @code{AC_LINK_IFELSE} instead.
11061
11062@xref{Quadrigraphs}, for what to do if you run into a hopeless case
11063where quoting does not suffice.
11064
11065When you create a @command{configure} script using newly written macros,
11066examine it carefully to check whether you need to add more quotes in
11067your macros.  If one or more words have disappeared in the M4
11068output, you need more quotes.  When in doubt, quote.
11069
11070However, it's also possible to put on too many layers of quotes.  If
11071this happens, the resulting @command{configure} script may contain
11072unexpanded macros.  The @command{autoconf} program checks for this problem
11073by looking for the string @samp{AC_} in @file{configure}.  However, this
11074heuristic does not work in general: for example, it does not catch
11075overquoting in @code{AC_DEFINE} descriptions.
11076
11077
11078@c ---------------------------------------- Using autom4te
11079
11080@node Using autom4te
11081@section Using @command{autom4te}
11082
11083The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11084to Autoconf per se, heavily rely on M4.  All these different uses
11085revealed common needs factored into a layer over M4:
11086@command{autom4te}@footnote{
11087@c
11088Yet another great name from Lars J. Aas.
11089@c
11090}.
11091
11092@command{autom4te} is a preprocessor that is like @command{m4}.
11093It supports M4 extensions designed for use in tools like Autoconf.
11094
11095@menu
11096* autom4te Invocation::         A GNU M4 wrapper
11097* Customizing autom4te::        Customizing the Autoconf package
11098@end menu
11099
11100@node autom4te Invocation
11101@subsection Invoking @command{autom4te}
11102
11103The command line arguments are modeled after M4's:
11104
11105@example
11106autom4te @var{options} @var{files}
11107@end example
11108
11109@noindent
11110@evindex M4
11111where the @var{files} are directly passed to @command{m4}.  By default,
11112GNU M4 is found during configuration, but the environment
11113variable
11114@env{M4} can be set to tell @command{autom4te} where to look.  In addition
11115to the regular expansion, it handles the replacement of the quadrigraphs
11116(@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11117output.  It supports an extended syntax for the @var{files}:
11118
11119@table @file
11120@item @var{file}.m4f
11121This file is an M4 frozen file.  Note that @emph{all the previous files
11122are ignored}.  See the option @option{--melt} for the rationale.
11123
11124@item @var{file}?
11125If found in the library path, the @var{file} is included for expansion,
11126otherwise it is ignored instead of triggering a failure.
11127@end table
11128
11129@sp 1
11130
11131Of course, it supports the Autoconf common subset of options:
11132
11133@table @option
11134@item --help
11135@itemx -h
11136Print a summary of the command line options and exit.
11137
11138@item --version
11139@itemx -V
11140Print the version number of Autoconf and exit.
11141
11142@item --verbose
11143@itemx -v
11144Report processing steps.
11145
11146@item --debug
11147@itemx -d
11148Don't remove the temporary files and be even more verbose.
11149
11150@item --include=@var{dir}
11151@itemx -I @var{dir}
11152Also look for input files in @var{dir}.  Multiple invocations
11153accumulate.
11154
11155@item --output=@var{file}
11156@itemx -o @var{file}
11157Save output (script or trace) to @var{file}.  The file @option{-} stands
11158for the standard output.
11159@end table
11160
11161@sp 1
11162
11163As an extension of @command{m4}, it includes the following options:
11164
11165@table @option
11166@item --warnings=@var{category}
11167@itemx -W @var{category}
11168@evindex WARNINGS
11169@c FIXME: Point to the M4sugar macros, not Autoconf's.
11170Report the warnings related to @var{category} (which can actually be a
11171comma separated list).  @xref{Reporting Messages}, macro
11172@code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11173values include:
11174
11175@table @samp
11176@item all
11177report all the warnings
11178
11179@item none
11180report none
11181
11182@item error
11183treats warnings as errors
11184
11185@item no-@var{category}
11186disable warnings falling into @var{category}
11187@end table
11188
11189Warnings about @samp{syntax} are enabled by default, and the environment
11190variable @env{WARNINGS}, a comma separated list of categories, is
11191honored.  @samp{autom4te -W @var{category}} actually
11192behaves as if you had run:
11193
11194@example
11195autom4te --warnings=syntax,$WARNINGS,@var{category}
11196@end example
11197
11198@noindent
11199For example, if you want to disable defaults and @env{WARNINGS}
11200of @command{autom4te}, but enable the warnings about obsolete
11201constructs, you would use @option{-W none,obsolete}.
11202
11203@cindex Back trace
11204@cindex Macro invocation stack
11205@command{autom4te} displays a back trace for errors, but not for
11206warnings; if you want them, just pass @option{-W error}.
11207
11208@item --melt
11209@itemx -M
11210Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11211replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11212are executed only when the files are frozen, typically
11213@code{m4_define}.  For instance, running:
11214
11215@example
11216autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11217@end example
11218
11219@noindent
11220is roughly equivalent to running:
11221
11222@example
11223m4 1.m4 2.m4 3.m4 4.m4 input.m4
11224@end example
11225
11226@noindent
11227while
11228
11229@example
11230autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11231@end example
11232
11233@noindent
11234is equivalent to:
11235
11236@example
11237m4 --reload-state=4.m4f input.m4
11238@end example
11239
11240@item --freeze
11241@itemx -F
11242Produce a frozen state file.  @command{autom4te} freezing is stricter
11243than M4's: it must produce no warnings, and no output other than empty
11244lines (a line with white space is @emph{not} empty) and comments
11245(starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11246this option takes no argument:
11247
11248@example
11249autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11250@end example
11251
11252@noindent
11253corresponds to
11254
11255@example
11256m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11257@end example
11258
11259@item --mode=@var{octal-mode}
11260@itemx -m @var{octal-mode}
11261Set the mode of the non-traces output to @var{octal-mode}; by default
11262@samp{0666}.
11263@end table
11264
11265@sp 1
11266
11267@cindex @file{autom4te.cache}
11268As another additional feature over @command{m4}, @command{autom4te}
11269caches its results.  GNU M4 is able to produce a regular
11270output and traces at the same time.  Traces are heavily used in the
11271GNU Build System: @command{autoheader} uses them to build
11272@file{config.h.in}, @command{autoreconf} to determine what
11273GNU Build System components are used, @command{automake} to
11274``parse'' @file{configure.ac} etc.  To avoid recomputation,
11275traces are cached while performing regular expansion,
11276and conversely.  This cache is (actually, the caches are) stored in
11277the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11278at any moment (especially if for some reason @command{autom4te}
11279considers it trashed).
11280
11281@table @option
11282@item --cache=@var{directory}
11283@itemx -C @var{directory}
11284Specify the name of the directory where the result should be cached.
11285Passing an empty value disables caching.  Be sure to pass a relative
11286file name, as for the time being, global caches are not supported.
11287
11288@item --no-cache
11289Don't cache the results.
11290
11291@item --force
11292@itemx -f
11293If a cache is used, consider it obsolete (but update it anyway).
11294@end table
11295
11296@sp 1
11297
11298Because traces are so important to the GNU Build System,
11299@command{autom4te} provides high level tracing features as compared to
11300M4, and helps exploiting the cache:
11301
11302@table @option
11303@item --trace=@var{macro}[:@var{format}]
11304@itemx -t @var{macro}[:@var{format}]
11305Trace the invocations of @var{macro} according to the @var{format}.
11306Multiple @option{--trace} arguments can be used to list several macros.
11307Multiple @option{--trace} arguments for a single macro are not
11308cumulative; instead, you should just make @var{format} as long as
11309needed.
11310
11311The @var{format} is a regular string, with newlines if desired, and
11312several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11313use the following special escapes:
11314
11315@table @samp
11316@item $$
11317@c $$ restore font-lock
11318The character @samp{$}.
11319
11320@item $f
11321The file name from which @var{macro} is called.
11322
11323@item $l
11324The line number from which @var{macro} is called.
11325
11326@item $d
11327The depth of the @var{macro} call.  This is an M4 technical detail that
11328you probably don't want to know about.
11329
11330@item $n
11331The name of the @var{macro}.
11332
11333@item $@var{num}
11334The @var{num}th argument of the call to @var{macro}.
11335
11336@item $@@
11337@itemx $@var{sep}@@
11338@itemx $@{@var{separator}@}@@
11339All the arguments passed to @var{macro}, separated by the character
11340@var{sep} or the string @var{separator} (@samp{,} by default).  Each
11341argument is quoted, i.e., enclosed in a pair of square brackets.
11342
11343@item $*
11344@itemx $@var{sep}*
11345@itemx $@{@var{separator}@}*
11346As above, but the arguments are not quoted.
11347
11348@item $%
11349@itemx $@var{sep}%
11350@itemx $@{@var{separator}@}%
11351As above, but the arguments are not quoted, all new line characters in
11352the arguments are smashed, and the default separator is @samp{:}.
11353
11354The escape @samp{$%} produces single-line trace outputs (unless you put
11355newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11356not.
11357@end table
11358
11359@xref{autoconf Invocation}, for examples of trace uses.
11360
11361@item --preselect=@var{macro}
11362@itemx -p @var{macro}
11363Cache the traces of @var{macro}, but do not enable traces.  This is
11364especially important to save CPU cycles in the future.  For instance,
11365when invoked, @command{autoconf} preselects all the macros that
11366@command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11367trace, so that running @command{m4} is not needed to trace them: the
11368cache suffices.  This results in a huge speed-up.
11369@end table
11370
11371@sp 1
11372
11373@cindex Autom4te Library
11374Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11375libraries}.  They consists in a powerful yet extremely simple feature:
11376sets of combined command line arguments:
11377
11378@table @option
11379@item --language=@var{language}
11380@itemx -l @var{language}
11381Use the @var{language} Autom4te library.  Current languages include:
11382
11383@table @code
11384@item M4sugar
11385create M4sugar output.
11386
11387@item M4sh
11388create M4sh executable shell scripts.
11389
11390@item Autotest
11391create Autotest executable test suites.
11392
11393@item Autoconf-without-aclocal-m4
11394create Autoconf executable configure scripts without
11395reading @file{aclocal.m4}.
11396
11397@item Autoconf
11398create Autoconf executable configure scripts.  This language inherits
11399all the characteristics of @code{Autoconf-without-aclocal-m4} and
11400additionally reads @file{aclocal.m4}.
11401@end table
11402
11403@item --prepend-include=@var{dir}
11404@itemx -B @var{dir}
11405Prepend directory @var{dir} to the search path.  This is used to include
11406the language-specific files before any third-party macros.
11407
11408@end table
11409
11410@cindex @file{autom4te.cfg}
11411As an example, if Autoconf is installed in its default location,
11412@file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11413strictly equivalent to the command:
11414
11415@example
11416autom4te --prepend-include /usr/local/share/autoconf \
11417  m4sugar/m4sugar.m4f --warnings syntax foo.m4
11418@end example
11419
11420@noindent
11421Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11422is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11423foo.m4}, i.e.:
11424
11425@example
11426autom4te --prepend-include /usr/local/share/autoconf \
11427  m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11428@end example
11429
11430@noindent
11431The definition of the languages is stored in @file{autom4te.cfg}.
11432
11433@node Customizing autom4te
11434@subsection Customizing @command{autom4te}
11435
11436One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11437as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11438as found in the directory from which @command{autom4te} is run).  The
11439order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11440then @file{./.autom4te.cfg}, and finally the command line arguments.
11441
11442In these text files, comments are introduced with @code{#}, and empty
11443lines are ignored.  Customization is performed on a per-language basis,
11444wrapped in between a @samp{begin-language: "@var{language}"},
11445@samp{end-language: "@var{language}"} pair.
11446
11447Customizing a language stands for appending options (@pxref{autom4te
11448Invocation}) to the current definition of the language.  Options, and
11449more generally arguments, are introduced by @samp{args:
11450@var{arguments}}.  You may use the traditional shell syntax to quote the
11451@var{arguments}.
11452
11453As an example, to disable Autoconf caches (@file{autom4te.cache})
11454globally, include the following lines in @file{~/.autom4te.cfg}:
11455
11456@verbatim
11457## ------------------ ##
11458## User Preferences.  ##
11459## ------------------ ##
11460
11461begin-language: "Autoconf-without-aclocal-m4"
11462args: --no-cache
11463end-language: "Autoconf-without-aclocal-m4"
11464@end verbatim
11465
11466
11467@node Programming in M4sugar
11468@section Programming in M4sugar
11469
11470@cindex M4sugar
11471M4 by itself provides only a small, but sufficient, set of all-purpose
11472macros.  M4sugar introduces additional generic macros.  Its name was
11473coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11474M4sugar''.
11475
11476M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11477the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11478define your own macros into these namespaces.
11479
11480@menu
11481* Redefined M4 Macros::         M4 builtins changed in M4sugar
11482* Diagnostic Macros::           Diagnostic messages from M4sugar
11483* Diversion support::           Diversions in M4sugar
11484* Conditional constructs::      Conditions in M4
11485* Looping constructs::          Iteration in M4
11486* Evaluation Macros::           More quotation and evaluation control
11487* Text processing Macros::      String manipulation in M4
11488* Number processing Macros::    Arithmetic computation in M4
11489* Set manipulation Macros::     Set manipulation in M4
11490* Forbidden Patterns::          Catching unexpanded macros
11491@end menu
11492
11493@node Redefined M4 Macros
11494@subsection Redefined M4 Macros
11495
11496@msindex{builtin}
11497@msindex{changecom}
11498@msindex{changequote}
11499@msindex{debugfile}
11500@msindex{debugmode}
11501@msindex{decr}
11502@msindex{define}
11503@msindex{divnum}
11504@msindex{errprint}
11505@msindex{esyscmd}
11506@msindex{eval}
11507@msindex{format}
11508@msindex{ifdef}
11509@msindex{incr}
11510@msindex{index}
11511@msindex{indir}
11512@msindex{len}
11513@msindex{pushdef}
11514@msindex{shift}
11515@msindex{substr}
11516@msindex{syscmd}
11517@msindex{sysval}
11518@msindex{traceoff}
11519@msindex{traceon}
11520@msindex{translit}
11521With a few exceptions, all the M4 native macros are moved in the
11522@samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11523@code{m4_define} etc.
11524
11525The list of macros unchanged from M4, except for their name, is:
11526@itemize @minus
11527@item m4_builtin
11528@item m4_changecom
11529@item m4_changequote
11530@item m4_debugfile
11531@item m4_debugmode
11532@item m4_decr
11533@item m4_define
11534@item m4_divnum
11535@item m4_errprint
11536@item m4_esyscmd
11537@item m4_eval
11538@item m4_format
11539@item m4_ifdef
11540@item m4_incr
11541@item m4_index
11542@item m4_indir
11543@item m4_len
11544@item m4_pushdef
11545@item m4_shift
11546@item m4_substr
11547@item m4_syscmd
11548@item m4_sysval
11549@item m4_traceoff
11550@item m4_traceon
11551@item m4_translit
11552@end itemize
11553
11554Some M4 macros are redefined, and are slightly incompatible with their
11555native equivalent.
11556
11557@defmac __file__
11558@defmacx __line__
11559@MSindex __file__
11560@MSindex __line__
11561All M4 macros starting with @samp{__} retain their original name: for
11562example, no @code{m4__file__} is defined.
11563@end defmac
11564
11565@defmac __oline__
11566@MSindex __oline__
11567This is not technically a macro, but a feature of Autom4te.  The
11568sequence @code{__oline__} can be used similarly to the other m4sugar
11569location macros, but rather than expanding to the location of the input
11570file, it is translated to the line number where it appears in the output
11571file after all other M4 expansions.
11572@end defmac
11573
11574@defmac dnl
11575@MSindex dnl
11576This macro kept its original name: no @code{m4_dnl} is defined.
11577@end defmac
11578
11579@defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11580@msindex{bpatsubst}
11581This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11582is kept for future versions of M4sugar, once GNU M4 2.0 is
11583released and supports extended regular expression syntax.
11584@end defmac
11585
11586@defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11587@msindex{bregexp}
11588This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11589is kept for future versions of M4sugar, once GNU M4 2.0 is
11590released and supports extended regular expression syntax.
11591@end defmac
11592
11593@defmac m4_copy (@var{source}, @var{dest})
11594@defmacx m4_copy_force (@var{source}, @var{dest})
11595@defmacx m4_rename (@var{source}, @var{dest})
11596@defmacx m4_rename_force (@var{source}, @var{dest})
11597@msindex{copy}
11598@msindex{copy_force}
11599@msindex{rename}
11600@msindex{rename_force}
11601These macros aren't directly builtins, but are closely related to
11602@code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11603@code{m4_rename} ensure that @var{dest} is undefined, while
11604@code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11605definition.  All four macros then proceed to copy the entire pushdef
11606stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11607and @code{m4_copy_force} preserve the source (including in the special
11608case where @var{source} is undefined), while @code{m4_rename} and
11609@code{m4_rename_force} undefine the original macro name (making it an
11610error to rename an undefined @var{source}).
11611
11612Note that attempting to invoke a renamed macro might not work, since the
11613macro may have a dependence on helper macros accessed via composition of
11614@samp{$0} but that were not also renamed; likewise, other macros may
11615have a hard-coded dependence on @var{source} and could break if
11616@var{source} has been deleted.  On the other hand, it is always safe to
11617rename a macro to temporarily move it out of the way, then rename it
11618back later to restore original semantics.
11619@end defmac
11620
11621@defmac m4_defn (@var{macro}@dots{})
11622@msindex{defn}
11623This macro fails if @var{macro} is not defined, even when using older
11624versions of M4 that did not warn.  See @code{m4_undefine}.
11625Unfortunately, in order to support these older versions of M4, there are
11626some situations involving unbalanced quotes where concatenating multiple
11627macros together will work in newer M4 but not in m4sugar; use
11628quadrigraphs to work around this.
11629@end defmac
11630
11631@defmac m4_divert (@var{diversion})
11632@msindex{divert}
11633M4sugar relies heavily on diversions, so rather than behaving as a
11634primitive, @code{m4_divert} behaves like:
11635@example
11636m4_divert_pop()m4_divert_push([@var{diversion}])
11637@end example
11638@noindent
11639@xref{Diversion support}, for more details about the use of the
11640diversion stack.  In particular, this implies that @var{diversion}
11641should be a named diversion rather than a raw number.  But be aware that
11642it is seldom necessary to explicitly change the diversion stack, and
11643that when done incorrectly, it can lead to syntactically invalid
11644scripts.
11645@end defmac
11646
11647@defmac m4_dumpdef (@var{name}@dots{})
11648@defmacx m4_dumpdefs (@var{name}@dots{})
11649@msindex{dumpdef}
11650@msindex{dumpdefs}
11651@code{m4_dumpdef} is like the M4 builtin, except that this version
11652requires at least one argument, output always goes to standard error
11653rather than the current debug file, no sorting is done on multiple
11654arguments, and an error is issued if any
11655@var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11656calls @code{m4_dumpdef} for all of the
11657@code{m4_pushdef} stack of definitions, starting with the current, and
11658silently does nothing if @var{name} is undefined.
11659
11660Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11661builtin is output as the empty string.  This behavior is rectified by
11662using M4 1.6 or newer.  However, this behavior difference means that
11663@code{m4_dumpdef} should only be used while developing m4sugar macros,
11664and never in the final published form of a macro.
11665@end defmac
11666
11667@defmac m4_esyscmd_s (@var{command})
11668@msindex{esyscmd_s}
11669Like @code{m4_esyscmd}, this macro expands to the result of running
11670@var{command} in a shell.  The difference is that any trailing newlines
11671are removed, so that the output behaves more like shell command
11672substitution.
11673@end defmac
11674
11675@defmac m4_exit (@var{exit-status})
11676@msindex{exit}
11677This macro corresponds to @code{m4exit}.
11678@end defmac
11679
11680@defmac m4_if (@var{comment})
11681@defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11682@defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11683  @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11684@msindex{if}
11685This macro corresponds to @code{ifelse}.  @var{string-1} and
11686@var{string-2} are compared literally, so usually one of the two
11687arguments is passed unquoted.  @xref{Conditional constructs}, for more
11688conditional idioms.
11689@end defmac
11690
11691@defmac m4_include (@var{file})
11692@defmacx m4_sinclude (@var{file})
11693@msindex{include}
11694@msindex{sinclude}
11695Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11696@end defmac
11697
11698@defmac m4_mkstemp (@var{template})
11699@defmacx m4_maketemp (@var{template})
11700@msindex{maketemp}
11701@msindex{mkstemp}
11702Posix requires @code{maketemp} to replace the trailing @samp{X}
11703characters in @var{template} with the process id, without regards to the
11704existence of a file by that name, but this a security hole.  When this
11705was pointed out to the Posix folks, they agreed to invent a new macro
11706@code{mkstemp} that always creates a uniquely named file, but not all
11707versions of GNU M4 support the new macro.  In M4sugar,
11708@code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11709and both have the secure semantics regardless of which macro the
11710underlying M4 provides.
11711@end defmac
11712
11713@defmac m4_popdef (@var{macro}@dots{})
11714@msindex{popdef}
11715This macro fails if @var{macro} is not defined, even when using older
11716versions of M4 that did not warn.  See @code{m4_undefine}.
11717@end defmac
11718
11719@defmac m4_undefine (@var{macro}@dots{})
11720@msindex{undefine}
11721This macro fails if @var{macro} is not defined, even when using older
11722versions of M4 that did not warn.  Use
11723
11724@example
11725m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11726@end example
11727
11728@noindent
11729if you are not sure whether @var{macro} is defined.
11730@end defmac
11731
11732@defmac m4_undivert (@var{diversion}@dots{})
11733@msindex{undivert}
11734Unlike the M4 builtin, at least one @var{diversion} must be specified.
11735Also, since the M4sugar diversion stack prefers named
11736diversions, the use of @code{m4_undivert} to include files is risky.
11737@xref{Diversion support}, for more details about the use of the
11738diversion stack.  But be aware that it is seldom necessary to explicitly
11739change the diversion stack, and that when done incorrectly, it can lead
11740to syntactically invalid scripts.
11741@end defmac
11742
11743@defmac m4_wrap (@var{text})
11744@defmacx m4_wrap_lifo (@var{text})
11745@msindex{wrap}
11746@msindex{wrap_lifo}
11747These macros correspond to @code{m4wrap}.  Posix requires arguments of
11748multiple wrap calls to be reprocessed at EOF in the same order
11749as the original calls (first-in, first-out).  GNU M4 versions
11750through 1.4.10, however, reprocess them in reverse order (last-in,
11751first-out).  Both orders are useful, therefore, you can rely on
11752@code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11753LIFO semantics, regardless of the underlying GNU M4 version.
11754
11755Unlike the GNU M4 builtin, these macros only recognize one
11756argument, and avoid token pasting between consecutive invocations.  On
11757the other hand, nested calls to @code{m4_wrap} from within wrapped text
11758work just as in the builtin.
11759@end defmac
11760
11761
11762@node Diagnostic Macros
11763@subsection Diagnostic messages from M4sugar
11764@cindex Messages, from @command{M4sugar}
11765
11766When macros statically diagnose abnormal situations, benign or fatal,
11767they should report them using these macros.  For issuing dynamic issues,
11768i.e., when @command{configure} is run, see @ref{Printing Messages}.
11769
11770@defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11771@msindex{assert}
11772Assert that the arithmetic @var{expression} evaluates to non-zero.
11773Otherwise, issue a fatal error, and exit @command{autom4te} with
11774@var{exit-status}.
11775@end defmac
11776
11777@defmac m4_errprintn (@var{message})
11778@msindex{errprintn}
11779Similar to the builtin @code{m4_errprint}, except that a newline is
11780guaranteed after @var{message}.
11781@end defmac
11782
11783@anchor{m4_fatal}
11784@defmac m4_fatal (@var{message})
11785@msindex{fatal}
11786Report a severe error @var{message} prefixed with the current location,
11787and have @command{autom4te} die.
11788@end defmac
11789
11790@defmac m4_location
11791@msindex{location}
11792Useful as a prefix in a message line.  Short for:
11793@example
11794__file__:__line__
11795@end example
11796@end defmac
11797
11798@anchor{m4_warn}
11799@defmac m4_warn (@var{category}, @var{message})
11800@msindex{warn}
11801Report @var{message} as a warning (or as an error if requested by the
11802user) if warnings of the @var{category} are turned on.  If the message
11803is emitted, it is prefixed with the current location, and followed by a
11804call trace of all macros defined via @code{AC_DEFUN} used to get to the
11805current expansion.  You are encouraged to use standard categories, which
11806currently include:
11807
11808@table @samp
11809@item all
11810messages that don't fall into one of the following categories.  Use of an
11811empty @var{category} is equivalent.
11812
11813@item cross
11814related to cross compilation issues.
11815
11816@item obsolete
11817use of an obsolete construct.
11818
11819@item syntax
11820dubious syntactic constructs, incorrectly ordered macro calls.
11821@end table
11822@end defmac
11823
11824
11825@node Diversion support
11826@subsection Diversion support
11827
11828M4sugar makes heavy use of diversions under the hood, because it is
11829often the case that
11830text that must appear early in the output is not discovered until late
11831in the input.  Additionally, some of the topological sorting algorithms
11832used in resolving macro dependencies use diversions.  However, most
11833macros should not need to change diversions directly, but rather rely on
11834higher-level M4sugar macros to manage diversions transparently.  If you
11835change diversions improperly, you risk generating a syntactically
11836invalid script, because an incorrect diversion will violate assumptions
11837made by many macros about whether prerequisite text has been previously
11838output.  In short, if you manually change the diversion, you should not
11839expect any macros provided by the Autoconf package to work until you
11840have restored the diversion stack back to its original state.
11841
11842In the rare case that it is necessary to write a macro that explicitly
11843outputs text to a different diversion, it is important to be aware of an
11844M4 limitation regarding diversions: text only goes to a diversion if it
11845is not part of argument collection.  Therefore, any macro that changes
11846the current diversion cannot be used as an unquoted argument to another
11847macro, but must be expanded at the top level.  The macro
11848@code{m4_expand} will diagnose any attempt to change diversions, since
11849it is generally useful only as an argument to another macro.  The
11850following example shows what happens when diversion manipulation is
11851attempted within macro arguments:
11852
11853@example
11854m4_do([normal text]
11855m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11856[m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11857@result{}normal text
11858@result{}unwanted
11859@end example
11860
11861@noindent
11862Notice that the unquoted text @code{unwanted} is output, even though it
11863was processed while the current diversion was @code{KILL}, because it
11864was collected as part of the argument to @code{m4_do}.  However, the
11865text @code{discarded} disappeared as desired, because the diversion
11866changes were single-quoted, and were not expanded until the top-level
11867rescan of the output of @code{m4_do}.
11868
11869To make diversion management easier, M4sugar uses the concept of named
11870diversions.  Rather than using diversion numbers directly, it is nicer
11871to associate a name with each diversion.  The diversion number associated
11872with a particular diversion name is an implementation detail, and a
11873syntax warning is issued if a diversion number is used instead of a
11874name.  In general, you should not output text
11875to a named diversion until after calling the appropriate initialization
11876routine for your language (@code{m4_init}, @code{AS_INIT},
11877@code{AT_INIT}, @dots{}), although there are some exceptions documented
11878below.
11879
11880M4sugar defines two named diversions.
11881@table @code
11882@item KILL
11883Text written to this diversion is discarded.  This is the default
11884diversion once M4sugar is initialized.
11885@item GROW
11886This diversion is used behind the scenes by topological sorting macros,
11887such as @code{AC_REQUIRE}.
11888@end table
11889
11890M4sh adds several more named diversions.
11891@table @code
11892@item BINSH
11893This diversion is reserved for the @samp{#!} interpreter line.
11894@item HEADER-REVISION
11895This diversion holds text from @code{AC_REVISION}.
11896@item HEADER-COMMENT
11897This diversion holds comments about the purpose of a file.
11898@item HEADER-COPYRIGHT
11899This diversion is managed by @code{AC_COPYRIGHT}.
11900@item M4SH-SANITIZE
11901This diversion contains M4sh sanitization code, used to ensure M4sh is
11902executing in a reasonable shell environment.
11903@item M4SH-INIT
11904This diversion contains M4sh initialization code, initializing variables
11905that are required by other M4sh macros.
11906@item BODY
11907This diversion contains the body of the shell code, and is the default
11908diversion once M4sh is initialized.
11909@end table
11910
11911Autotest inherits diversions from M4sh, and changes the default
11912diversion from @code{BODY} back to @code{KILL}.  It also adds several
11913more named diversions, with the following subset designed for developer
11914use.
11915@table @code
11916@item PREPARE_TESTS
11917This diversion contains initialization sequences which are executed
11918after @file{atconfig} and @file{atlocal}, and after all command line
11919arguments have been parsed, but prior to running any tests.  It can be
11920used to set up state that is required across all tests.  This diversion
11921will work even before @code{AT_INIT}.
11922@end table
11923
11924Autoconf inherits diversions from M4sh, and adds the following named
11925diversions which developers can utilize.
11926@table @code
11927@item DEFAULTS
11928This diversion contains shell variable assignments to set defaults that
11929must be in place before arguments are parsed.  This diversion is placed
11930early enough in @file{configure} that it is unsafe to expand any
11931autoconf macros into this diversion.
11932@item HELP_ENABLE
11933If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11934diversion will be included as part of a quoted here-doc providing all of
11935the @option{--help} output of @file{configure} related to options
11936created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11937@item INIT_PREPARE
11938This diversion occurs after all command line options have been parsed,
11939but prior to the main body of the @file{configure} script.  This
11940diversion is the last chance to insert shell code such as variable
11941assignments or shell function declarations that will used by the
11942expansion of other macros.
11943@end table
11944
11945For now, the remaining named diversions of Autoconf, Autoheader, and
11946Autotest are not documented.  In other words,
11947intentionally outputting text into an undocumented diversion is subject
11948to breakage in a future release of Autoconf.
11949
11950@defmac m4_cleardivert (@var{diversion}@dots{})
11951@msindex{cleardivert}
11952Permanently discard any text that has been diverted into
11953@var{diversion}.
11954@end defmac
11955
11956@defmac m4_divert_once (@var{diversion}, @ovar{content})
11957@msindex{divert_once}
11958Similar to @code{m4_divert_text}, except that @var{content} is only
11959output to @var{diversion} if this is the first time that
11960@code{m4_divert_once} has been called with its particular arguments.
11961@end defmac
11962
11963@defmac m4_divert_pop (@ovar{diversion})
11964@msindex{divert_pop}
11965If provided, check that the current diversion is indeed @var{diversion}.
11966Then change to the diversion located earlier on the stack, giving an
11967error if an attempt is made to pop beyond the initial m4sugar diversion
11968of @code{KILL}.
11969@end defmac
11970
11971@defmac m4_divert_push (@var{diversion})
11972@msindex{divert_push}
11973Remember the former diversion on the diversion stack, and output
11974subsequent text into @var{diversion}.  M4sugar maintains a diversion
11975stack, and issues an error if there is not a matching pop for every
11976push.
11977@end defmac
11978
11979@defmac m4_divert_text (@var{diversion}, @ovar{content})
11980@msindex{divert_text}
11981Output @var{content} and a newline into @var{diversion}, without
11982affecting the current diversion.  Shorthand for:
11983@example
11984m4_divert_push([@var{diversion}])@var{content}
11985m4_divert_pop([@var{diversion}])dnl
11986@end example
11987
11988One use of @code{m4_divert_text} is to develop two related macros, where
11989macro @samp{MY_A} does the work, but adjusts what work is performed
11990based on whether the optional macro @samp{MY_B} has also been expanded.
11991Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11992require that @samp{MY_B} occurs first, if it occurs at all.  But this
11993imposes an ordering restriction on the user; it would be nicer if macros
11994@samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
11995is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
11996@samp{MY_A} can then use to determine whether @samp{MY_B} has been
11997expanded.
11998
11999@example
12000AC_DEFUN([MY_A],
12001[# various actions
12002if test -n "$b_was_used"; then
12003  # extra action
12004fi])
12005AC_DEFUN([MY_B],
12006[AC_REQUIRE([MY_A])dnl
12007m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12008@end example
12009
12010@end defmac
12011
12012@defmac m4_init
12013@msindex{init}
12014Initialize the M4sugar environment, setting up the default named
12015diversion to be @code{KILL}.
12016@end defmac
12017
12018@node Conditional constructs
12019@subsection Conditional constructs
12020
12021The following macros provide additional conditional constructs as
12022convenience wrappers around @code{m4_if}.
12023
12024@defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12025  @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12026@msindex{bmatch}
12027The string @var{string} is repeatedly compared against a series of
12028@var{regex} arguments; if a match is found, the expansion is the
12029corresponding @var{value}, otherwise, the macro moves on to the next
12030@var{regex}.  If no @var{regex} match, then the result is the optional
12031@var{default}, or nothing.
12032@end defmac
12033
12034@defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12035  @ovar{regex-2}, @ovar{subst-2}, @dots{})
12036@msindex{bpatsubsts}
12037The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12038as if by:
12039@example
12040m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12041@end example
12042
12043@noindent
12044The result of the substitution is then passed through the next set of
12045@var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12046deletion of any matched portions in the current string.  Note that this
12047macro over-quotes @var{string}; this behavior is intentional, so that
12048the result of each step of the recursion remains as a quoted string.
12049However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12050will line up with the extra quotations, and not the characters of the
12051original string.  The overquoting is removed after the final
12052substitution.
12053@end defmac
12054
12055@defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12056  @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12057@msindex{case}
12058Test @var{string} against multiple @var{value} possibilities, resulting
12059in the first @var{if-value} for a match, or in the optional
12060@var{default}.  This is shorthand for:
12061@example
12062m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12063      [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12064      [@var{default}])
12065@end example
12066@end defmac
12067
12068@defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12069  @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12070@msindex{cond}
12071This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12072except that each @var{test} is expanded only when it is encountered.
12073This is useful for short-circuiting expensive tests; while @code{m4_if}
12074requires all its strings to be expanded up front before doing
12075comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12076tests have failed.
12077
12078For an example, these two sequences give the same result, but in the
12079case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12080version only expands @code{m4_index} once, instead of five times, for
12081faster computation if this is a common case for @samp{$1}.  Notice that
12082every third argument is unquoted for @code{m4_if}, and quoted for
12083@code{m4_cond}:
12084
12085@example
12086m4_if(m4_index([$1], [\]), [-1], [$2],
12087      m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12088      m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12089      m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12090      m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12091      [$2])
12092m4_cond([m4_index([$1], [\])], [-1], [$2],
12093        [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12094        [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12095        [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12096        [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12097        [$2])
12098@end example
12099@end defmac
12100
12101@defmac m4_default (@var{expr-1}, @var{expr-2})
12102@defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12103@defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12104@defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12105@msindex{default}
12106@msindex{default_quoted}
12107@msindex{default_nblank}
12108@msindex{default_nblank_quoted}
12109If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12110@code{m4_default} expands the result, while @code{m4_default_quoted}
12111does not.  Useful for providing a fixed default if the expression that
12112results in @var{expr-1} would otherwise be empty.  The difference
12113between @code{m4_default} and @code{m4_default_nblank} is whether an
12114argument consisting of just blanks (space, tab, newline) is
12115significant.  When using the expanding versions, note that an argument
12116may contain text but still expand to an empty string.
12117
12118@example
12119m4_define([active], [ACTIVE])dnl
12120m4_define([empty], [])dnl
12121m4_define([demo1], [m4_default([$1], [$2])])dnl
12122m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12123m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12124m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12125demo1([active], [default])
12126@result{}ACTIVE
12127demo1([], [active])
12128@result{}ACTIVE
12129demo1([empty], [text])
12130@result{}
12131-demo1([ ], [active])-
12132@result{}- -
12133demo2([active], [default])
12134@result{}active
12135demo2([], [active])
12136@result{}active
12137demo2([empty], [text])
12138@result{}empty
12139-demo2([ ], [active])-
12140@result{}- -
12141demo3([active], [default])
12142@result{}ACTIVE
12143demo3([], [active])
12144@result{}ACTIVE
12145demo3([empty], [text])
12146@result{}
12147-demo3([ ], [active])-
12148@result{}-ACTIVE-
12149demo4([active], [default])
12150@result{}active
12151demo4([], [active])
12152@result{}active
12153demo4([empty], [text])
12154@result{}empty
12155-demo4([ ], [active])-
12156@result{}-active-
12157@end example
12158@end defmac
12159
12160@defmac m4_define_default (@var{macro}, @ovar{default-definition})
12161@msindex{define_default}
12162If @var{macro} does not already have a definition, then define it to
12163@var{default-definition}.
12164@end defmac
12165
12166@defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12167@defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12168@msindex{ifblank}
12169@msindex{ifnblank}
12170If @var{cond} is empty or consists only of blanks (space, tab, newline),
12171then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12172variants exist, in order to make it easier to select the correct logical
12173sense when using only two parameters.  Note that this is more efficient
12174than the equivalent behavior of:
12175@example
12176m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12177@end example
12178@end defmac
12179
12180@defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12181@msindex{ifndef}
12182This is shorthand for:
12183@example
12184m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12185@end example
12186@end defmac
12187
12188@defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12189@msindex{ifset}
12190If @var{macro} is undefined, or is defined as the empty string, expand
12191to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12192@example
12193m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12194@end example
12195@noindent
12196except that it is not an error if @var{macro} is undefined.
12197@end defmac
12198
12199@defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12200@msindex{ifval}
12201Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12202@var{if-false}.  This is shorthand for:
12203@example
12204m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12205@end example
12206@end defmac
12207
12208@defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12209@msindex{ifvaln}
12210Similar to @code{m4_ifval}, except guarantee that a newline is present
12211after any non-empty expansion.  Often followed by @code{dnl}.
12212@end defmac
12213
12214@defmac m4_n (@var{text})
12215@msindex{n}
12216Expand to @var{text}, and add a newline if @var{text} is not empty.
12217Often followed by @code{dnl}.
12218@end defmac
12219
12220
12221@node Looping constructs
12222@subsection Looping constructs
12223
12224The following macros are useful in implementing recursive algorithms in
12225M4, including loop operations.  An M4 list is formed by quoting a list
12226of quoted elements; generally the lists are comma-separated, although
12227@code{m4_foreach_w} is whitespace-separated.  For example, the list
12228@samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12229It is common to see lists with unquoted elements when those elements are
12230not likely to be macro names, as in @samp{[fputc_unlocked,
12231fgetc_unlocked]}.
12232
12233Although not generally recommended, it is possible for quoted lists to
12234have side effects; all side effects are expanded only once, and prior to
12235visiting any list element.  On the other hand, the fact that unquoted
12236macros are expanded exactly once means that macros without side effects
12237can be used to generate lists.  For example,
12238
12239@example
12240m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12241@error{}hi
12242@result{}123
12243m4_define([list], [[1], [2], [3]])
12244@result{}
12245m4_foreach([i], [list], [i])
12246@result{}123
12247@end example
12248
12249@defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12250@msindex{argn}
12251Extracts argument @var{n} (larger than 0) from the remaining arguments.
12252If there are too few arguments, the empty string is used.  For any
12253@var{n} besides 1, this is more efficient than the similar
12254@samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12255@end defmac
12256
12257@defmac m4_car (@var{arg}@dots{})
12258@msindex{car}
12259Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12260to recursively iterate
12261through a list.  Generally, when using quoted lists of quoted elements,
12262@code{m4_car} should be called without any extra quotes.
12263@end defmac
12264
12265@defmac m4_cdr (@var{arg}@dots{})
12266@msindex{cdr}
12267Expands to a quoted list of all but the first @var{arg}, or the empty
12268string if there was only one argument.  Generally, when using quoted
12269lists of quoted elements, @code{m4_cdr} should be called without any
12270extra quotes.
12271
12272For example, this is a simple implementation of @code{m4_map}; note how
12273each iteration checks for the end of recursion, then merely applies the
12274first argument to the first element of the list, then repeats with the
12275rest of the list.  (The actual implementation in M4sugar is a bit more
12276involved, to gain some speed and share code with @code{m4_map_sep}, and
12277also to avoid expanding side effects in @samp{$2} twice).
12278@example
12279m4_define([m4_map], [m4_ifval([$2],
12280  [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12281m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12282@result{} 1 2 a
12283@end example
12284@end defmac
12285
12286@defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12287  @var{expression})
12288@msindex{for}
12289Loop over the numeric values between @var{first} and @var{last}
12290including bounds by increments of @var{step}.  For each iteration,
12291expand @var{expression} with the numeric value assigned to @var{var}.
12292If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12293on the order of the limits.  If given, @var{step} has to match this
12294order.  The number of iterations is determined independently from
12295definition of @var{var}; iteration cannot be short-circuited or
12296lengthened by modifying @var{var} from within @var{expression}.
12297@end defmac
12298
12299@defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12300@msindex{foreach}
12301Loop over the comma-separated M4 list @var{list}, assigning each value
12302to @var{var}, and expand @var{expression}.  The following example
12303outputs two lines:
12304
12305@example
12306m4_foreach([myvar], [[foo], [bar, baz]],
12307           [echo myvar
12308])dnl
12309@result{}echo foo
12310@result{}echo bar, baz
12311@end example
12312
12313Note that for some forms of @var{expression}, it may be faster to use
12314@code{m4_map_args}.
12315@end defmac
12316
12317@anchor{m4_foreach_w}
12318@defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12319@msindex{foreach_w}
12320Loop over the white-space-separated list @var{list}, assigning each value
12321to @var{var}, and expand @var{expression}.  If @var{var} is only
12322referenced once in @var{expression}, it is more efficient to use
12323@code{m4_map_args_w}.
12324
12325The deprecated macro @code{AC_FOREACH} is an alias of
12326@code{m4_foreach_w}.
12327@end defmac
12328
12329@defmac m4_map (@var{macro}, @var{list})
12330@defmacx m4_mapall (@var{macro}, @var{list})
12331@defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12332@defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12333@msindex{map}
12334@msindex{mapall}
12335@msindex{map_sep}
12336@msindex{mapall_sep}
12337Loop over the comma separated quoted list of argument descriptions in
12338@var{list}, and invoke @var{macro} with the arguments.  An argument
12339description is in turn a comma-separated quoted list of quoted elements,
12340suitable for @code{m4_apply}.  The macros @code{m4_map} and
12341@code{m4_map_sep} ignore empty argument descriptions, while
12342@code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12343arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12344additionally expand @var{separator} between invocations of @var{macro}.
12345
12346Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12347separating output with commas, this means that the map result can be
12348used as a series of arguments, by using a single-quoted comma as
12349@var{separator}, or as a single string, by using a double-quoted comma.
12350
12351@example
12352m4_map([m4_count], [])
12353@result{}
12354m4_map([ m4_count], [[],
12355                     [[1]],
12356                     [[1], [2]]])
12357@result{} 1 2
12358m4_mapall([ m4_count], [[],
12359                        [[1]],
12360                        [[1], [2]]])
12361@result{} 0 1 2
12362m4_map_sep([m4_eval], [,], [[[1+2]],
12363                            [[10], [16]]])
12364@result{}3,a
12365m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12366@result{}a,b
12367m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12368@result{}2
12369m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12370@result{}a,b
12371m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12372@result{}1
12373@end example
12374@end defmac
12375
12376@defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12377@msindex{map_args}
12378Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12379argument.  In the following example, three solutions are presented with
12380the same expansion; the solution using @code{m4_map_args} is the most
12381efficient.
12382@example
12383m4_define([active], [ACTIVE])dnl
12384m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12385@result{} plain active
12386m4_map([ m4_echo], [[[plain]], [[active]]])
12387@result{} plain active
12388m4_map_args([ m4_echo], [plain], [active])
12389@result{} plain active
12390@end example
12391
12392In cases where it is useful to operate on additional parameters besides
12393the list elements, the macro @code{m4_curry} can be used in @var{macro}
12394to supply the argument currying necessary to generate the desired
12395argument list.  In the following example, @code{list_add_n} is more
12396efficient than @code{list_add_x}.  On the other hand, using
12397@code{m4_map_args_sep} can be even more efficient.
12398
12399@example
12400m4_define([list], [[1], [2], [3]])dnl
12401m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12402dnl list_add_n(N, ARG...)
12403dnl Output a list consisting of each ARG added to N
12404m4_define([list_add_n],
12405[m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12406list_add_n([1], list)
12407@result{}2,3,4
12408list_add_n([2], list)
12409@result{}3,4,5
12410m4_define([list_add_x],
12411[m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12412  [,add([$1],m4_defn([var]))]))])dnl
12413list_add_x([1], list)
12414@result{}2,3,4
12415@end example
12416@end defmac
12417
12418@defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
12419  @var{arg}@dots{})
12420@msindex{map_args_pair}
12421For every pair of arguments @var{arg}, invoke @var{macro} with two
12422arguments.  If there is an odd number of arguments, invoke
12423@var{macro-end}, which defaults to @var{macro}, with the remaining
12424argument.
12425
12426@example
12427m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12428@result{}, 2, 1, 3
12429m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12430@result{}, 2, 1, [3]
12431m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12432@result{}, 2, 1, 4, 3
12433@end example
12434@end defmac
12435
12436@defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12437@msindex{map_args_sep}
12438Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12439argument, additionally expanding @var{sep} between arguments.  One
12440common use of this macro is constructing a macro call, where the opening
12441and closing parentheses are split between @var{pre} and @var{post}; in
12442particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12443to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12444macro provides the most efficient means for iterating over an arbitrary
12445list of arguments, particularly when repeatedly constructing a macro
12446call with more arguments than @var{arg}.
12447@end defmac
12448
12449@defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12450@msindex{map_args_w}
12451Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12452the whitespace-separated @var{string}, additionally expanding @var{sep}
12453between words.  This macro provides the most efficient means for
12454iterating over a whitespace-separated string.  In particular,
12455@code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12456efficient than @code{m4_foreach_w([var], [@var{string}],
12457[@var{action}(m4_defn([var]))])}.
12458@end defmac
12459
12460@defmac m4_shiftn (@var{count}, @dots{})
12461@defmacx m4_shift2 (@dots{})
12462@defmacx m4_shift3 (@dots{})
12463@msindex{shift2}
12464@msindex{shift3}
12465@msindex{shiftn}
12466@code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12467along with validation that enough arguments were passed in to match the
12468shift count, and that the count is positive.  @code{m4_shift2} and
12469@code{m4_shift3} are specializations
12470of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12471for two and three shifts, respectively.
12472@end defmac
12473
12474@defmac m4_stack_foreach (@var{macro}, @var{action})
12475@defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12476@msindex{stack_foreach}
12477@msindex{stack_foreach_lifo}
12478For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12479@var{action} with the single argument of a definition of @var{macro}.
12480@code{m4_stack_foreach} starts with the oldest definition, while
12481@code{m4_stack_foreach_lifo} starts with the current definition.
12482@var{action} should not push or pop definitions of @var{macro}, nor is
12483there any guarantee that the current definition of @var{macro} matches
12484the argument that was passed to @var{action}.  The macro @code{m4_curry}
12485can be used if @var{action} needs more than one argument, although in
12486that case it is more efficient to use @var{m4_stack_foreach_sep}.
12487
12488Due to technical limitations, there are a few low-level m4sugar
12489functions, such as @code{m4_pushdef}, that cannot be used as the
12490@var{macro} argument.
12491
12492@example
12493m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12494m4_stack_foreach([a], [ m4_incr])
12495@result{} 2 3
12496m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12497@result{} cd bcd
12498@end example
12499@end defmac
12500
12501@defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12502@defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12503  @ovar{sep})
12504@msindex{stack_foreach_sep}
12505@msindex{stack_foreach_sep_lifo}
12506Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12507@code{m4_pushdef} definition of @var{macro}, additionally expanding
12508@var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12509oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12510the current definition first.  This macro provides the most efficient
12511means for iterating over a pushdef stack.  In particular,
12512@code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12513@code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12514@end defmac
12515
12516@node Evaluation Macros
12517@subsection Evaluation Macros
12518
12519The following macros give some control over the order of the evaluation
12520by adding or removing levels of quotes.
12521
12522@defmac m4_apply (@var{macro}, @var{list})
12523@msindex{apply}
12524Apply the elements of the quoted, comma-separated @var{list} as the
12525arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12526without arguments.  Note the difference between @code{m4_indir}, which
12527expects its first argument to be a macro name but can use names that are
12528otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12529other text, but must end in a valid macro name.
12530@example
12531m4_apply([m4_count], [])
12532@result{}0
12533m4_apply([m4_count], [[]])
12534@result{}1
12535m4_apply([m4_count], [[1], [2]])
12536@result{}2
12537m4_apply([m4_join], [[|], [1], [2]])
12538@result{}1|2
12539@end example
12540@end defmac
12541
12542@defmac m4_count (@var{arg}, @dots{})
12543@msindex{count}
12544This macro returns the decimal count of the number of arguments it was
12545passed.
12546@end defmac
12547
12548@defmac m4_curry (@var{macro}, @var{arg}@dots{})
12549@msindex{curry}
12550This macro performs argument currying.  The expansion of this macro is
12551another macro name that expects exactly one argument; that argument is
12552then appended to the @var{arg} list, and then @var{macro} is expanded
12553with the resulting argument list.
12554
12555@example
12556m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12557@result{}3, 2, 1
12558@end example
12559
12560Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12561pass the definition of a builtin macro as the argument to the output of
12562@code{m4_curry}; the empty string is used instead of the builtin token.
12563This behavior is rectified by using M4 1.6 or newer.
12564@end defmac
12565
12566@defmac m4_do (@var{arg}, @dots{})
12567@msindex{do}
12568This macro loops over its arguments and expands each @var{arg} in
12569sequence.  Its main use is for readability; it allows the use of
12570indentation and fewer @code{dnl} to result in the same expansion.  This
12571macro guarantees that no expansion will be concatenated with subsequent
12572text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12573@var{arg@dots{}}))}.
12574
12575@example
12576m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12577m4_do([a],[b])c
12578@result{}abc
12579m4_unquote(m4_join([],[a],[b]))c
12580@result{}3
12581m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12582m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12583m4_do([a],[b])c
12584@result{}ABC
12585m4_unquote(m4_join([],[a],[b]))c
12586@result{}3
12587@end example
12588@end defmac
12589
12590@defmac m4_dquote (@var{arg}, @dots{})
12591@msindex{dquote}
12592Return the arguments as a quoted list of quoted arguments.
12593Conveniently, if there is just one @var{arg}, this effectively adds a
12594level of quoting.
12595@end defmac
12596
12597@defmac m4_dquote_elt (@var{arg}, @dots{})
12598@msindex{dquote_elt}
12599Return the arguments as a series of double-quoted arguments.  Whereas
12600@code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12601as many arguments as it was passed.
12602@end defmac
12603
12604@defmac m4_echo (@var{arg}, @dots{})
12605@msindex{echo}
12606Return the arguments, with the same level of quoting.  Other than
12607discarding whitespace after unquoted commas, this macro is a no-op.
12608@end defmac
12609
12610@defmac m4_expand (@var{arg})
12611@msindex{expand}
12612Return the expansion of @var{arg} as a quoted string.  Whereas
12613@code{m4_quote} is designed to collect expanded text into a single
12614argument, @code{m4_expand} is designed to perform one level of expansion
12615on quoted text.  One distinction is in the treatment of whitespace
12616following a comma in the original @var{arg}.  Any time multiple
12617arguments are collected into one with @code{m4_quote}, the M4 argument
12618collection rules discard the whitespace.  However, with @code{m4_expand},
12619whitespace is preserved, even after the expansion of macros contained in
12620@var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12621would involve an unterminated comment, whereas expanding that same text
12622as the argument to @code{m4_quote} runs into difficulty in finding the
12623end of the argument.  Since manipulating diversions during argument
12624collection is inherently unsafe, @code{m4_expand} issues an error if
12625@var{arg} attempts to change the current diversion (@pxref{Diversion
12626support}).
12627
12628@example
12629m4_define([active], [ACT, IVE])dnl
12630m4_define([active2], [[ACT, IVE]])dnl
12631m4_quote(active, active)
12632@result{}ACT,IVE,ACT,IVE
12633m4_expand([active, active])
12634@result{}ACT, IVE, ACT, IVE
12635m4_quote(active2, active2)
12636@result{}ACT, IVE,ACT, IVE
12637m4_expand([active2, active2])
12638@result{}ACT, IVE, ACT, IVE
12639m4_expand([# m4_echo])
12640@result{}# m4_echo
12641m4_quote(# m4_echo)
12642)
12643@result{}# m4_echo)
12644@result{}
12645@end example
12646
12647Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12648literal unbalanced quotes, but that quadrigraphs can be used when
12649unbalanced output is necessary.  Likewise, unbalanced parentheses should
12650be supplied with double quoting or a quadrigraph.
12651
12652@example
12653m4_define([pattern], [[!@@<:@@]])dnl
12654m4_define([bar], [BAR])dnl
12655m4_expand([case $foo in
12656  m4_defn([pattern])@@:@}@@ bar ;;
12657  *[)] blah ;;
12658esac])
12659@result{}case $foo in
12660@result{}  [![]) BAR ;;
12661@result{}  *) blah ;;
12662@result{}esac
12663@end example
12664@end defmac
12665
12666@defmac m4_ignore (@dots{})
12667@msindex{ignore}
12668This macro was introduced in Autoconf 2.62.  Expands to nothing,
12669ignoring all of its arguments.  By itself, this isn't very useful.
12670However, it can be used to conditionally ignore an arbitrary number of
12671arguments, by deciding which macro name to apply to a list of arguments.
12672@example
12673dnl foo outputs a message only if [debug] is defined.
12674m4_define([foo],
12675[m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12676@end example
12677
12678Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12679serve the same purpose, although it is less readable.
12680@end defmac
12681
12682@defmac m4_make_list (@var{arg}, @dots{})
12683@msindex{make_list}
12684This macro exists to aid debugging of M4sugar algorithms.  Its net
12685effect is similar to @code{m4_dquote}---it produces a quoted list of
12686quoted arguments, for each @var{arg}.  The difference is that this
12687version uses a comma-newline separator instead of just comma, to improve
12688readability of the list; with the result that it is less efficient than
12689@code{m4_dquote}.
12690@example
12691m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12692m4_dquote(zero, [one], [[two]])
12693@result{}[0],[one],[[two]]
12694m4_make_list(zero, [one], [[two]])
12695@result{}[0],
12696@result{}[one],
12697@result{}[[two]]
12698m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12699@result{} 0 1 two
12700m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12701@result{} 0 1 two
12702@end example
12703@end defmac
12704
12705@c m4_noquote is too dangerous to document - it invokes macros that
12706@c probably rely on @samp{[]} nested quoting for proper operation.  The
12707@c user should generally prefer m4_unquote instead.
12708
12709@defmac m4_quote (@var{arg}, @dots{})
12710@msindex{quote}
12711Return the arguments as a single entity, i.e., wrap them into a pair of
12712quotes.  This effectively collapses multiple arguments into one,
12713although it loses whitespace after unquoted commas in the process.
12714@end defmac
12715
12716@defmac m4_reverse (@var{arg}, @dots{})
12717@msindex{reverse}
12718Outputs each argument with the same level of quoting, but in reverse
12719order, and with space following each comma for readability.
12720
12721@example
12722m4_define([active], [ACT,IVE])
12723@result{}
12724m4_reverse(active, [active])
12725@result{}active, IVE, ACT
12726@end example
12727@end defmac
12728
12729@defmac m4_unquote (@var{arg}, @dots{})
12730@msindex{unquote}
12731This macro was introduced in Autoconf 2.62.  Expand each argument,
12732separated by commas.  For a single @var{arg}, this effectively removes a
12733layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12734than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12735this results in an unquoted list of expansions.  This is commonly used
12736with @code{m4_split}, in order to convert a single quoted list into a
12737series of quoted elements.
12738@end defmac
12739
12740The following example aims at emphasizing the difference between several
12741scenarios: not using these macros, using @code{m4_defn}, using
12742@code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12743
12744@example
12745$ @kbd{cat example.m4}
12746dnl Overquote, so that quotes are visible.
12747m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12748m4_define([a], [A])
12749m4_define([mkargs], [1, 2[,] 3])
12750m4_define([arg1], [[$1]])
12751m4_divert([0])dnl
12752show(a, b)
12753show([a, b])
12754show(m4_quote(a, b))
12755show(m4_dquote(a, b))
12756show(m4_expand([a, b]))
12757
12758arg1(mkargs)
12759arg1([mkargs])
12760arg1(m4_defn([mkargs]))
12761arg1(m4_quote(mkargs))
12762arg1(m4_dquote(mkargs))
12763arg1(m4_expand([mkargs]))
12764$ @kbd{autom4te -l m4sugar example.m4}
12765$1 = A, $@@ = [A],[b]
12766$1 = a, b, $@@ = [a, b]
12767$1 = A,b, $@@ = [A,b]
12768$1 = [A],[b], $@@ = [[A],[b]]
12769$1 = A, b, $@@ = [A, b]
12770
127711
12772mkargs
127731, 2[,] 3
127741,2, 3
12775[1],[2, 3]
127761, 2, 3
12777@end example
12778
12779
12780@node Text processing Macros
12781@subsection String manipulation in M4
12782
12783The following macros may be used to manipulate strings in M4.  Many of
12784the macros in this section intentionally result in quoted strings as
12785output, rather than subjecting the arguments to further expansions.  As
12786a result, if you are manipulating text that contains active M4
12787characters, the arguments are passed with single quoting rather than
12788double.
12789
12790@defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12791@defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12792  @ovar{if-uniq}, @ovar{if-duplicate})
12793@msindex{append}
12794@msindex{append_uniq}
12795Redefine @var{macro-name} to its former contents with @var{separator}
12796and @var{string} added at the end.  If @var{macro-name} was undefined
12797before (but not if it was defined but empty), then no @var{separator} is
12798added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12799are expanded during this macro; instead, they are expanded when
12800@var{macro-name} is invoked.
12801
12802@code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12803to grow strings without duplicating substrings.  Additionally,
12804@code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12805@var{if-uniq} is expanded if @var{string} was appended, and
12806@var{if-duplicate} is expanded if @var{string} was already present.
12807Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12808occurs within @var{string}, since that can lead to duplicates.
12809
12810Note that @code{m4_append} can scale linearly in the length of the final
12811string, depending on the quality of the underlying M4 implementation,
12812while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12813If an algorithm can tolerate duplicates in the final string, use the
12814former for speed.  If duplicates must be avoided, consider using
12815@code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12816
12817@example
12818m4_define([active], [ACTIVE])dnl
12819m4_append([sentence], [This is an])dnl
12820m4_append([sentence], [ active ])dnl
12821m4_append([sentence], [symbol.])dnl
12822sentence
12823@result{}This is an ACTIVE symbol.
12824m4_undefine([active])dnl
12825@result{}This is an active symbol.
12826m4_append_uniq([list], [one], [, ], [new], [existing])
12827@result{}new
12828m4_append_uniq([list], [one], [, ], [new], [existing])
12829@result{}existing
12830m4_append_uniq([list], [two], [, ], [new], [existing])
12831@result{}new
12832m4_append_uniq([list], [three], [, ], [new], [existing])
12833@result{}new
12834m4_append_uniq([list], [two], [, ], [new], [existing])
12835@result{}existing
12836list
12837@result{}one, two, three
12838m4_dquote(list)
12839@result{}[one],[two],[three]
12840m4_append([list2], [one], [[, ]])dnl
12841m4_append_uniq([list2], [two], [[, ]])dnl
12842m4_append([list2], [three], [[, ]])dnl
12843list2
12844@result{}one, two, three
12845m4_dquote(list2)
12846@result{}[one, two, three]
12847@end example
12848@end defmac
12849
12850@defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12851@msindex{append_uniq_w}
12852This macro was introduced in Autoconf 2.62.  It is similar to
12853@code{m4_append_uniq}, but treats @var{strings} as a whitespace
12854separated list of words to append, and only appends unique words.
12855@var{macro-name} is updated with a single space between new words.
12856@example
12857m4_append_uniq_w([numbers], [1 1 2])dnl
12858m4_append_uniq_w([numbers], [ 2 3 ])dnl
12859numbers
12860@result{}1 2 3
12861@end example
12862@end defmac
12863
12864@defmac m4_chomp (@var{string})
12865@defmacx m4_chomp_all (@var{string})
12866@msindex{chomp}
12867@msindex{chomp_all}
12868Output @var{string} in quotes, but without a trailing newline.  The
12869macro @code{m4_chomp} is slightly faster, and removes at most one
12870newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12871newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12872and backslash does not influence the result.
12873@end defmac
12874
12875@defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12876  @var{suffix-1}, @ovar{suffix-2}, @dots{})
12877@msindex{combine}
12878This macro produces a quoted string containing the pairwise combination
12879of every element of the quoted, comma-separated @var{prefix-list}, and
12880every element from the @var{suffix} arguments.  Each pairwise
12881combination is joined with @var{infix} in the middle, and successive
12882pairs are joined by @var{separator}.  No expansion occurs on any of the
12883arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12884list is empty, but the lists can contain empty elements.
12885@example
12886m4_define([a], [oops])dnl
12887m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12888@result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12889m4_combine([, ], [[a], [b]], [-])
12890@result{}
12891m4_combine([, ], [[a], [b]], [-], [])
12892@result{}a-, b-
12893m4_combine([, ], [], [-], [1], [2])
12894@result{}
12895m4_combine([, ], [[]], [-], [1], [2])
12896@result{}-1, -2
12897@end example
12898@end defmac
12899
12900@defmac m4_escape (@var{string})
12901@msindex{escape}
12902Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12903within @var{string} into their respective quadrigraphs.  The result is
12904still a quoted string.
12905@end defmac
12906
12907@defmac m4_flatten (@var{string})
12908@msindex{flatten}
12909Flatten @var{string} into a single line.  Delete all backslash-newline
12910pairs, and replace all remaining newlines with a space.  The result is
12911still a quoted string.
12912@end defmac
12913
12914@defmac m4_join (@ovar{separator}, @var{args}@dots{})
12915@defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12916@msindex{join}
12917@msindex{joinall}
12918Concatenate each @var{arg}, separated by @var{separator}.
12919@code{joinall} uses every argument, while @code{join} omits empty
12920arguments so that there are no back-to-back separators in the output.
12921The result is a quoted string.
12922@example
12923m4_define([active], [ACTIVE])dnl
12924m4_join([|], [one], [], [active], [two])
12925@result{}one|active|two
12926m4_joinall([|], [one], [], [active], [two])
12927@result{}one||active|two
12928@end example
12929
12930Note that if all you intend to do is join @var{args} with commas between
12931them, to form a quoted list suitable for @code{m4_foreach}, it is more
12932efficient to use @code{m4_dquote}.
12933@end defmac
12934
12935@defmac m4_newline (@ovar{text})
12936@msindex{newline}
12937This macro was introduced in Autoconf 2.62, and expands to a newline,
12938followed by any @var{text}.
12939It is primarily useful for maintaining macro formatting, and ensuring
12940that M4 does not discard leading whitespace during argument collection.
12941@end defmac
12942
12943@defmac m4_normalize (@var{string})
12944@msindex{normalize}
12945Remove leading and trailing spaces and tabs, sequences of
12946backslash-then-newline, and replace multiple spaces, tabs, and newlines
12947with a single space.  This is a combination of @code{m4_flatten} and
12948@code{m4_strip}.  To determine if @var{string} consists only of bytes
12949that would be removed by @code{m4_normalize}, you can use
12950@code{m4_ifblank}.
12951@end defmac
12952
12953@defmac m4_re_escape (@var{string})
12954@msindex{re_escape}
12955Backslash-escape all characters in @var{string} that are active in
12956regexps.
12957@end defmac
12958
12959@c We cannot use @dvar because the macro expansion mistreats backslashes.
12960@defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12961@msindex{split}
12962Split @var{string} into an M4 list of elements quoted by @samp{[} and
12963@samp{]}, while keeping white space at the beginning and at the end.
12964If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12965If @var{string} is empty, the result is an empty list.
12966@end defmac
12967
12968@defmac m4_strip (@var{string})
12969@msindex{strip}
12970Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12971reduced to a single space, then leading and trailing spaces are removed.
12972The result is still a quoted string.  Note that this does not interfere
12973with newlines; if you want newlines stripped as well, consider
12974@code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12975quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12976@end defmac
12977
12978@defmac m4_text_box (@var{message}, @dvar{frame, -})
12979@msindex{text_box}
12980Add a text box around @var{message}, using @var{frame} as the border
12981character above and below the message.  The @var{frame} argument must be
12982a single byte, and does not support quadrigraphs.
12983The frame correctly accounts for
12984the subsequent expansion of @var{message}.  For example:
12985@example
12986m4_define([macro], [abc])dnl
12987m4_text_box([macro])
12988@result{}## --- ##
12989@result{}## abc ##
12990@result{}## --- ##
12991@end example
12992
12993The @var{message} must contain balanced quotes and parentheses, although
12994quadrigraphs can be used to work around this.
12995@end defmac
12996
12997@defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
12998  @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
12999@msindex{text_wrap}
13000Break @var{string} into a series of whitespace-separated words, then
13001output those words separated by spaces, and wrapping lines any time the
13002output would exceed @var{width} columns.  If given, @var{prefix1} begins
13003the first line, and @var{prefix} begins all wrapped lines.  If
13004@var{prefix1} is longer than @var{prefix}, then the first line consists
13005of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13006padding is inserted so that the first word of @var{string} begins at the
13007same indentation as all wrapped lines.  Note that using literal tab
13008characters in any of the arguments will interfere with the calculation
13009of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13010words of @var{string}, although quadrigraphs are recognized.
13011
13012For some examples:
13013@example
13014m4_text_wrap([Short string */], [   ], [/* ], [20])
13015@result{}/* Short string */
13016m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13017@result{}/* Much longer
13018@result{}   string */
13019m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13020@result{}  --short Short doc.
13021m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13022@result{}  --too-wide
13023@result{}          Short doc.
13024m4_text_wrap([Super long documentation.], [     ],
13025             [  --too-wide ], 30)
13026@result{}  --too-wide
13027@result{}     Super long
13028@result{}     documentation.
13029@end example
13030@end defmac
13031
13032@defmac m4_tolower (@var{string})
13033@defmacx m4_toupper (@var{string})
13034@msindex{tolower}
13035@msindex{toupper}
13036Return @var{string} with letters converted to upper or lower case,
13037respectively.
13038@end defmac
13039
13040@node Number processing Macros
13041@subsection Arithmetic computation in M4
13042
13043The following macros facilitate integer arithmetic operations.
13044Where a parameter is documented as taking an arithmetic expression, you
13045can use anything that can be parsed by @code{m4_eval}.
13046
13047@defmac m4_cmp (@var{expr-1}, @var{expr-2})
13048@msindex{cmp}
13049Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13050expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13051equal, and @samp{1} if @var{expr-1} is larger.
13052@end defmac
13053
13054@defmac m4_list_cmp (@var{list-1}, @var{list-2})
13055@msindex{list_cmp}
13056Compare the two M4 lists consisting of comma-separated arithmetic
13057expressions, left to right.  Expand to @samp{-1} for the first element
13058pairing where the value from @var{list-1} is smaller, @samp{1} where the
13059value from @var{list-2} is smaller, or @samp{0} if both lists have the
13060same values.  If one list is shorter than the other, the remaining
13061elements of the longer list are compared against zero.
13062@example
13063m4_list_cmp([1, 0],       [1])
13064@result{}0
13065m4_list_cmp([1, [1 * 0]], [1, 0])
13066@result{}0
13067m4_list_cmp([1, 2],       [1, 0])
13068@result{}1
13069m4_list_cmp([1, [1+1], 3],[1, 2])
13070@result{}1
13071m4_list_cmp([1, 2, -3],   [1, 2])
13072@result{}-1
13073m4_list_cmp([1, 0],       [1, 2])
13074@result{}-1
13075m4_list_cmp([1],          [1, 2])
13076@result{}-1
13077@end example
13078@end defmac
13079
13080@defmac m4_max (@var{arg}, @dots{})
13081@msindex{max}
13082This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13083of the maximum arithmetic expression among all the arguments.
13084@end defmac
13085
13086@defmac m4_min (@var{arg}, @dots{})
13087@msindex{min}
13088This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13089of the minimum arithmetic expression among all the arguments.
13090@end defmac
13091
13092@defmac m4_sign (@var{expr})
13093@msindex{sign}
13094Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13095@samp{1} if it is positive, and @samp{0} if it is zero.
13096@end defmac
13097
13098@anchor{m4_version_compare}
13099@defmac m4_version_compare (@var{version-1}, @var{version-2})
13100@msindex{version_compare}
13101This macro was introduced in Autoconf 2.53, but had a number of
13102usability limitations that were not lifted until Autoconf 2.62.  Compare
13103the version strings @var{version-1} and @var{version-2}, and expand to
13104@samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13105or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13106of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13107element is a number along with optional case-insensitive letters
13108designating beta releases.  The comparison stops at the leftmost element
13109that contains a difference, although a 0 element compares equal to a
13110missing element.
13111
13112It is permissible to include commit identifiers in @var{version}, such
13113as an abbreviated SHA1 of the commit, provided there is still a
13114monotonically increasing prefix to allow for accurate version-based
13115comparisons.  For example, this paragraph was written when the
13116development snapshot of autoconf claimed to be at version
13117@samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13118abbreviated commit identification of @samp{dc51}.
13119
13120@example
13121m4_version_compare([1.1], [2.0])
13122@result{}-1
13123m4_version_compare([2.0b], [2.0a])
13124@result{}1
13125m4_version_compare([1.1.1], [1.1.1a])
13126@result{}-1
13127m4_version_compare([1.2], [1.1.1a])
13128@result{}1
13129m4_version_compare([1.0], [1])
13130@result{}0
13131m4_version_compare([1.1pre], [1.1PRE])
13132@result{}0
13133m4_version_compare([1.1a], [1,10])
13134@result{}-1
13135m4_version_compare([2.61a], [2.61a-248-dc51])
13136@result{}-1
13137m4_version_compare([2.61b], [2.61a-248-dc51])
13138@result{}1
13139@end example
13140@end defmac
13141
13142@defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13143  @dvar{if-old, m4_fatal})
13144@msindex{version_prereq}
13145Compares @var{version} against the version of Autoconf currently
13146running.  If the running version is at @var{version} or newer, expand
13147@var{if-new-enough}, but if @var{version} is larger than the version
13148currently executing, expand @var{if-old}, which defaults to printing an
13149error message and exiting m4sugar with status 63.  When given only one
13150argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13151Remember that the autoconf philosophy favors feature checks over version
13152checks.
13153@end defmac
13154
13155@node Set manipulation Macros
13156@subsection Set manipulation in M4
13157@cindex Set manipulation
13158@cindex Data structure, set
13159@cindex Unordered set manipulation
13160
13161Sometimes, it is necessary to track a set of data, where the order does
13162not matter and where there are no duplicates in the set.  The following
13163macros facilitate set manipulations.  Each set is an opaque object,
13164which can only be accessed via these basic operations.  The underlying
13165implementation guarantees linear scaling for set creation, which is more
13166efficient than using the quadratic @code{m4_append_uniq}.  Both set
13167names and values can be arbitrary strings, except for unbalanced quotes.
13168This implementation ties up memory for removed elements until the next
13169operation that must traverse all the elements of a set; and although
13170that may slow down some operations until the memory for removed elements
13171is pruned, it still guarantees linear performance.
13172
13173@defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13174@msindex{set_add}
13175Adds the string @var{value} as a member of set @var{set}.  Expand
13176@var{if-uniq} if the element was added, or @var{if-dup} if it was
13177previously in the set.  Operates in amortized constant time, so that set
13178creation scales linearly.
13179@end defmac
13180
13181@defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13182@msindex{set_add_all}
13183Adds each @var{value} to the set @var{set}.  This is slightly more
13184efficient than repeatedly invoking @code{m4_set_add}.
13185@end defmac
13186
13187@defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13188 @ovar{if-absent})
13189@msindex{set_contains}
13190Expands @var{if-present} if the string @var{value} is a member of
13191@var{set}, otherwise @var{if-absent}.
13192
13193@example
13194m4_set_contains([a], [1], [yes], [no])
13195@result{}no
13196m4_set_add([a], [1], [added], [dup])
13197@result{}added
13198m4_set_add([a], [1], [added], [dup])
13199@result{}dup
13200m4_set_contains([a], [1], [yes], [no])
13201@result{}yes
13202m4_set_remove([a], [1], [removed], [missing])
13203@result{}removed
13204m4_set_contains([a], [1], [yes], [no])
13205@result{}no
13206m4_set_remove([a], [1], [removed], [missing])
13207@result{}missing
13208@end example
13209@end defmac
13210
13211@defmac m4_set_contents (@var{set}, @ovar{sep})
13212@defmacx m4_set_dump (@var{set}, @ovar{sep})
13213@msindex{set_contents}
13214@msindex{set_dump}
13215Expands to a single string consisting of all the members of the set
13216@var{set}, each separated by @var{sep}, which is not expanded.
13217@code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13218memory occupied by removed elements, while @code{m4_set_dump} is a
13219faster one-shot action that also deletes the set.  No provision is made
13220for disambiguating members that contain a non-empty @var{sep} as a
13221substring; use @code{m4_set_empty} to distinguish between an empty set
13222and the set containing only the empty string.  The order of the output
13223is unspecified; in the current implementation, part of the speed of
13224@code{m4_set_dump} results from using a different output order than
13225@code{m4_set_contents}.  These macros scale linearly in the size of the
13226set before memory pruning, and @code{m4_set_contents([@var{set}],
13227[@var{sep}])} is faster than
13228@code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13229
13230@example
13231m4_set_add_all([a], [1], [2], [3])
13232@result{}
13233m4_set_contents([a], [-])
13234@result{}1-2-3
13235m4_joinall([-]m4_set_listc([a]))
13236@result{}1-2-3
13237m4_set_dump([a], [-])
13238@result{}3-2-1
13239m4_set_contents([a])
13240@result{}
13241m4_set_add([a], [])
13242@result{}
13243m4_set_contents([a], [-])
13244@result{}
13245@end example
13246@end defmac
13247
13248@defmac m4_set_delete (@var{set})
13249@msindex{set_delete}
13250Delete all elements and memory associated with @var{set}.  This is
13251linear in the set size, and faster than removing one element at a time.
13252@end defmac
13253
13254@defmac m4_set_difference (@var{seta}, @var{setb})
13255@defmacx m4_set_intersection (@var{seta}, @var{setb})
13256@defmacx m4_set_union (@var{seta}, @var{setb})
13257@msindex{set_difference}
13258@msindex{set_intersection}
13259@msindex{set_union}
13260Compute the relation between @var{seta} and @var{setb}, and output the
13261result as a list of quoted arguments without duplicates and with a
13262leading comma.  Set difference selects the elements in @var{seta} but
13263not @var{setb}, intersection selects only elements in both sets, and
13264union selects elements in either set.  These actions are linear in the
13265sum of the set sizes.  The leading comma is necessary to distinguish
13266between no elements and the empty string as the only element.
13267
13268@example
13269m4_set_add_all([a], [1], [2], [3])
13270@result{}
13271m4_set_add_all([b], [3], [], [4])
13272@result{}
13273m4_set_difference([a], [b])
13274@result{},1,2
13275m4_set_difference([b], [a])
13276@result{},,4
13277m4_set_intersection([a], [b])
13278@result{},3
13279m4_set_union([a], [b])
13280@result{},1,2,3,,4
13281@end example
13282@end defmac
13283
13284@defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13285@msindex{set_empty}
13286Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13287expand @var{if-elements}.  This macro operates in constant time.  Using
13288this macro can help disambiguate output from @code{m4_set_contents} or
13289@code{m4_set_list}.
13290@end defmac
13291
13292@defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13293@msindex{set_foreach}
13294For each element in the set @var{set}, expand @var{action} with the
13295macro @var{variable} defined as the set element.  Behavior is
13296unspecified if @var{action} recursively lists the contents of @var{set}
13297(although listing other sets is acceptable), or if it modifies the set
13298in any way other than removing the element currently contained in
13299@var{variable}.  This macro is faster than the corresponding
13300@code{m4_foreach([@var{variable}],
13301m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13302although @code{m4_set_map} might be faster still.
13303
13304@example
13305m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13306@result{}
13307m4_set_contents([a])
13308@result{}12345
13309m4_set_foreach([a], [i],
13310  [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13311@result{}24
13312m4_set_contents([a])
13313@result{}135
13314@end example
13315@end defmac
13316
13317@defmac m4_set_list (@var{set})
13318@defmacx m4_set_listc (@var{set})
13319@msindex{set_list}
13320@msindex{set_listc}
13321Produce a list of arguments, where each argument is a quoted element
13322from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13323by adding a leading comma if there are any set elements, whereas the
13324variant @code{m4_set_list} cannot distinguish between an empty set and a
13325set containing only the empty string.  These can be directly used in
13326macros that take multiple arguments, such as @code{m4_join} or
13327@code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13328take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13329memory occupied by removed elements is reclaimed during these macros.
13330
13331@example
13332m4_set_add_all([a], [1], [2], [3])
13333@result{}
13334m4_set_list([a])
13335@result{}1,2,3
13336m4_set_list([b])
13337@result{}
13338m4_set_listc([b])
13339@result{}
13340m4_count(m4_set_list([b]))
13341@result{}1
13342m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13343@result{}0
13344m4_set_add([b], [])
13345@result{}
13346m4_set_list([b])
13347@result{}
13348m4_set_listc([b])
13349@result{},
13350m4_count(m4_set_list([b]))
13351@result{}1
13352m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13353@result{}1
13354@end example
13355@end defmac
13356
13357@defmac m4_set_map (@var{set}, @var{action})
13358@msindex{set_map}
13359For each element in the set @var{set}, expand @var{action} with a single
13360argument of the set element.  Behavior is unspecified if @var{action}
13361recursively lists the contents of @var{set} (although listing other sets
13362is acceptable), or if it modifies the set in any way other than removing
13363the element passed as an argument.  This macro is faster than either
13364corresponding counterpart of
13365@code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13366@code{m4_set_foreach([@var{set}], [var],
13367[@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13368if more than one argument is needed for @var{action}, although it is
13369more efficient to use @code{m4_set_map_sep} in that case.
13370@end defmac
13371
13372@defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13373@msindex{set_map_sep}
13374For each element in the set @var{set}, expand
13375@code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13376between elements.  Behavior is unspecified if the expansion recursively
13377lists the contents of @var{set} (although listing other sets
13378is acceptable), or if it modifies the set in any way other than removing
13379the element visited by the expansion.  This macro provides the most
13380efficient means for non-destructively visiting the elements of a set; in
13381particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13382to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13383@end defmac
13384
13385@defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13386 @ovar{if-absent})
13387@msindex{set_remove}
13388If @var{value} is an element in the set @var{set}, then remove it and
13389expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13390operates in constant time so that multiple removals will scale linearly
13391rather than quadratically; but when used outside of
13392@code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13393until the set is later
13394compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13395other set operations are then less efficient between the time of element
13396removal and subsequent memory compaction, but still maintain their
13397guaranteed scaling performance.
13398@end defmac
13399
13400@defmac m4_set_size (@var{set})
13401@msindex{set_size}
13402Expand to the size of the set @var{set}.  This implementation operates
13403in constant time, and is thus more efficient than
13404@code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13405@end defmac
13406
13407
13408@node Forbidden Patterns
13409@subsection Forbidden Patterns
13410@cindex Forbidden patterns
13411@cindex Patterns, forbidden
13412
13413M4sugar provides a means to define suspicious patterns, patterns
13414describing tokens which should not be found in the output.  For
13415instance, if an Autoconf @file{configure} script includes tokens such as
13416@samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13417wrong (typically a macro was not evaluated because of overquotation).
13418
13419M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13420Additional layers, such as M4sh and Autoconf, add additional forbidden
13421patterns to the list.
13422
13423@defmac m4_pattern_forbid (@var{pattern})
13424@msindex{pattern_forbid}
13425Declare that no token matching @var{pattern} must be found in the output.
13426Comments are not checked; this can be a problem if, for instance, you
13427have some macro left unexpanded after an @samp{#include}.  No consensus
13428is currently found in the Autoconf community, as some people consider it
13429should be valid to name macros in comments (which doesn't make sense to
13430the authors of this documentation: input, such as macros, should be
13431documented by @samp{dnl} comments; reserving @samp{#}-comments to
13432document the output).
13433@end defmac
13434
13435Of course, you might encounter exceptions to these generic rules, for
13436instance you might have to refer to @samp{$m4_flags}.
13437
13438@defmac m4_pattern_allow (@var{pattern})
13439@msindex{pattern_allow}
13440Any token matching @var{pattern} is allowed, including if it matches an
13441@code{m4_pattern_forbid} pattern.
13442@end defmac
13443
13444@node Debugging via autom4te
13445@section Debugging via autom4te
13446@cindex debugging tips
13447@cindex autom4te debugging tips
13448@cindex m4sugar debugging tips
13449At times, it is desirable to see what was happening inside m4, to see
13450why output was not matching expectations.  However, post-processing done
13451by @command{autom4te} means that directly using the m4 builtin
13452@code{m4_traceon} is likely to interfere with operation.  Also, frequent
13453diversion changes and the concept of forbidden tokens make it difficult
13454to use @code{m4_defn} to generate inline comments in the final output.
13455
13456There are a couple of tools to help with this.  One is the use of the
13457@option{--trace} option provided by @command{autom4te} (as well as each
13458of the programs that wrap @command{autom4te}, such as
13459@command{autoconf}), in order to inspect when a macro is called and with
13460which arguments.  For example, when this paragraph was written, the
13461autoconf version could be found by:
13462
13463@example
13464$ @kbd{autoconf --trace=AC_INIT}
13465configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13466$ @kbd{autoconf --trace='AC_INIT:version is $2'}
13467version is 2.63b.95-3963
13468@end example
13469
13470Another trick is to print out the expansion of various m4 expressions to
13471standard error or to an independent file, with no further m4 expansion,
13472and without interfering with diversion changes or the post-processing
13473done to standard output.  @code{m4_errprintn} shows a given expression
13474on standard error.  For example, if you want to see the expansion of an
13475autoconf primitive or of one of your autoconf macros, you can do it like
13476this:
13477
13478@example
13479$ @kbd{cat <<\EOF > configure.ac}
13480AC_INIT
13481m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13482m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13483AC_OUTPUT
13484EOF
13485$ @kbd{autoconf}
13486@error{}The definition of AC_DEFINE_UNQUOTED:
13487@error{}_AC_DEFINE_Q([], $@@)
13488@end example
13489
13490@node Programming in M4sh
13491@chapter Programming in M4sh
13492
13493M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13494scripts.  This name was coined by Lars J. Aas, who notes that,
13495according to the Webster's Revised Unabridged Dictionary (1913):
13496
13497@quotation
13498Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13499wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13500
13501@enumerate 1
13502@item
13503A mass of mixed ingredients reduced to a soft pulpy state by beating or
13504pressure@enddots{}
13505
13506@item
13507A mixture of meal or bran and water fed to animals.
13508
13509@item
13510A mess; trouble.  [Obs.] --Beau.@: & Fl.
13511@end enumerate
13512@end quotation
13513
13514M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13515the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13516and environment variable namespace @samp{^as_}, and the here-document
13517delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13518define your own macros or output shell code that conflicts with these
13519namespaces.
13520
13521@menu
13522* Common Shell Constructs::     Portability layer for common shell constructs
13523* Polymorphic Variables::       Support for indirect variable names
13524* Initialization Macros::       Macros to establish a sane shell environment
13525* File Descriptor Macros::      File descriptor macros for input and output
13526@end menu
13527
13528@node Common Shell Constructs
13529@section Common Shell Constructs
13530
13531M4sh provides portable alternatives for some common shell constructs
13532that unfortunately are not portable in practice.
13533
13534@c Deprecated, to be replaced by a better API
13535@ignore
13536@defmac AS_BASENAME (@var{file-name})
13537@asindex{BASENAME}
13538Output the non-directory portion of @var{file-name}.  For example,
13539if @code{$file} is @samp{/one/two/three}, the command
13540@code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13541@end defmac
13542@end ignore
13543
13544@defmac AS_BOX (@var{text}, @dvar{char, -})
13545@asindex{BOX}
13546Expand into shell code that will output @var{text} surrounded by a box
13547with @var{char} in the top and bottom border.  @var{text} should not
13548contain a newline, but may contain shell expansions valid for unquoted
13549here-documents.  @var{char} defaults to @samp{-}, but can be any
13550character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13551@samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13552log files to separate distinct phases of script operation.
13553@end defmac
13554
13555@defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13556  @dots{}, @ovar{default})
13557@asindex{CASE}
13558Expand into a shell @samp{case} statement, where @var{word} is matched
13559against one or more patterns.  @var{if-matched} is run if the
13560corresponding pattern matched @var{word}, else @var{default} is run.
13561Avoids several portability issues (@pxref{case, , Limitations of Shell
13562Builtins}).
13563@end defmac
13564
13565@c Deprecated, to be replaced by a better API
13566@defmac AS_DIRNAME (@var{file-name})
13567@asindex{DIRNAME}
13568Output the directory portion of @var{file-name}.  For example,
13569if @code{$file} is @samp{/one/two/three}, the command
13570@code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13571
13572This interface may be improved in the future to avoid forks and losing
13573trailing newlines.
13574@end defmac
13575
13576@defmac AS_ECHO (@var{word})
13577@asindex{ECHO}
13578Emits @var{word} to the standard output, followed by a newline.  @var{word}
13579must be a single shell word (typically a quoted string).  The bytes of
13580@var{word} are output as-is, even if it starts with "-" or contains "\".
13581Redirections can be placed outside the macro invocation.  This is much
13582more portable than using @command{echo} (@pxref{echo, , Limitations of
13583Shell Builtins}).
13584@end defmac
13585
13586@defmac AS_ECHO_N (@var{word})
13587@asindex{ECHO_N}
13588Emits @var{word} to the standard output, without a following newline.
13589@var{word} must be a single shell word (typically a quoted string) and,
13590for portability, should not include more than one newline.  The bytes of
13591@var{word} are output as-is, even if it starts with "-" or contains "\".
13592Redirections can be placed outside the macro invocation.
13593@end defmac
13594
13595@c We cannot use @dvar because the macro expansion mistreats backslashes.
13596@defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13597@asindex{ESCAPE}
13598Expands to @var{string}, with any characters in @var{chars} escaped with
13599a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13600and only contain characters from the set @samp{`\"$}; however,
13601characters may be safely listed more than once in @var{chars} for the
13602sake of syntax highlighting editors.  The current implementation expands
13603@var{string} after adding escapes; if @var{string} contains macro calls
13604that in turn expand to text needing shell quoting, you can use
13605@code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13606
13607The default for @var{chars} (@samp{\"$`}) is the set of characters
13608needing escapes when @var{string} will be used literally within double
13609quotes.  One common variant is the set of characters to protect when
13610@var{string} will be used literally within back-ticks or an unquoted
13611here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13612be used to form a double-quoted string containing the same expansions
13613that would have occurred if @var{string} were expanded in an unquoted
13614here-document; however, when using this variant, care must be taken that
13615@var{string} does not use double quotes within complex variable
13616expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13617with improper escapes.
13618
13619This macro is often used with @code{AS_ECHO}.  For an example, observe
13620the output generated by the shell code generated from this snippet:
13621
13622@example
13623foo=bar
13624AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13625@result{}"$foo" = "bar"
13626m4_define([macro], [a, [\b]])
13627AS_ECHO(["AS_ESCAPE([[macro]])"])
13628@result{}macro
13629AS_ECHO(["AS_ESCAPE([macro])"])
13630@result{}a, b
13631AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13632@result{}a, \b
13633@end example
13634
13635@comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13636@comment the case of @var{string} that does not contain '.
13637To escape a string that will be placed within single quotes, use:
13638
13639@example
13640m4_bpatsubst([[@var{string}]], ['], ['\\''])
13641@end example
13642@end defmac
13643
13644@defmac AS_EXECUTABLE_P (@var{file})
13645@asindex{EXECUTABLE_P}
13646Emit code to probe whether @var{file} is a regular file with executable
13647permissions (and not a directory with search permissions).  The caller
13648is responsible for quoting @var{file}.
13649@end defmac
13650
13651@defmac AS_EXIT (@dvar{status, $?})
13652@asindex{EXIT}
13653Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13654This macro
13655works around shells that see the exit status of the command prior to
13656@code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13657of Shell Builtins}).
13658@end defmac
13659
13660@defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13661@asindex{IF}
13662Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13663run shell code @var{run-if-true1}, else examine further tests.  If no test
13664exits with a zero status, run shell code @var{run-if-false}, with
13665simplifications if either @var{run-if-true1} or @var{run-if-false}
13666is empty.  For example,
13667
13668@example
13669AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13670      [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13671      [echo foo not specified])
13672@end example
13673
13674@noindent
13675ensures any required macros of @code{HANDLE_FOO}
13676are expanded before the first test.
13677@end defmac
13678
13679@defmac AS_MKDIR_P (@var{file-name})
13680@asindex{MKDIR_P}
13681Make the directory @var{file-name}, including intervening directories
13682as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13683except that it is portable to older versions of @command{mkdir} that
13684lack support for the @option{-p} option or for the @option{--}
13685delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13686@code{AS_MKDIR_P}
13687succeeds if @var{file-name} is a symbolic link to an existing directory,
13688even though Posix is unclear whether @samp{mkdir -p} should
13689succeed in that case.  If creation of @var{file-name} fails, exit the
13690script.
13691
13692Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13693@end defmac
13694
13695@defmac AS_SET_STATUS (@var{status})
13696@asindex{SET_STATUS}
13697Emit shell code to set the value of @samp{$?} to @var{status}, as
13698efficiently as possible.  However, this is not guaranteed to abort a
13699shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13700Builtins}).  This should also be used at the end of a complex shell
13701function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13702a DJGPP shell bug.
13703@end defmac
13704
13705@defmac AS_TR_CPP (@var{expression})
13706@asindex{TR_CPP}
13707Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13708For example:
13709
13710@example
13711# This outputs "#define HAVE_CHAR_P 1".
13712# Notice the m4 quoting around #, to prevent an m4 comment
13713type="char *"
13714echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13715@end example
13716@end defmac
13717
13718@defmac AS_TR_SH (@var{expression})
13719@asindex{TR_SH}
13720Transform @var{expression} into shell code that generates a valid shell
13721variable name.  The result is literal when possible at m4 time, but must
13722be used with @code{eval} if @var{expression} causes shell indirections.
13723For example:
13724
13725@example
13726# This outputs "Have it!".
13727header="sys/some file.h"
13728eval AS_TR_SH([HAVE_$header])=yes
13729if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13730@end example
13731@end defmac
13732
13733@defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13734@asindex{SET_CATFILE}
13735Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13736but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13737@var{file} is absolute, etc.).
13738@end defmac
13739
13740@defmac AS_UNSET (@var{var})
13741@asindex{UNSET}
13742Unsets the shell variable @var{var}, working around bugs in older
13743shells (@pxref{unset, , Limitations of Shell
13744Builtins}).  @var{var} can be a literal or indirect variable name.
13745@end defmac
13746
13747@defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13748  @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13749@asindex{VERSION_COMPARE}
13750Compare two strings @var{version-1} and @var{version-2}, possibly
13751containing shell variables, as version strings, and expand
13752@var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13753depending upon the result.
13754The algorithm to compare is similar to the one used by strverscmp in
13755glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13756The GNU C Library}).
13757@end defmac
13758
13759@node Polymorphic Variables
13760@section Support for indirect variable names
13761@cindex variable name indirection
13762@cindex polymorphic variable name
13763@cindex indirection, variable name
13764
13765Often, it is convenient to write a macro that will emit shell code
13766operating on a shell variable.  The simplest case is when the variable
13767name is known.  But a more powerful idiom is writing shell code that can
13768work through an indirection, where another variable or command
13769substitution produces the name of the variable to actually manipulate.
13770M4sh supports the notion of polymorphic shell variables, making it easy
13771to write a macro that can deal with either literal or indirect variable
13772names and output shell code appropriate for both use cases.  Behavior is
13773undefined if expansion of an indirect variable does not result in a
13774literal variable name.
13775
13776@defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13777  @dvar{if-simple-ref, @var{if-not}})
13778@defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13779  @ovar{if-not}, @dvar{if-simple-ref, @var{if-not}})
13780@asindex{LITERAL_IF}
13781@asindex{LITERAL_WORD_IF}
13782If the expansion of @var{expression} is definitely a shell literal,
13783expand @var{if-literal}.  If the expansion of @var{expression} looks
13784like it might contain shell indirections (such as @code{$var} or
13785@code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13786possible to output optimized code if @var{expression} consists only of
13787shell variable expansions (such as @code{$@{var@}}), in which case
13788@var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13789should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13790@var{if-literal} if @var{expression} looks like a single shell word,
13791containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13792in @var{expression}.
13793
13794In order to reduce the time spent recognizing whether an
13795@var{expression} qualifies as a literal or a simple indirection, the
13796implementation is somewhat conservative: @var{expression} must be a
13797single shell word (possibly after stripping whitespace), consisting only
13798of bytes that would have the same meaning whether unquoted or enclosed
13799in double quotes (for example, @samp{a.b} results in @var{if-literal},
13800even though it is not a valid shell variable name; while both @samp{'a'}
13801and @samp{[$]} result in @var{if-not}, because they behave differently
13802than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13803for recognizing portable file names (such as in the implementation of
13804@code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13805valid variable names (such as in the implementation of @code{AS_TR_SH},
13806which uses an additional @code{m4_translit} to convert @samp{.} to
13807@samp{_}).
13808
13809This example shows how to read the contents of the shell variable
13810@code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13811results in a script that will output the line @samp{hello} three times.
13812
13813@example
13814AC_DEFUN([MY_ACTION],
13815[AS_LITERAL_IF([$1],
13816  [echo "$$1"],
13817@c $$
13818  [AS_VAR_COPY([var], [$1])
13819   echo "$var"],
13820  [eval 'echo "$'"$1"\"])])
13821foo=bar bar=hello
13822MY_ACTION([bar])
13823MY_ACTION([`echo bar`])
13824MY_ACTION([$foo])
13825@end example
13826@end defmac
13827
13828@defmac AS_VAR_APPEND (@var{var}, @var{text})
13829@asindex{VAR_APPEND}
13830Emit shell code to append the shell expansion of @var{text} to the end
13831of the current contents of the polymorphic shell variable @var{var},
13832taking advantage of shells that provide the @samp{+=} extension for more
13833efficient scaling.
13834
13835For situations where the final contents of @var{var} are relatively
13836short (less than 256 bytes), it is more efficient to use the simpler
13837code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13838polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13839@code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13840when the script will be repeatedly appending text into @code{var},
13841issues of scaling start to become apparent.  A naive implementation
13842requires execution time linear to the length of the current contents of
13843@var{var} as well as the length of @var{text} for a single append, for
13844an overall quadratic scaling with multiple appends.  This macro takes
13845advantage of shells which provide the extension
13846@code{@var{var}+=@var{text}}, which can provide amortized constant time
13847for a single append, for an overall linear scaling with multiple
13848appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13849@var{text} be quoted properly to avoid field splitting and file name
13850expansion.
13851@end defmac
13852
13853@defmac AS_VAR_ARITH (@var{var}, @var{expression})
13854@asindex{VAR_ARITH}
13855Emit shell code to compute the arithmetic expansion of @var{expression},
13856assigning the result as the contents of the polymorphic shell variable
13857@var{var}.  The code takes advantage of shells that provide @samp{$(())}
13858for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13859syntax for a valid @var{expression} is rather limited: all operators
13860must occur as separate shell arguments and with proper quoting, there is
13861no portable equality operator, all variables containing numeric values
13862must be expanded prior to the computation, all numeric values must be
13863provided in decimal without leading zeroes, and the first shell argument
13864should not be a negative number.  In the following example, this snippet
13865will print @samp{(2+3)*4 == 20}.
13866
13867@example
13868bar=3
13869AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13870echo "(2+$bar)*4 == $foo"
13871@end example
13872@end defmac
13873
13874@defmac AS_VAR_COPY (@var{dest}, @var{source})
13875@asindex{VAR_COPY}
13876Emit shell code to assign the contents of the polymorphic shell variable
13877@var{source} to the polymorphic shell variable @var{dest}.  For example,
13878executing this M4sh snippet will output @samp{bar hi}:
13879
13880@example
13881foo=bar bar=hi
13882AS_VAR_COPY([a], [foo])
13883AS_VAR_COPY([b], [$foo])
13884echo "$a $b"
13885@end example
13886
13887When it is necessary to access the contents of an indirect variable
13888inside a shell double-quoted context, the recommended idiom is to first
13889copy the contents into a temporary literal shell variable.
13890
13891@smallexample
13892for header in stdint_h inttypes_h ; do
13893  AS_VAR_COPY([var], [ac_cv_header_$header])
13894  echo "$header detected: $var"
13895done
13896@end smallexample
13897@end defmac
13898
13899@comment AS_VAR_GET is intentionally undocumented; it can't handle
13900@comment trailing newlines uniformly, and forks too much.
13901
13902@defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13903  @ovar{if-not-equal})
13904@asindex{VAR_IF}
13905Output a shell conditional statement.  If the contents of the
13906polymorphic shell variable @var{var} match the string @var{word},
13907execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13908must be a single shell word (typically a quoted string).  Avoids
13909shell bugs if an interrupt signal arrives while a command substitution
13910in @var{var} is being expanded.
13911@end defmac
13912
13913@defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13914@defmacx AS_VAR_POPDEF (@var{m4-name})
13915@asindex{VAR_PUSHDEF}
13916@asindex{VAR_POPDEF}
13917@cindex composing variable names
13918@cindex variable names, composing
13919A common M4sh idiom involves composing shell variable names from an m4
13920argument (for example, writing a macro that uses a cache variable).
13921@var{value} can be an arbitrary string, which will be transliterated
13922into a valid shell name by @code{AS_TR_SH}.  In order to access the
13923composed variable name based on @var{value}, it is easier to declare a
13924temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13925that macro as the argument to subsequent @code{AS_VAR} macros as a
13926polymorphic variable name, and finally free the temporary macro with
13927@code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13928to avoid excess newlines in the output.
13929
13930Here is an involved example, that shows the power of writing macros that
13931can handle composed shell variable names:
13932
13933@example
13934m4_define([MY_CHECK_HEADER],
13935[AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13936AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13937AS_VAR_POPDEF([my_Header])dnl
13938])
13939MY_CHECK_HEADER([stdint.h])
13940for header in inttypes.h stdlib.h ; do
13941  MY_CHECK_HEADER([$header])
13942done
13943@end example
13944
13945@noindent
13946In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13947variable names.  In the first invocation, the m4 argument is
13948@code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13949As a result, the temporary macro @code{my_Header} expands to the literal
13950shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13951m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13952temporary macro @code{my_Header} expands to the indirect shell name
13953@samp{$as_my_Header}.  During the shell execution of the for loop, when
13954@samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13955contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13956platform where all three headers have been previously detected, the
13957output of the script will include:
13958
13959@smallexample
13960header stdint.h detected
13961header inttypes.h detected
13962header stdlib.h detected
13963@end smallexample
13964@end defmac
13965
13966@defmac AS_VAR_SET (@var{var}, @ovar{value})
13967@asindex{VAR_SET}
13968Emit shell code to assign the contents of the polymorphic shell variable
13969@var{var} to the shell expansion of @var{value}.  @var{value} is not
13970subject to field splitting or file name expansion, so if command
13971substitution is used, it may be done with @samp{`""`} rather than using
13972an intermediate variable (@pxref{Shell Substitutions}).  However,
13973@var{value} does undergo rescanning for additional macro names; behavior
13974is unspecified if late expansion results in any shell meta-characters.
13975@end defmac
13976
13977@defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13978@asindex{VAR_SET_IF}
13979Emit a shell conditional statement, which executes @var{if-set} if the
13980polymorphic shell variable @code{var} is set to any value, and
13981@var{if-undef} otherwise.
13982@end defmac
13983
13984@defmac AS_VAR_TEST_SET (@var{var})
13985@asindex{VAR_TEST_SET}
13986Emit a shell statement that results in a successful exit status only if
13987the polymorphic shell variable @code{var} is set.
13988@end defmac
13989
13990@node Initialization Macros
13991@section Initialization Macros
13992
13993@defmac AS_BOURNE_COMPATIBLE
13994@asindex{BOURNE_COMPATIBLE}
13995Set up the shell to be more compatible with the Bourne shell as
13996standardized by Posix, if possible.  This may involve setting
13997environment variables, or setting options, or similar
13998implementation-specific actions.  This macro is deprecated, since
13999@code{AS_INIT} already invokes it.
14000@end defmac
14001
14002@defmac AS_INIT
14003@asindex{INIT}
14004@evindex LC_ALL
14005@evindex SHELL
14006Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14007outputs the @code{#! /bin/sh} line, a notice about where the output was
14008generated from, and code to sanitize the environment for the rest of the
14009script.  Among other initializations, this sets @env{SHELL} to the shell
14010chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14011ensure the C locale.  Finally, it changes the current diversion to
14012@code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14013and @code{AT_INIT}, so shell code in @file{configure},
14014@file{config.status}, and @file{testsuite} all benefit from a sanitized
14015shell environment.
14016@end defmac
14017
14018@defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14019@asindex{INIT_GENERATED}
14020Emit shell code to start the creation of a subsidiary shell script in
14021@var{file}, including changing @var{file} to be executable.  This macro
14022populates the child script with information learned from the parent
14023(thus, the emitted code is equivalent in effect, but more efficient,
14024than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14025@code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14026beginning of the child, prior to the shell initialization code, and is
14027subject to parameter expansion, command substitution, and backslash
14028quote removal.  The
14029parent script should check the exit status after this macro, in case
14030@var{file} could not be properly created (for example, if the disk was
14031full).  If successfully created, the parent script can then proceed to
14032append additional M4sh constructs into the child script.
14033
14034Note that the child script starts life without a log file open, so if
14035the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14036must temporarily disable any attempts to use the log file until after
14037emitting code to open a log within the child.  On the other hand, if the
14038parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14039@samp{1}, then the child script already has code that copies stdout to
14040that descriptor.  Currently, the suggested
14041idiom for writing a M4sh shell script from within another script is:
14042
14043@example
14044AS_INIT_GENERATED([@var{file}], [[# My child script.
14045]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14046m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14047cat >> "@var{file}" <<\__EOF__
14048# Code to initialize AS_MESSAGE_LOG_FD
14049m4_popdef([AS_MESSAGE_LOG_FD])dnl
14050# Additional code
14051__EOF__
14052@end example
14053
14054This, however, may change in the future as the M4sh interface is
14055stabilized further.
14056
14057Also, be aware that use of @env{LINENO} within the child script may
14058report line numbers relative to their location in the parent script,
14059even when using @code{AS_LINENO_PREPARE}, if the parent script was
14060unable to locate a shell with working @env{LINENO} support.
14061@end defmac
14062
14063@defmac AS_LINENO_PREPARE
14064@asindex{LINENO_PREPARE}
14065@evindex LINENO
14066Find a shell that supports the special variable @env{LINENO}, which
14067contains the number of the currently executing line.  This macro is
14068automatically invoked by @code{AC_INIT} in configure scripts.
14069@end defmac
14070
14071@defmac AS_ME_PREPARE
14072@asindex{ME_PREPARE}
14073Set up variable @env{as_me} to be the basename of the currently executing
14074script.  This macro is automatically invoked by @code{AC_INIT} in
14075configure scripts.
14076@end defmac
14077
14078@defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14079@asindex{TMPDIR}
14080@evindex TMPDIR
14081@ovindex tmp
14082Create, as safely as possible, a temporary sub-directory within
14083@var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14084be 2-4 characters, to make it slightly easier to identify the owner of
14085the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14086will be used (defaulting to @samp{/tmp}).  On success, the name of the
14087newly created directory is stored in the shell variable @code{tmp}.  On
14088error, the script is aborted.
14089
14090Typically, this macro is coupled with some exit traps to delete the created
14091directory and its contents on exit or interrupt.  However, there is a
14092slight window between when the directory is created and when the name is
14093actually known to the shell, so an interrupt at the right moment might
14094leave the temporary directory behind.  Hence it is important to use a
14095@var{prefix} that makes it easier to determine if a leftover temporary
14096directory from an interrupted script is safe to delete.
14097
14098The use of the output variable @samp{$tmp} rather than something in the
14099@samp{as_} namespace is historical; it has the unfortunate consequence
14100that reusing this otherwise common name for any other purpose inside
14101your script has the potential to break any cleanup traps designed to
14102remove the temporary directory.
14103@end defmac
14104
14105@defmac AS_SHELL_SANITIZE
14106@asindex{SHELL_SANITIZE}
14107Initialize the shell suitably for @command{configure} scripts.  This has
14108the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14109environment variables for predictable results from configuration tests.
14110For example, it sets @env{LC_ALL} to change to the default C locale.
14111@xref{Special Shell Variables}.  This macro is deprecated, since
14112@code{AS_INIT} already invokes it.
14113@end defmac
14114
14115
14116@node File Descriptor Macros
14117@section File Descriptor Macros
14118@cindex input
14119@cindex standard input
14120@cindex file descriptors
14121@cindex descriptors
14122@cindex low-level output
14123@cindex output, low-level
14124
14125The following macros define file descriptors used to output messages
14126(or input values) from @file{configure} scripts.
14127For example:
14128
14129@example
14130echo "$wombats found" >&AS_MESSAGE_LOG_FD
14131echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14132read kangaroos <&AS_ORIGINAL_STDIN_FD`
14133@end example
14134
14135@noindent
14136However doing so is seldom needed, because Autoconf provides higher
14137level macros as described below.
14138
14139@defmac AS_MESSAGE_FD
14140@asindex{MESSAGE_FD}
14141The file descriptor for @samp{checking for...}  messages and results.
14142By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14143clients.  However, @code{AC_INIT} shuffles things around to another file
14144descriptor, in order to allow the @option{-q} option of
14145@command{configure} to choose whether messages should go to the script's
14146standard output or be discarded.
14147
14148If you want to display some messages, consider using one of the printing
14149macros (@pxref{Printing Messages}) instead.  Copies of messages output
14150via these macros are also recorded in @file{config.log}.
14151@end defmac
14152
14153@anchor{AS_MESSAGE_LOG_FD}
14154@defmac AS_MESSAGE_LOG_FD
14155@asindex{MESSAGE_LOG_FD}
14156This must either be empty, or expand to a file descriptor for log
14157messages.  By default, @code{AS_INIT} sets this macro to the empty
14158string for standalone M4sh clients, thus disabling logging.  However,
14159@code{AC_INIT} shuffles things around so that both @command{configure}
14160and @command{config.status} use @file{config.log} for log messages.
14161Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14162Compiler}), redirect all output to this descriptor.  You may want to do
14163so if you develop such a low-level macro.
14164@end defmac
14165
14166@defmac AS_ORIGINAL_STDIN_FD
14167@asindex{ORIGINAL_STDIN_FD}
14168This must expand to a file descriptor for the original standard input.
14169By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14170M4sh clients.  However, @code{AC_INIT} shuffles things around for
14171safety.
14172
14173When @command{configure} runs, it may accidentally execute an
14174interactive command that has the same name as the non-interactive meant
14175to be used or checked.  If the standard input was the terminal, such
14176interactive programs would cause @command{configure} to stop, pending
14177some user input.  Therefore @command{configure} redirects its standard
14178input from @file{/dev/null} during its initialization.  This is not
14179normally a problem, since @command{configure} normally does not need
14180user input.
14181
14182In the extreme case where your @file{configure} script really needs to
14183obtain some values from the original standard input, you can read them
14184explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14185@end defmac
14186
14187
14188@c =================================================== Writing Autoconf Macros.
14189
14190@node Writing Autoconf Macros
14191@chapter Writing Autoconf Macros
14192
14193When you write a feature test that could be applicable to more than one
14194software package, the best thing to do is encapsulate it in a new macro.
14195Here are some instructions and guidelines for writing Autoconf macros.
14196
14197@menu
14198* Macro Definitions::           Basic format of an Autoconf macro
14199* Macro Names::                 What to call your new macros
14200* Reporting Messages::          Notifying @command{autoconf} users
14201* Dependencies Between Macros::  What to do when macros depend on other macros
14202* Obsoleting Macros::           Warning about old ways of doing things
14203* Coding Style::                Writing Autoconf macros @`a la Autoconf
14204@end menu
14205
14206@node Macro Definitions
14207@section Macro Definitions
14208
14209@defmac AC_DEFUN (@var{name}, @ovar{body})
14210@acindex{DEFUN}
14211Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14212similar to the M4 builtin @code{m4_define} macro; this creates a macro
14213named @var{name} and with @var{body} as its expansion.  In addition to
14214defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14215constrain the order in which macros are called, while avoiding redundant
14216output (@pxref{Prerequisite Macros}).
14217@end defmac
14218
14219An Autoconf macro definition looks like this:
14220
14221@example
14222AC_DEFUN(@var{macro-name}, @var{macro-body})
14223@end example
14224
14225You can refer to any arguments passed to the macro as @samp{$1},
14226@samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
14227GNU M4}, for more complete information on writing M4 macros.
14228
14229Most macros fall in one of two general categories.  The first category
14230includes macros which take arguments, in order to generate output
14231parameterized by those arguments.  Macros in this category are designed
14232to be directly expanded, often multiple times, and should not be used as
14233the argument to @code{AC_REQUIRE}.  The other category includes macros
14234which are shorthand for a fixed block of text, and therefore do not take
14235arguments.  For this category of macros, directly expanding the macro
14236multiple times results in redundant output, so it is more common to use
14237the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14238with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14239
14240Be sure to properly quote both the @var{macro-body} @emph{and} the
14241@var{macro-name} to avoid any problems if the macro happens to have
14242been previously defined.
14243
14244Each macro should have a header comment that gives its prototype, and a
14245brief description.  When arguments have default values, display them in
14246the prototype.  For example:
14247
14248@example
14249# AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14250# --------------------------------------
14251m4_define([AC_MSG_ERROR],
14252  [@{ AS_MESSAGE([error: $1], [2])
14253     exit m4_default([$2], [1]); @}])
14254@end example
14255
14256Comments about the macro should be left in the header comment.  Most
14257other comments make their way into @file{configure}, so just keep
14258using @samp{#} to introduce comments.
14259
14260@cindex @code{dnl}
14261If you have some special comments about pure M4 code, comments
14262that make no sense in @file{configure} and in the header comment, then
14263use the builtin @code{dnl}: it causes M4 to discard the text
14264through the next newline.
14265
14266Keep in mind that @code{dnl} is rarely needed to introduce comments;
14267@code{dnl} is more useful to get rid of the newlines following macros
14268that produce no output, such as @code{AC_REQUIRE}.
14269
14270Public third-party macros need to use @code{AC_DEFUN}, and not
14271@code{m4_define}, in order to be found by @command{aclocal}
14272(@pxref{Extending aclocal,,, automake, GNU Automake}).
14273Additionally, if it is ever determined that a macro should be made
14274obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14275in order to have @command{autoupdate} assist the user in choosing a
14276better alternative, but there is no corresponding way to make
14277@code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14278
14279There is another subtle, but important, difference between using
14280@code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14281@code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14282block of text with a @code{m4_define} macro that will expand to the same
14283text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14284the same content does not necessarily give the same results, because it
14285changes the location where any embedded but unsatisfied
14286@code{AC_REQUIRE} invocations within the block will be expanded.  For an
14287example of this, see @ref{Expanded Before Required}.
14288
14289@node Macro Names
14290@section Macro Names
14291
14292All of the public Autoconf macros have all-uppercase names in the
14293namespace @samp{^AC_} to prevent them from accidentally conflicting with
14294other text; Autoconf also reserves the namespace @samp{^_AC_} for
14295internal macros.  All shell variables that they use for internal
14296purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14297also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14298@command{configure}, files produced by Autoconf make heavy use of the
14299file system namespace @samp{^conf}.
14300
14301Since Autoconf is built on top of M4sugar (@pxref{Programming in
14302M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14303of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14304@file{configure.ac} is also designed to be scanned by Autoheader,
14305Autoscan, Autoupdate, and Automake, you should be aware of the
14306@samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14307the namespace of a package that does not own the macro or shell code you
14308are writing.
14309
14310To ensure that your macros don't conflict with present or future
14311Autoconf macros, you should prefix your own macro names and any shell
14312variables they use with some other sequence.  Possibilities include your
14313initials, or an abbreviation for the name of your organization or
14314software package.  Historically, people have not always followed the
14315rule of using a namespace appropriate for their package, and this has
14316made it difficult for determining the origin of a macro (and where to
14317report bugs about that macro), as well as difficult for the true
14318namespace owner to add new macros without interference from pre-existing
14319uses of third-party macros.  Perhaps the best example of this confusion
14320is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14321to Gettext.
14322
14323Most of the Autoconf macros' names follow a structured naming convention
14324that indicates the kind of feature check by the name.  The macro names
14325consist of several words, separated by underscores, going from most
14326general to most specific.  The names of their cache variables use the
14327same convention (@pxref{Cache Variable Names}, for more information on
14328them).
14329
14330The first word of the name after the namespace initials (such as
14331@samp{AC_}) usually tells the category
14332of the feature being tested.  Here are the categories used in Autoconf for
14333specific test macros, the kind of macro that you are more likely to
14334write.  They are also used for cache variables, in all-lowercase.  Use
14335them where applicable; where they're not, invent your own categories.
14336
14337@table @code
14338@item C
14339C language builtin features.
14340@item DECL
14341Declarations of C variables in header files.
14342@item FUNC
14343Functions in libraries.
14344@item GROUP
14345Posix group owners of files.
14346@item HEADER
14347Header files.
14348@item LIB
14349C libraries.
14350@item PROG
14351The base names of programs.
14352@item MEMBER
14353Members of aggregates.
14354@item SYS
14355Operating system features.
14356@item TYPE
14357C builtin or declared types.
14358@item VAR
14359C variables in libraries.
14360@end table
14361
14362After the category comes the name of the particular feature being
14363tested.  Any further words in the macro name indicate particular aspects
14364of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
14365C compiler supports ISO Standard C.
14366
14367An internal macro should have a name that starts with an underscore;
14368Autoconf internals should therefore start with @samp{_AC_}.
14369Additionally, a macro that is an internal subroutine of another macro
14370should have a name that starts with an underscore and the name of that
14371other macro, followed by one or more words saying what the internal
14372macro does.  For example, @code{AC_PATH_X} has internal macros
14373@code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14374
14375@node Reporting Messages
14376@section Reporting Messages
14377@cindex Messages, from @command{autoconf}
14378
14379When macros statically diagnose abnormal situations, benign or fatal, it
14380is possible to make @command{autoconf} detect the problem, and refuse to
14381create @file{configure} in the case of an error.  The macros in this
14382section are considered obsolescent, and new code should use M4sugar
14383macros for this purpose, see @ref{Diagnostic Macros}.
14384
14385On the other hand, it is possible to want to detect errors when
14386@command{configure} is run, which are dependent on the environment of
14387the user rather than the maintainer.  For dynamic diagnostics, see
14388@ref{Printing Messages}.
14389
14390@defmac AC_DIAGNOSE (@var{category}, @var{message})
14391@acindex{DIAGNOSE}
14392Report @var{message} as a warning (or as an error if requested by the
14393user) if warnings of the @var{category} are turned on.  This macro is
14394obsolescent; you are encouraged to use:
14395@example
14396m4_warn([@var{category}], [@var{message}])
14397@end example
14398@noindent
14399instead.  @xref{m4_warn}, for more details, including valid
14400@var{category} names.
14401@end defmac
14402
14403@defmac AC_WARNING (@var{message})
14404@acindex{WARNING}
14405Report @var{message} as a syntax warning.  This macro is obsolescent;
14406you are encouraged to use:
14407@example
14408m4_warn([syntax], [@var{message}])
14409@end example
14410@noindent
14411instead.  @xref{m4_warn}, for more details, as well as better
14412finer-grained categories of warnings (not all problems have to do with
14413syntax).
14414@end defmac
14415
14416@defmac AC_FATAL (@var{message})
14417@acindex{FATAL}
14418Report a severe error @var{message}, and have @command{autoconf} die.
14419This macro is obsolescent; you are encouraged to use:
14420@example
14421m4_fatal([@var{message}])
14422@end example
14423@noindent
14424instead.  @xref{m4_fatal}, for more details.
14425@end defmac
14426
14427When the user runs @samp{autoconf -W error}, warnings from
14428@code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14429@code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14430
14431@node Dependencies Between Macros
14432@section Dependencies Between Macros
14433@cindex Dependencies between macros
14434
14435Some Autoconf macros depend on other macros having been called first in
14436order to work correctly.  Autoconf provides a way to ensure that certain
14437macros are called if needed and a way to warn the user if macros are
14438called in an order that might cause incorrect operation.
14439
14440@menu
14441* Prerequisite Macros::         Ensuring required information
14442* Suggested Ordering::          Warning about possible ordering problems
14443* One-Shot Macros::             Ensuring a macro is called only once
14444@end menu
14445
14446@node Prerequisite Macros
14447@subsection Prerequisite Macros
14448@cindex Prerequisite macros
14449@cindex Macros, prerequisites
14450
14451A macro that you write might need to use values that have previously
14452been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14453examines the output of @code{flex} or @code{lex}, so it depends on
14454@code{AC_PROG_LEX} having been called first to set the shell variable
14455@code{LEX}.
14456
14457Rather than forcing the user of the macros to keep track of the
14458dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14459it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14460called if it is needed, and only called once.
14461
14462@defmac AC_REQUIRE (@var{macro-name})
14463@acindex{REQUIRE}
14464If the M4 macro @var{macro-name} has not already been called, call it
14465(without any arguments).  Make sure to quote @var{macro-name} with
14466square brackets.  @var{macro-name} must have been defined using
14467@code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14468that it has been called.
14469
14470@code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14471must not be called from the top level.  Also, it does not make sense to
14472require a macro that takes parameters.
14473@end defmac
14474
14475@code{AC_REQUIRE} is often misunderstood.  It really implements
14476dependencies between macros in the sense that if one macro depends upon
14477another, the latter is expanded @emph{before} the body of the
14478former.  To be more precise, the required macro is expanded before
14479the outermost defined macro in the current expansion stack.
14480In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14481@code{FOO}.  For instance, this definition of macros:
14482
14483@example
14484@group
14485AC_DEFUN([TRAVOLTA],
14486[test "$body_temperature_in_celsius" -gt "38" &&
14487  dance_floor=occupied])
14488AC_DEFUN([NEWTON_JOHN],
14489[test "x$hair_style" = xcurly &&
14490  dance_floor=occupied])
14491@end group
14492
14493@group
14494AC_DEFUN([RESERVE_DANCE_FLOOR],
14495[if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14496  AC_REQUIRE([TRAVOLTA])
14497  AC_REQUIRE([NEWTON_JOHN])
14498fi])
14499@end group
14500@end example
14501
14502@noindent
14503with this @file{configure.ac}
14504
14505@example
14506AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14507RESERVE_DANCE_FLOOR
14508if test "x$dance_floor" = xoccupied; then
14509  AC_MSG_ERROR([cannot pick up here, let's move])
14510fi
14511@end example
14512
14513@noindent
14514does not leave you with a better chance to meet a kindred soul at
14515other times than Saturday night since it expands into:
14516
14517@example
14518@group
14519test "$body_temperature_in_Celsius" -gt "38" &&
14520  dance_floor=occupied
14521test "x$hair_style" = xcurly &&
14522  dance_floor=occupied
14523fi
14524if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14525
14526
14527fi
14528@end group
14529@end example
14530
14531This behavior was chosen on purpose: (i) it prevents messages in
14532required macros from interrupting the messages in the requiring macros;
14533(ii) it avoids bad surprises when shell conditionals are used, as in:
14534
14535@example
14536@group
14537if @dots{}; then
14538  AC_REQUIRE([SOME_CHECK])
14539fi
14540@dots{}
14541SOME_CHECK
14542@end group
14543@end example
14544
14545However, this implementation can lead to another class of problems.
14546Consider the case where an outer macro first expands, then indirectly
14547requires, an inner macro:
14548
14549@example
14550AC_DEFUN([TESTA], [[echo in A
14551if test -n "$SEEN_A" ; then echo duplicate ; fi
14552SEEN_A=:]])
14553AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14554if test -z "$SEEN_A" ; then echo bug ; fi]])
14555AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14556AC_DEFUN([OUTER], [[echo in OUTER]
14557TESTA
14558TESTC])
14559OUTER
14560@end example
14561
14562@noindent
14563Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14564recognized that @code{TESTB} needed to be hoisted prior to the expansion
14565of @code{OUTER}, but because @code{TESTA} had already been directly
14566expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14567@code{TESTB} occurs prior to its prerequisites, leading to the following
14568output:
14569
14570@example
14571in B
14572bug
14573in OUTER
14574in A
14575in C
14576@end example
14577
14578@noindent
14579Newer Autoconf is smart enough to recognize this situation, and hoists
14580@code{TESTA} even though it has already been expanded, but issues a
14581syntax warning in the process.  This is because the hoisted expansion of
14582@code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14583redundant code, and causes its own set of problems if the hoisted macro
14584is not idempotent:
14585
14586@example
14587in A
14588in B
14589in OUTER
14590in A
14591duplicate
14592in C
14593@end example
14594
14595The bug is not in Autoconf, but in the macro definitions.  If you ever
14596pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14597that the macro only needs to be expanded once.  But to enforce this,
14598either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14599this only helps in Autoconf 2.64 or newer), or all
14600uses of that macro should be through @code{AC_REQUIRE}; directly
14601expanding the macro defeats the point of using @code{AC_REQUIRE} to
14602eliminate redundant expansion.  In the example, this rule of thumb was
14603violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14604directly expands it.  One way of fixing the bug is to factor
14605@code{TESTA} into two macros, the portion designed for direct and
14606repeated use (here, named @code{TESTA}), and the portion designed for
14607one-shot output and used only inside @code{AC_REQUIRE} (here, named
14608@code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14609calling convention according to their needs:
14610
14611@example
14612AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14613AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14614if test -n "$SEEN_A" ; then echo duplicate ; fi
14615SEEN_A=:]])
14616AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14617if test -z "$SEEN_A" ; then echo bug ; fi]])
14618AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14619AC_DEFUN([OUTER], [[echo in OUTER]
14620TESTA
14621TESTC])
14622OUTER
14623@end example
14624
14625@noindent
14626the resulting output will then obey all dependency rules and avoid any
14627syntax warnings, whether the script is built with old or new Autoconf
14628versions:
14629
14630@example
14631in A_PREREQ
14632in B
14633in OUTER
14634in A
14635in C
14636@end example
14637
14638The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14639enforce expansion of required macros outside of shell conditional
14640constructs.  You are furthermore encouraged, although not required, to
14641put all @code{AC_REQUIRE} calls
14642at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14643lines they leave.
14644
14645@node Suggested Ordering
14646@subsection Suggested Ordering
14647@cindex Macros, ordering
14648@cindex Ordering macros
14649
14650Some macros should be run before another macro if both are called, but
14651neither @emph{requires} that the other be called.  For example, a macro
14652that changes the behavior of the C compiler should be called before any
14653macros that run the C compiler.  Many of these dependencies are noted in
14654the documentation.
14655
14656Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14657with this kind of dependency appear out of order in a
14658@file{configure.ac} file.  The warning occurs when creating
14659@command{configure} from @file{configure.ac}, not when running
14660@command{configure}.
14661
14662For example, @code{AC_PROG_CPP} checks whether the C compiler
14663can run the C preprocessor when given the @option{-E} option.  It should
14664therefore be called after any macros that change which C compiler is
14665being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14666
14667@example
14668AC_BEFORE([$0], [AC_PROG_CPP])dnl
14669@end example
14670
14671@noindent
14672This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14673when @code{AC_PROG_CC} is called.
14674
14675@defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14676@acindex{BEFORE}
14677Make M4 print a warning message to the standard error output if
14678@var{called-macro-name} has already been called.  @var{this-macro-name}
14679should be the name of the macro that is calling @code{AC_BEFORE}.  The
14680macro @var{called-macro-name} must have been defined using
14681@code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14682that it has been called.
14683@end defmac
14684
14685@node One-Shot Macros
14686@subsection One-Shot Macros
14687@cindex One-shot macros
14688@cindex Macros, called once
14689
14690Some macros should be called only once, either because calling them
14691multiple time is unsafe, or because it is bad style.  For instance
14692Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14693(@pxref{Canonicalizing}) are evaluated only once, because it makes no
14694sense to run these expensive checks more than once.  Such one-shot
14695macros can be defined using @code{AC_DEFUN_ONCE}.
14696
14697@defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14698@acindex{DEFUN_ONCE}
14699Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14700Definitions}), but add additional logic that guarantees that only the
14701first use of the macro (whether by direct expansion or
14702@code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14703expansion will occur before the start of any enclosing macro defined by
14704@code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14705Generally, it does not make sense for @var{macro-body} to use parameters
14706such as @code{$1}.
14707@end defmac
14708
14709Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14710emit a warning if it was directly expanded a second time, so for
14711portability, it is better to use @code{AC_REQUIRE} than direct
14712invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14713(@pxref{Prerequisite Macros}).
14714
14715@node Obsoleting Macros
14716@section Obsoleting Macros
14717@cindex Obsoleting macros
14718@cindex Macros, obsoleting
14719
14720Configuration and portability technology has evolved over the years.
14721Often better ways of solving a particular problem are developed, or
14722ad-hoc approaches are systematized.  This process has occurred in many
14723parts of Autoconf.  One result is that some of the macros are now
14724considered @dfn{obsolete}; they still work, but are no longer considered
14725the best thing to do, hence they should be replaced with more modern
14726macros.  Ideally, @command{autoupdate} should replace the old macro calls
14727with their modern implementation.
14728
14729Autoconf provides a simple means to obsolete a macro.
14730
14731@anchor{AU_DEFUN}
14732@defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14733@auindex{DEFUN}
14734Define @var{old-macro} as @var{implementation}.  The only difference
14735with @code{AC_DEFUN} is that the user is warned that
14736@var{old-macro} is now obsolete.
14737
14738If she then uses @command{autoupdate}, the call to @var{old-macro} is
14739replaced by the modern @var{implementation}.  @var{message} should
14740include information on what to do after running @command{autoupdate};
14741@command{autoupdate} prints it as a warning, and includes it
14742in the updated @file{configure.ac} file.
14743
14744The details of this macro are hairy: if @command{autoconf} encounters an
14745@code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14746as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14747macros are expanded here, while all other macros are disabled and
14748appear literally in the updated @file{configure.ac}.
14749@end defmac
14750
14751@defmac AU_ALIAS (@var{old-name}, @var{new-name})
14752@auindex{ALIAS}
14753Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14754with the same parameters.  This happens for example if the macro was renamed.
14755@end defmac
14756
14757@node Coding Style
14758@section Coding Style
14759@cindex Coding style
14760
14761The Autoconf macros follow a strict coding style.  You are encouraged to
14762follow this style, especially if you intend to distribute your macro,
14763either by contributing it to Autoconf itself or the
14764@uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14765Archive}, or by other means.
14766
14767The first requirement is to pay great attention to the quotation.  For
14768more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14769
14770Do not try to invent new interfaces.  It is likely that there is a macro
14771in Autoconf that resembles the macro you are defining: try to stick to
14772this existing interface (order of arguments, default values, etc.).  We
14773@emph{are} conscious that some of these interfaces are not perfect;
14774nevertheless, when harmless, homogeneity should be preferred over
14775creativity.
14776
14777Be careful about clashes both between M4 symbols and between shell
14778variables.
14779
14780If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14781you are unlikely to generate conflicts.  Nevertheless, when you need to
14782set a special value, @emph{avoid using a regular macro name}; rather,
14783use an ``impossible'' name.  For instance, up to version 2.13, the macro
14784@code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14785by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14786But since there is a macro named @code{AC_SUBST_FILE}, it was just
14787impossible to @samp{AC_SUBST(FILE)}!  In this case,
14788@code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14789have been used (yes, with the parentheses).
14790@c or better yet, high-level macros such as @code{m4_expand_once}
14791
14792No Autoconf macro should ever enter the user-variable name space; i.e.,
14793except for the variables that are the actual result of running the
14794macro, all shell variables should start with @code{ac_}.  In
14795addition, small macros or any macro that is likely to be embedded in
14796other macros should be careful not to use obvious names.
14797
14798@cindex @code{dnl}
14799Do not use @code{dnl} to introduce comments: most of the comments you
14800are likely to write are either header comments which are not output
14801anyway, or comments that should make their way into @file{configure}.
14802There are exceptional cases where you do want to comment special M4
14803constructs, in which case @code{dnl} is right, but keep in mind that it
14804is unlikely.
14805
14806M4 ignores the leading blanks and newlines before each argument.
14807Use this feature to
14808indent in such a way that arguments are (more or less) aligned with the
14809opening parenthesis of the macro being called.  For instance, instead of
14810
14811@example
14812AC_CACHE_CHECK(for EMX OS/2 environment,
14813ac_cv_emxos2,
14814[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14815[ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14816@end example
14817
14818@noindent
14819write
14820
14821@example
14822AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14823[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14824                   [ac_cv_emxos2=yes],
14825                   [ac_cv_emxos2=no])])
14826@end example
14827
14828@noindent
14829or even
14830
14831@example
14832AC_CACHE_CHECK([for EMX OS/2 environment],
14833               [ac_cv_emxos2],
14834               [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14835                                                   [return __EMX__;])],
14836                                  [ac_cv_emxos2=yes],
14837                                  [ac_cv_emxos2=no])])
14838@end example
14839
14840When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14841cross-compiling, provide a pessimistic value (typically @samp{no}).
14842
14843Feel free to use various tricks to prevent auxiliary tools, such as
14844syntax-highlighting editors, from behaving improperly.  For instance,
14845instead of:
14846
14847@example
14848m4_bpatsubst([$1], [$"])
14849@end example
14850
14851@noindent
14852use
14853
14854@example
14855m4_bpatsubst([$1], [$""])
14856@end example
14857
14858@noindent
14859so that Emacsen do not open an endless ``string'' at the first quote.
14860For the same reasons, avoid:
14861
14862@example
14863test $[#] != 0
14864@end example
14865
14866@noindent
14867and use:
14868
14869@example
14870test $[@@%:@@] != 0
14871@end example
14872
14873@noindent
14874Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14875breaking the bracket-matching highlighting from Emacsen.  Note the
14876preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14877not escape when it is unnecessary.  Common examples of useless quotation
14878are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14879etc.  If you add portability issues to the picture, you'll prefer
14880@samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14881better than hacking Autoconf @code{:-)}.
14882
14883When using @command{sed}, don't use @option{-e} except for indenting
14884purposes.  With the @code{s} and @code{y} commands, the preferred
14885separator is @samp{/} unless @samp{/} itself might appear in the pattern
14886or replacement, in which case you should use @samp{|}, or optionally
14887@samp{,} if you know the pattern and replacement cannot contain a file
14888name.  If none of these characters will do, choose a printable character
14889that cannot appear in the pattern or replacement.  Characters from the
14890set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14891replacement might contain a file name, since they have special meaning
14892to the shell and are less likely to occur in file names.
14893
14894@xref{Macro Definitions}, for details on how to define a macro.  If a
14895macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14896of an @code{AC_REQUIRE} directive, and macros required by other macros
14897inside arguments do not need to be expanded before this macro, then
14898use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14899Also take into account that public third-party macros need to use
14900@code{AC_DEFUN} in order to be found by @command{aclocal}
14901(@pxref{Extending aclocal,,, automake, GNU Automake}).
14902All the @code{AC_REQUIRE} statements should be at the beginning of the
14903macro, and each statement should be followed by @code{dnl}.
14904
14905You should not rely on the number of arguments: instead of checking
14906whether an argument is missing, test that it is not empty.  It provides
14907both a simpler and a more predictable interface to the user, and saves
14908room for further arguments.
14909
14910Unless the macro is short, try to leave the closing @samp{])} at the
14911beginning of a line, followed by a comment that repeats the name of the
14912macro being defined.  This introduces an additional newline in
14913@command{configure}; normally, that is not a problem, but if you want to
14914remove it you can use @samp{[]dnl} on the last line.  You can similarly
14915use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14916is recommended instead of @samp{dnl} to ensure that M4 does not
14917interpret the @samp{dnl} as being attached to the preceding text or
14918macro output.  For example, instead of:
14919
14920@example
14921AC_DEFUN([AC_PATH_X],
14922[AC_MSG_CHECKING([for X])
14923AC_REQUIRE_CPP()
14924@r{# @dots{}omitted@dots{}}
14925  AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14926fi])
14927@end example
14928
14929@noindent
14930you would write:
14931
14932@example
14933AC_DEFUN([AC_PATH_X],
14934[AC_REQUIRE_CPP()[]dnl
14935AC_MSG_CHECKING([for X])
14936@r{# @dots{}omitted@dots{}}
14937  AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14938fi[]dnl
14939])# AC_PATH_X
14940@end example
14941
14942If the macro is long, try to split it into logical chunks.  Typically,
14943macros that check for a bug in a function and prepare its
14944@code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14945this setup.  Do not hesitate to introduce auxiliary macros to factor
14946your code.
14947
14948In order to highlight the recommended coding style, here is a macro
14949written the old way:
14950
14951@example
14952dnl Check for EMX on OS/2.
14953dnl _AC_EMXOS2
14954AC_DEFUN(_AC_EMXOS2,
14955[AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14956[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14957ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14958test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14959@end example
14960
14961@noindent
14962and the new way:
14963
14964@example
14965# _AC_EMXOS2
14966# ----------
14967# Check for EMX on OS/2.
14968m4_define([_AC_EMXOS2],
14969[AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14970[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14971                   [ac_cv_emxos2=yes],
14972                   [ac_cv_emxos2=no])])
14973test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14974])# _AC_EMXOS2
14975@end example
14976
14977
14978
14979
14980@c ============================================= Portable Shell Programming
14981
14982@node Portable Shell
14983@chapter Portable Shell Programming
14984@cindex Portable shell programming
14985
14986When writing your own checks, there are some shell-script programming
14987techniques you should avoid in order to make your code portable.  The
14988Bourne shell and upward-compatible shells like the Korn shell and Bash
14989have evolved over the years, and many features added to the original
14990System7 shell are now supported on all interesting porting targets.
14991However, the following discussion between Russ Allbery and Robert Lipe
14992is worth reading:
14993
14994@noindent
14995Russ Allbery:
14996
14997@quotation
14998The GNU assumption that @command{/bin/sh} is the one and only shell
14999leads to a permanent deadlock.  Vendors don't want to break users'
15000existing shell scripts, and there are some corner cases in the Bourne
15001shell that are not completely compatible with a Posix shell.  Thus,
15002vendors who have taken this route will @emph{never} (OK@dots{}``never say
15003never'') replace the Bourne shell (as @command{/bin/sh}) with a
15004Posix shell.
15005@end quotation
15006
15007@noindent
15008Robert Lipe:
15009
15010@quotation
15011This is exactly the problem.  While most (at least most System V's) do
15012have a Bourne shell that accepts shell functions most vendor
15013@command{/bin/sh} programs are not the Posix shell.
15014
15015So while most modern systems do have a shell @emph{somewhere} that meets the
15016Posix standard, the challenge is to find it.
15017@end quotation
15018
15019For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15020is to find such a shell.  But to prevent trouble, if you're not using
15021M4sh you should not take advantage of features that were added after Unix
15022version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15023negated character classes, or even @command{unset}.  @code{#} comments,
15024while not in Unix version 7, were retrofitted in the original Bourne
15025shell and can be assumed to be part of the least common denominator.
15026
15027On the other hand, if you're using M4sh you can assume that the shell
15028has the features that were added in SVR2 (circa 1984), including shell
15029functions,
15030@command{return}, @command{unset}, and I/O redirection for builtins.  For
15031more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15032However, some pitfalls have to be avoided for portable use of these
15033constructs; these will be documented in the rest of this chapter.
15034See in particular @ref{Shell Functions} and @ref{Limitations of
15035Builtins, , Limitations of Shell Builtins}.
15036
15037Some ancient systems have quite
15038small limits on the length of the @samp{#!} line; for instance, 32
15039bytes (not including the newline) on SunOS 4.
15040However, these ancient systems are no longer of practical concern.
15041
15042The set of external programs you should run in a @command{configure} script
15043is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15044Makefiles, standards, The GNU Coding Standards}, for the list.  This
15045restriction allows users to start out with a fairly small set of
15046programs and build the rest, avoiding too many interdependencies between
15047packages.
15048
15049Some of these external utilities have a portable subset of features; see
15050@ref{Limitations of Usual Tools}.
15051
15052There are other sources of documentation about shells.  The
15053specification for the Posix
15054@uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15055Command Language}, though more generous than the restrictive shell
15056subset described above, is fairly portable nowadays.  Also please see
15057@uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15058
15059@menu
15060* Shellology::                  A zoology of shells
15061* Invoking the Shell::          Invoking the shell as a command
15062* Here-Documents::              Quirks and tricks
15063* File Descriptors::            FDs and redirections
15064* Signal Handling::             Shells, signals, and headaches
15065* File System Conventions::     File names
15066* Shell Pattern Matching::      Pattern matching
15067* Shell Substitutions::         Variable and command expansions
15068* Assignments::                 Varying side effects of assignments
15069* Parentheses::                 Parentheses in shell scripts
15070* Slashes::                     Slashes in shell scripts
15071* Special Shell Variables::     Variables you should not change
15072* Shell Functions::             What to look out for if you use them
15073* Limitations of Builtins::     Portable use of not so portable /bin/sh
15074* Limitations of Usual Tools::  Portable use of portable tools
15075@end menu
15076
15077@node Shellology
15078@section Shellology
15079@cindex Shellology
15080
15081There are several families of shells, most prominently the Bourne family
15082and the C shell family which are deeply incompatible.  If you want to
15083write portable shell scripts, avoid members of the C shell family.  The
15084@uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15085Shell difference FAQ} includes a small history of Posix shells, and a
15086comparison between several of them.
15087
15088Below we describe some of the members of the Bourne shell family.
15089
15090@table @asis
15091@item Ash
15092@cindex Ash
15093Ash is often used on GNU/Linux and BSD
15094systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15095bugs that are fixed in the 0.3.x series, but portable shell scripts
15096should work around them, since version 0.2 is still shipped with many
15097GNU/Linux distributions.
15098
15099To be compatible with Ash 0.2:
15100
15101@itemize @minus
15102@item
15103don't use @samp{$?} after expanding empty or unset variables,
15104or at the start of an @command{eval}:
15105
15106@example
15107foo=
15108false
15109$foo
15110echo "Do not use it: $?"
15111false
15112eval 'echo "Do not use it: $?"'
15113@end example
15114
15115@item
15116don't use command substitution within variable expansion:
15117
15118@example
15119cat $@{FOO=`bar`@}
15120@end example
15121
15122@item
15123beware that single builtin substitutions are not performed by a
15124subshell, hence their effect applies to the current shell!  @xref{Shell
15125Substitutions}, item ``Command Substitution''.
15126@end itemize
15127
15128@item Bash
15129@cindex Bash
15130To detect whether you are running Bash, test whether
15131@code{BASH_VERSION} is set.  To require
15132Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15133Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15134Manual}, for details.
15135
15136@item Bash 2.05 and later
15137@cindex Bash 2.05 and later
15138Versions 2.05 and later of Bash use a different format for the
15139output of the @command{set} builtin, designed to make evaluating its
15140output easier.  However, this output is not compatible with earlier
15141versions of Bash (or with many other shells, probably).  So if
15142you use Bash 2.05 or higher to execute @command{configure},
15143you'll need to use Bash 2.05 for all other build tasks as well.
15144
15145@item Ksh
15146@cindex Ksh
15147@cindex Korn shell
15148@prindex @samp{ksh}
15149@prindex @samp{ksh88}
15150@prindex @samp{ksh93}
15151The Korn shell is compatible with the Bourne family and it mostly
15152conforms to Posix.  It has two major variants commonly
15153called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15154release.  It is usually called @command{ksh}, but is called @command{sh}
15155on some hosts if you set your path appropriately.
15156
15157Solaris systems have three variants:
15158@prindex @command{/usr/bin/ksh} on Solaris
15159@command{/usr/bin/ksh} is @samp{ksh88}; it is
15160standard on Solaris 2.0 and later.
15161@prindex @command{/usr/xpg4/bin/sh} on Solaris
15162@command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15163@samp{ksh88}; it is standard on Solaris 9 and later.
15164@prindex @command{/usr/dt/bin/dtksh} on Solaris
15165@command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15166Variants that are not standard may be parts of optional
15167packages.  There is no extra charge for these packages, but they are
15168not part of a minimal OS install and therefore some installations may
15169not have it.
15170
15171Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15172is also available as @command{/usr/bin/posix/sh}.  If the environment
15173variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15174the standard shell conform to Posix.
15175
15176@item Pdksh
15177@prindex @samp{pdksh}
15178A public-domain clone of the Korn shell called @command{pdksh} is widely
15179available: it has most of the @samp{ksh88} features along with a few of
15180its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15181@command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15182Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15183@command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15184Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15185at least one respect, see @ref{Shell Substitutions}.
15186
15187@item Zsh
15188@cindex Zsh
15189To detect whether you are running @command{zsh}, test whether
15190@code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15191compatible with the Bourne shell: you must execute @samp{emulate sh},
15192and for @command{zsh} versions before 3.1.6-dev-18 you must also
15193set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15194zsh, The Z Shell Manual}, for details.
15195
15196The default Mac OS X @command{sh} was originally Zsh; it was changed to
15197Bash in Mac OS X 10.2.
15198@end table
15199
15200@node Invoking the Shell
15201@section Invoking the Shell
15202@cindex invoking the shell
15203@cindex shell invocation
15204
15205The Korn shell (up to at least version M-12/28/93d) has a bug when
15206invoked on a file whose name does not contain a slash.  It first
15207searches for the file's name in @env{PATH}, and if found it executes
15208that rather than the original file.  For example, assuming there is a
15209binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15210command in the following example fails because the Korn shell finds
15211@file{/usr/bin/script} and refuses to execute it as a shell script:
15212
15213@example
15214$ @kbd{touch xxyzzyz script}
15215$ @kbd{ksh xxyzzyz}
15216$ @kbd{ksh ./script}
15217$ @kbd{ksh script}
15218ksh: script: cannot execute
15219@end example
15220
15221Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15222option-argument ends in backslash-newline, Bash incorrectly reports a
15223syntax error.  The problem does not occur if a character follows the
15224backslash:
15225
15226@example
15227$ @kbd{$ bash -c 'echo foo \}
15228> @kbd{'}
15229bash: -c: line 2: syntax error: unexpected end of file
15230$ @kbd{bash -c 'echo foo \}
15231> @kbd{ '}
15232foo
15233@end example
15234
15235@noindent
15236@xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15237
15238@node Here-Documents
15239@section Here-Documents
15240@cindex Here-documents
15241@cindex Shell here-documents
15242
15243Don't rely on @samp{\} being preserved just because it has no special
15244meaning together with the next symbol.  In the native @command{sh}
15245on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15246unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15247use @samp{\\} to get @samp{\}.
15248
15249With OpenBSD 2.7's @command{sh}
15250
15251@example
15252@group
15253$ @kbd{cat <<EOF
15254> \" \\
15255> EOF}
15256" \
15257@end group
15258@end example
15259
15260@noindent
15261and with Bash:
15262
15263@example
15264@group
15265bash-2.04$ @kbd{cat <<EOF
15266> \" \\
15267> EOF}
15268\" \
15269@end group
15270@end example
15271
15272Using command substitutions in a here-document that is fed to a shell
15273function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15274
15275@example
15276$ @kbd{kitty () @{ cat; @}}
15277$ @kbd{kitty <<EOF
15278> `echo ok`
15279> EOF}
15280/tmp/sh199886: cannot open
15281$ @kbd{echo $?}
152821
15283@end example
15284
15285Some shells mishandle large here-documents: for example,
15286Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15287derived from Korn shell version M-12/28/93d, mishandle braced variable
15288expansion that crosses a 1024- or 4096-byte buffer boundary
15289within a here-document.  Only the part of the variable name after the boundary
15290is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15291of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15292boundary, the shell reports an error, as if you used @code{$@{@}}.
15293Instead of @code{$@{variable-default@}}, the shell may expand
15294@code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15295be worked around by omitting the braces: @code{$variable}.  The bug was
15296fixed in
15297@samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15298still shipping older versions with the bug.
15299
15300Empty here-documents are not portable either; with the following code,
15301@command{zsh} up to at least version 4.3.10 creates a file with a single
15302newline, whereas other shells create an empty file:
15303
15304@example
15305cat >file <<EOF
15306EOF
15307@end example
15308
15309Many shells (including the Bourne shell) implement here-documents
15310inefficiently.  In particular, some shells can be extremely inefficient when
15311a single statement contains many here-documents.  For instance if your
15312@file{configure.ac} includes something like:
15313
15314@example
15315@group
15316if <cross_compiling>; then
15317  assume this and that
15318else
15319  check this
15320  check that
15321  check something else
15322  @dots{}
15323  on and on forever
15324  @dots{}
15325fi
15326@end group
15327@end example
15328
15329A shell parses the whole @code{if}/@code{fi} construct, creating
15330temporary files for each here-document in it.  Some shells create links
15331for such here-documents on every @code{fork}, so that the clean-up code
15332they had installed correctly removes them.  It is creating the links
15333that can take the shell forever.
15334
15335Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15336@code{if}/@code{fi} constructs, would improve the performance
15337significantly.  Anyway, this kind of construct is not exactly the
15338typical use of Autoconf.  In fact, it's even not recommended, because M4
15339macros can't look into shell conditionals, so we may fail to expand a
15340macro when it was expanded before in a conditional path, and the
15341condition turned out to be false at runtime, and we end up not
15342executing the macro at all.
15343
15344Be careful with the use of @samp{<<-} to unindent here-documents.  The
15345behavior is only portable for stripping leading @key{TAB}s, and things
15346can silently break if an overzealous editor converts to using leading
15347spaces (not all shells are nice enough to warn about unterminated
15348here-documents).
15349
15350@example
15351$ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
153521
15353 2
15354done
15355$ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15356 1
15357  2
15358 x
15359done
15360@end example
15361
15362@node File Descriptors
15363@section File Descriptors
15364@cindex Descriptors
15365@cindex File descriptors
15366@cindex Shell file descriptors
15367
15368Most shells, if not all (including Bash, Zsh, Ash), output traces on
15369stderr, even for subshells.  This might result in undesirable content
15370if you meant to capture the standard-error output of the inner command:
15371
15372@example
15373$ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15374$ @kbd{cat stderr}
15375+ eval echo foo >&2
15376+ echo foo
15377foo
15378$ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15379$ @kbd{cat stderr}
15380+ eval 'echo foo >&2'
15381++ echo foo
15382foo
15383$ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15384@i{# Traces on startup files deleted here.}
15385$ @kbd{cat stderr}
15386+zsh:1> eval echo foo >&2
15387+zsh:1> echo foo
15388foo
15389@end example
15390
15391@noindent
15392One workaround is to grep out uninteresting lines, hoping not to remove
15393good ones.
15394
15395If you intend to redirect both standard error and standard output,
15396redirect standard output first.  This works better with HP-UX,
15397since its shell mishandles tracing if standard error is redirected
15398first:
15399
15400@example
15401$ @kbd{sh -x -c ': 2>err >out'}
15402+ :
15403+ 2> err $ @kbd{cat err}
154041> out
15405@end example
15406
15407Don't try to redirect the standard error of a command substitution.  It
15408must be done @emph{inside} the command substitution.  When running
15409@samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15410escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15411
15412On the other hand, some shells, such as Solaris or FreeBSD
15413@command{/bin/sh}, warn about missing programs before performing
15414redirections.  Therefore, to silently check whether a program exists, it
15415is necessary to perform redirections on a subshell or brace group:
15416@example
15417$ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15418nosuch: not found
15419$ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15420$ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15421$ @kbd{bash -c 'nosuch 2>/dev/null'}
15422@end example
15423
15424FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15425shell pipeline.
15426
15427It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15428in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15429
15430Some shells, like @command{ash}, don't recognize bi-directional
15431redirection (@samp{<>}).  And even on shells that recognize it, it is
15432not portable to use on fifos: Posix does not require read-write support
15433for named pipes, and Cygwin does not support it:
15434
15435@example
15436$ @kbd{mkfifo fifo}
15437$ @kbd{exec 5<>fifo}
15438$ @kbd{echo hi >&5}
15439bash: echo: write error: Communication error on send
15440@end example
15441
15442@noindent
15443Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15444regular files when using @samp{<>}:
15445
15446@example
15447$ @kbd{echo a > file}
15448$ @kbd{bash -c ': 1<>file'; cat file}
15449a
15450$ @kbd{dash -c ': 1<>file'; cat file}
15451$ rm a
15452@end example
15453
15454When catering to old systems, don't redirect the same file descriptor
15455several times, as you are doomed to failure under Ultrix.
15456
15457@example
15458ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15459UWS V4.4 (Rev. 11)
15460$ @kbd{eval 'echo matter >fullness' >void}
15461illegal io
15462$ @kbd{eval '(echo matter >fullness)' >void}
15463illegal io
15464$ @kbd{(eval '(echo matter >fullness)') >void}
15465Ambiguous output redirect.
15466@end example
15467
15468@noindent
15469In each case the expected result is of course @file{fullness} containing
15470@samp{matter} and @file{void} being empty.  However, this bug is
15471probably not of practical concern to modern platforms.
15472
15473Solaris 10 @command{sh} will try to optimize away a @command{:} command
15474(even if it is redirected) in a loop after the first iteration, or in a
15475shell function after the first call:
15476
15477@example
15478$ @kbd{for i in 1 2 3 ; do : >x$i; done}
15479$ @kbd{ls x*}
15480x1
15481$ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15482$ @kbd{ls y*}
15483y1
15484@end example
15485
15486@noindent
15487As a workaround, @command{echo} or @command{eval} can be used.
15488
15489Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15490subsidiary program.  If any of these descriptors is closed, the
15491operating system may open an unspecified file for the descriptor in the
15492new process image.  Posix 2008 says this may be done only if the
15493subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15494it even for ordinary programs, and the next version of Posix will allow
15495HP-UX behavior.
15496
15497If you want a file descriptor above 2 to be inherited into a child
15498process, then you must use redirections specific to that command or a
15499containing subshell or command group, rather than relying on
15500@command{exec} in the shell. In @command{ksh} as well as HP-UX
15501@command{sh}, file descriptors above 2 which are opened using
15502@samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15503that involved in the fork-and-exec which runs a program or script):
15504
15505@example
15506$ @kbd{echo 'echo hello >&5' >k}
15507$ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15508hello
15509$ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15510hello
15511$ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15512./k[1]: 5: cannot open [Bad file number]
15513$ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15514hello
15515$ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15516hello
15517$ @kbd{ksh -c '5>t ksh ./k; cat t}
15518hello
15519@end example
15520
15521Don't rely on duplicating a closed file descriptor to cause an
15522error.  With Solaris @command{/bin/sh}, failed duplication is silently
15523ignored, which can cause unintended leaks to the original file
15524descriptor.  In this example, observe the leak to standard output:
15525
15526@example
15527$ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15528bash: 3: Bad file descriptor
155291
15530$ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15531hi
155320
15533@end example
15534
15535Fortunately, an attempt to close an already closed file descriptor will
15536portably succeed.  Likewise, it is safe to use either style of
15537@samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15538even if it doesn't match the read/write mode that the file descriptor
15539was opened with.
15540
15541DOS variants cannot rename or remove open files, such as in
15542@samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15543perfectly portable among Posix hosts.
15544
15545A few ancient systems reserved some file descriptors.  By convention,
15546file descriptor 3 was opened to @file{/dev/tty} when you logged into
15547Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15548descriptor 4 had a special use on the Stardent/Kubota Titan (circa
155491990), though we don't now remember what it was.  Both these systems are
15550obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15551other file descriptors.
15552
15553On the other hand, you can't portably use multi-digit file descriptors.
15554Solaris @command{ksh} doesn't understand any file descriptor larger than
15555@samp{9}:
15556
15557@example
15558$ @kbd{bash -c 'exec 10>&-'; echo $?}
155590
15560$ @kbd{ksh -c 'exec 9>&-'; echo $?}
155610
15562$ @kbd{ksh -c 'exec 10>&-'; echo $?}
15563ksh[1]: exec: 10: not found
15564127
15565@end example
15566
15567@c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15568@node Signal Handling
15569@section Signal Handling
15570@cindex Signal handling in the shell
15571@cindex Signals, shells and
15572
15573Portable handling of signals within the shell is another major source of
15574headaches.  This is worsened by the fact that various different, mutually
15575incompatible approaches are possible in this area, each with its
15576distinctive merits and demerits.  A detailed description of these possible
15577approaches, as well as of their pros and cons, can be found in
15578@uref{http://www.cons.org/cracauer/sigint.html, this article}.
15579
15580Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15581@c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15582the shell still exits with error upon termination by one of those signals,
15583but in such a case the exit status might be somewhat unexpected (even if
15584allowed by POSIX, strictly speaking):
15585
15586@example
15587$ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15588Hangup
15589129
15590$ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15591Terminated
15592143
15593$ @kbd{for sig in 1 2 3 15; do}
15594> @kbd{  echo $sig:}
15595> @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15596> @kbd{done}
15597signal 1:
15598Hangup
15599129
15600signal 2:
15601208
15602signal 3:
15603208
15604signal 15:
15605208
15606@end example
15607
15608This gets even worse if one is using the POSIX `wait' interface to get
15609details about the shell process terminations: it will result in the shell
15610having exited normally, rather than by receiving a signal.
15611
15612@example
15613$ @kbd{cat > foo.c <<'END'}
15614#include <stdio.h>    /* for printf */
15615#include <stdlib.h>   /* for system */
15616#include <sys/wait.h> /* for WIF* macros */
15617int main(void)
15618@{
15619  int status = system ("kill -15 $$");
15620  printf ("Terminated by signal: %s\n",
15621          WIFSIGNALED (status) ? "yes" : "no");
15622  printf ("Exited normally: %s\n",
15623          WIFEXITED (status) ? "yes" : "no");
15624  return 0;
15625@}
15626END
15627@c $$ font-lock
15628$ @kbd{cc -o foo foo.c}
15629$ @kbd{./a.out} # On GNU/Linux
15630Terminated by signal: no
15631Exited normally: yes
15632$ @kbd{./a.out} # On Solaris 10
15633Terminated by signal: yes
15634Exited normally: no
15635@end example
15636
15637Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15638if it is not blocked, and even if the shell is not running interactively
15639(in fact, even if the shell has no attached tty); among these shells
15640are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15641@code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15642Still, @code{SIGQUIT} seems to be trappable quite portably within all
15643these shells.  OTOH, some other shells doesn't special-case the handling
15644of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15645Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15646
15647@c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15648Some shells (especially Korn shells and derivatives) might try to
15649propagate to themselves a signal that has killed a child process; this is
15650not a bug, but a conscious design choice (although its overall value might
15651be debatable).  The exact details of how this is attained vary from shell
15652to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15653the perl process has been interrupted AT&T @code{ksh93} (2011) will
15654proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15655and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15656128 + 2). In any case, if there is an active trap associated with
15657@code{SIGINT}, those shells will correctly execute it.
15658
15659@c See: <http://www.austingroupbugs.net/view.php?id=51>
15660Some Korn shells, when a child process die due receiving a signal with
15661signal number @var{n}, can leave in @samp{$?} an exit status of
15662256+@var{n} instead of the more common 128+@var{n}.  Observe the
15663difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15664Debian:
15665
15666@example
15667$ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15668/bin/ksh: line 1: 7837: Hangup
15669257
15670$ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15671/bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15672129
15673@end example
15674
15675@noindent
15676This @command{ksh} behavior is allowed by POSIX, if implemented with
15677due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15678Austin Group discussion} for more background.  However, if it is not
15679implemented with proper care, such a behavior might cause problems
15680in some corner cases.  To see why, assume we have a ``wrapper'' script
15681like this:
15682
15683@example
15684#!/bin/sh
15685# Ignore some signals in the shell only, not in its child processes.
15686trap : 1 2 13 15
15687wrapped_command "$@@"
15688ret=$?
15689other_command
15690exit $ret
15691@end example
15692
15693@noindent
15694If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15695has signal number 1), @code{ret} will be set to 257.  Unless the
15696@command{exit} shell builtin is smart enough to understand that such
15697a value can only have originated from a signal, and adjust the final
15698wait status of the shell appropriately, the value 257 will just get
15699truncated to 1 by the closing @code{exit} call, so that a caller of
15700the script will have no way to determine that termination by a signal
15701was involved.  Observe the different behavior of AT&T @code{ksh93}
15702(2011) and @code{bash} 4.1.5 on Debian:
15703
15704@example
15705$ @kbd{cat foo.sh}
15706#!/bin/sh
15707sh -c 'kill -1 $$'
15708ret=$?
15709echo $ret
15710exit $ret
15711$ @kbd{/bin/ksh foo.sh; echo $?}
15712foo.sh: line 2: 12479: Hangup
15713257
157141
15715$ @kbd{/bin/bash foo.sh; echo $?}
15716foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15717129
15718129
15719@end example
15720
15721@node File System Conventions
15722@section File System Conventions
15723@cindex File system conventions
15724
15725Autoconf uses shell-script processing extensively, so the file names
15726that it processes should not contain characters that are special to the
15727shell.  Special characters include space, tab, newline, NUL, and
15728the following:
15729
15730@example
15731" # $ & ' ( ) * ; < = > ? [ \ ` |
15732@end example
15733
15734Also, file names should not begin with @samp{~} or @samp{-}, and should
15735contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15736immediately after @samp{:}.  On Posix-like platforms, directory names
15737should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15738path separator.
15739
15740These restrictions apply not only to the files that you distribute, but
15741also to the absolute file names of your source, build, and destination
15742directories.
15743
15744On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15745they should be avoided.
15746
15747Posix lets implementations treat leading @file{//} specially, but
15748requires leading @file{///} and beyond to be equivalent to @file{/}.
15749Most Unix variants treat @file{//} like @file{/}.  However, some treat
15750@file{//} as a ``super-root'' that can provide access to files that are
15751not otherwise reachable from @file{/}.  The super-root tradition began
15752with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15753has revived it.
15754
15755While @command{autoconf} and friends are usually run on some Posix
15756variety, they can be used on other systems, most notably DOS
15757variants.  This impacts several assumptions regarding file names.
15758
15759@noindent
15760For example, the following code:
15761
15762@example
15763case $foo_dir in
15764  /*) # Absolute
15765     ;;
15766  *)
15767     foo_dir=$dots$foo_dir ;;
15768esac
15769@end example
15770
15771@noindent
15772fails to properly detect absolute file names on those systems, because
15773they can use a drivespec, and usually use a backslash as directory
15774separator.  If you want to be portable to DOS variants (at the
15775price of rejecting valid but oddball Posix file names like @file{a:\b}),
15776you can check for absolute file names like this:
15777
15778@cindex absolute file names, detect
15779@example
15780case $foo_dir in
15781  [\\/]* | ?:[\\/]* ) # Absolute
15782     ;;
15783  *)
15784     foo_dir=$dots$foo_dir ;;
15785esac
15786@end example
15787
15788@noindent
15789Make sure you quote the brackets if appropriate and keep the backslash as
15790first character (@pxref{case, , Limitations of Shell Builtins}).
15791
15792Also, because the colon is used as part of a drivespec, these systems don't
15793use it as path separator.  When creating or accessing paths, you can use the
15794@code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15795to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15796starts up.
15797
15798File names need extra care as well.  While DOS variants
15799that are Posixy enough to run @command{autoconf} (such as DJGPP)
15800are usually able to handle long file names properly, there are still
15801limitations that can seriously break packages.  Several of these issues
15802can be easily detected by the
15803@uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15804package.
15805
15806A short overview follows; problems are marked with SFN/LFN to
15807indicate where they apply: SFN means the issues are only relevant to
15808plain DOS, not to DOS under Microsoft Windows
15809variants, while LFN identifies problems that exist even under
15810Microsoft Windows variants.
15811
15812@table @asis
15813@item No multiple dots (SFN)
15814DOS cannot handle multiple dots in file names.  This is an especially
15815important thing to remember when building a portable configure script,
15816as @command{autoconf} uses a .in suffix for template files.
15817
15818This is perfectly OK on Posix variants:
15819
15820@example
15821AC_CONFIG_HEADERS([config.h])
15822AC_CONFIG_FILES([source.c foo.bar])
15823AC_OUTPUT
15824@end example
15825
15826@noindent
15827but it causes problems on DOS, as it requires @samp{config.h.in},
15828@samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15829to DOS-based environments, you should use this instead:
15830
15831@example
15832AC_CONFIG_HEADERS([config.h:config.hin])
15833AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15834AC_OUTPUT
15835@end example
15836
15837@item No leading dot (SFN)
15838DOS cannot handle file names that start with a dot.  This is usually
15839not important for @command{autoconf}.
15840
15841@item Case insensitivity (LFN)
15842DOS is case insensitive, so you cannot, for example, have both a
15843file called @samp{INSTALL} and a directory called @samp{install}.  This
15844also affects @command{make}; if there's a file called @samp{INSTALL} in
15845the directory, @samp{make install} does nothing (unless the
15846@samp{install} target is marked as PHONY).
15847
15848@item The 8+3 limit (SFN)
15849Because the DOS file system only stores the first 8 characters of
15850the file name and the first 3 of the extension, those must be unique.
15851That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15852@file{foobar-prettybird.c} all resolve to the same file name
15853(@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15854@file{foo.bartender}.
15855
15856The 8+3 limit is not usually a problem under Microsoft Windows, as it
15857uses numeric
15858tails in the short version of file names to make them unique.  However, a
15859registry setting can turn this behavior off.  While this makes it
15860possible to share file trees containing long file names between SFN
15861and LFN environments, it also means the above problem applies there
15862as well.
15863
15864@item Invalid characters (LFN)
15865Some characters are invalid in DOS file names, and should therefore
15866be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15867@samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15868In a SFN environment, other characters are also invalid.  These
15869include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15870
15871@item Invalid names (LFN)
15872Some DOS file names are reserved, and cause problems if you
15873try to use files with those names.  These names include @file{CON},
15874@file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15875@file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15876File names are case insensitive, so even names like
15877@file{aux/config.guess} are disallowed.
15878
15879@end table
15880
15881@node Shell Pattern Matching
15882@section Shell Pattern Matching
15883@cindex Shell pattern matching
15884
15885Nowadays portable patterns can use negated character classes like
15886@samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15887some shells but not others; hence portable scripts should never use
15888@samp{^} as the first character of a bracket pattern.
15889
15890Outside the C locale, patterns like @samp{[a-z]} are problematic since
15891they may match characters that are not lower-case letters.
15892
15893@node Shell Substitutions
15894@section Shell Substitutions
15895@cindex Shell substitutions
15896
15897Contrary to a persistent urban legend, the Bourne shell does not
15898systematically split variables and back-quoted expressions, in particular
15899on the right-hand side of assignments and in the argument of @code{case}.
15900For instance, the following code:
15901
15902@example
15903case "$given_srcdir" in
15904.)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15905*)  top_srcdir="$dots$given_srcdir" ;;
15906esac
15907@end example
15908
15909@noindent
15910is more readable when written as:
15911
15912@example
15913case $given_srcdir in
15914.)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15915*)  top_srcdir=$dots$given_srcdir ;;
15916esac
15917@end example
15918
15919@noindent
15920and in fact it is even @emph{more} portable: in the first case of the
15921first attempt, the computation of @code{top_srcdir} is not portable,
15922since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15923for example Solaris 10 ksh:
15924
15925@example
15926$ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15927ksh: : cannot execute
15928ksh: bar | sed 's, ,,': cannot execute
15929@end example
15930
15931@noindent
15932Posix does not specify behavior for this sequence.  On the other hand,
15933behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15934but in practice, not all shells understand it the same way: pdksh 5.2.14
15935prints spurious quotes when in Posix mode:
15936
15937@example
15938$ @kbd{echo "`echo \"hello\"`"}
15939hello
15940$ @kbd{set -o posix}
15941$ @kbd{echo "`echo \"hello\"`"}
15942"hello"
15943@end example
15944
15945@noindent
15946There is just no portable way to use double-quoted strings inside
15947double-quoted back-quoted expressions (pfew!).
15948
15949Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15950parameter expansions are elided during word splitting.  Meanwhile, zsh
15951does not perform word splitting except when in Bourne compatibility
15952mode.  In the example below, the correct behavior is to have five
15953arguments to the function, and exactly two spaces on either side of the
15954middle @samp{-}, since word splitting collapses multiple spaces in
15955@samp{$f} but leaves empty arguments intact.
15956
15957@example
15958$ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
159593- - -
15960$ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
159615-  -  -
15962$ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
159633-   -   -
15964$ @kbd{zsh -c 'emulate sh;}
15965> @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
159665-  -  -
15967@end example
15968
15969@noindent
15970You can work around this by doing manual word splitting, such as using
15971@samp{"$str" $list} rather than @samp{"$str"$list}.
15972
15973There are also portability pitfalls with particular expansions:
15974
15975@table @code
15976@item $@@
15977@cindex @code{"$@@"}
15978One of the most famous shell-portability issues is related to
15979@samp{"$@@"}.  When there are no positional arguments, Posix says
15980that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15981original Unix version 7 Bourne shell treated it as equivalent to
15982@samp{""} instead, and this behavior survives in later implementations
15983like Digital Unix 5.0.
15984
15985The traditional way to work around this portability problem is to use
15986@samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15987Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15988the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15989
15990@example
15991zsh $ @kbd{emulate sh}
15992zsh $ @kbd{for i in "$@@"; do echo $i; done}
15993Hello World
15994!
15995zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15996Hello
15997World
15998!
15999@end example
16000
16001@noindent
16002Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16003@samp{"$@@"} because of the portability problems mentioned above.
16004One workaround relies on Zsh's ``global aliases'' to convert
16005@samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16006
16007@example
16008test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
16009@end example
16010
16011Zsh only recognizes this alias when a shell word matches it exactly;
16012@samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16013case always yields at least one shell word, use plain @samp{"$@@"}.
16014
16015A more conservative workaround is to avoid @samp{"$@@"} if it is
16016possible that there may be no positional arguments.  For example,
16017instead of:
16018
16019@example
16020cat conftest.c "$@@"
16021@end example
16022
16023you can use this instead:
16024
16025@example
16026case $# in
160270) cat conftest.c;;
16028*) cat conftest.c "$@@";;
16029esac
16030@end example
16031
16032Autoconf macros often use the @command{set} command to update
16033@samp{$@@}, so if you are writing shell code intended for
16034@command{configure} you should not assume that the value of @samp{$@@}
16035persists for any length of time.
16036
16037
16038@item $@{10@}
16039@cindex positional parameters
16040The 10th, 11th, @dots{} positional parameters can be accessed only after
16041a @code{shift}.  The 7th Edition shell reported an error if given
16042@code{$@{10@}}, and
16043Solaris 10 @command{/bin/sh} still acts that way:
16044
16045@example
16046$ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16047$ @kbd{echo $@{10@}}
16048bad substitution
16049@end example
16050
16051Conversely, not all shells obey the Posix rule that when braces are
16052omitted, multiple digits beyond a @samp{$} imply the single-digit
16053positional parameter expansion concatenated with the remaining literal
16054digits.  To work around the issue, you must use braces.
16055
16056@example
16057$ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16058a0 a0
16059$ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16060j a0
16061@end example
16062
16063@item $@{@var{var}:-@var{value}@}
16064@c Info cannot handle `:' in index entries.
16065@ifnotinfo
16066@cindex @code{$@{@var{var}:-@var{value}@}}
16067@end ifnotinfo
16068@cindex @code{$@{@var{var}-@var{value}@}}
16069Old BSD shells, including the Ultrix @code{sh}, don't accept the
16070colon for any shell substitution, and complain and die.
16071Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
16072However, all shells that support functions allow the use of colon in
16073shell substitution, and since m4sh requires functions, you can portably
16074use null variable substitution patterns in configure scripts.
16075
16076@item $@{@var{var}+@var{value}@}
16077@cindex @code{$@{@var{var}+@var{value}@}}
16078When using @samp{$@{@var{var}-@var{value}@}} or
16079@samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16080@var{value} must either be a single shell word, quoted, or in the
16081context of an unquoted here-document.  Solaris
16082@command{/bin/sh} complains otherwise.
16083
16084@example
16085$ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16086/bin/sh: bad substitution
16087$ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16088b c
16089$ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16090b c
16091$ @kbd{/bin/sh -c 'cat <<EOF
16092$@{a-b c@}
16093EOF}
16094b c
16095@end example
16096
16097According to Posix, if an expansion occurs inside double quotes, then
16098the use of unquoted double quotes within @var{value} is unspecified, and
16099any single quotes become literal characters; in that case, escaping must
16100be done with backslash.  Likewise, the use of unquoted here-documents is
16101a case where double quotes have unspecified results:
16102
16103@example
16104$ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16105/bin/sh: bad substitution
16106$ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16107b c
16108$ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16109b  c
16110$ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16111b  c
16112$ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16113'b  c'
16114$ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16115"b  c"
16116$ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16117b  c
16118$ @kbd{/bin/sh -c 'cat <<EOF
16119$@{a-"b  c"@}
16120EOF'}
16121"b  c"
16122$ @kbd{/bin/sh -c 'cat <<EOF
16123$@{a-'b  c'@}
16124EOF'}
16125'b  c'
16126$ @kbd{bash -c 'cat <<EOF
16127$@{a-"b  c"@}
16128EOF'}
16129b  c
16130$ @kbd{bash -c 'cat <<EOF
16131$@{a-'b  c'@}
16132EOF'}
16133'b  c'
16134@end example
16135
16136Perhaps the easiest way to work around quoting issues in a manner
16137portable to all shells is to place the results in a temporary variable,
16138then use @samp{$t} as the @var{value}, rather than trying to inline
16139the expression needing quoting.
16140
16141@example
16142$ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16143b  c"'@}\
16144$ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16145b  c"'@}\
16146$ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16147b  c"'@}\
16148@end example
16149
16150@item $@{@var{var}=@var{value}@}
16151@cindex @code{$@{@var{var}=@var{value}@}}
16152When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16153to @var{var}, remember that even though the assignment to @var{var} does
16154not undergo file name expansion, the result of the variable expansion
16155does unless the expansion occurred within double quotes.  In particular,
16156when using @command{:} followed by unquoted variable expansion for the
16157side effect of setting a default value, if the final value of
16158@samp{$var} contains any globbing characters (either from @var{value} or
16159from prior contents), the shell has to spend time performing file name
16160expansion and field splitting even though those results will not be
16161used.  Therefore, it is a good idea to consider double quotes when performing
16162default initialization; while remembering how this impacts any quoting
16163characters appearing in @var{value}.
16164
16165@example
16166$ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16167/usr/bin/*
16168
16169real	0m0.005s
16170user	0m0.002s
16171sys	0m0.003s
16172$ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16173/usr/bin/*
16174
16175real	0m0.039s
16176user	0m0.026s
16177sys	0m0.009s
16178$ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16179/usr/bin/*
16180
16181real	0m0.031s
16182user	0m0.020s
16183sys	0m0.010s
16184
16185$ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16186/usr/bin/*
16187
16188real	0m0.006s
16189user	0m0.002s
16190sys	0m0.003s
16191@end example
16192
16193As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16194if the @var{value} contains more than one shell word; either single
16195quotes for just the @var{value}, or double quotes around the entire
16196expansion:
16197
16198@example
16199$ @kbd{: $@{var1='Some words'@}}
16200$ @kbd{: "$@{var2=like this@}"}
16201$ @kbd{echo $var1 $var2}
16202Some words like this
16203@end example
16204
16205@noindent
16206otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16207Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16208requires that with @samp{=}, quote removal happens prior to the
16209assignment, and the expansion be the final contents of @var{var} without
16210quoting (and thus subject to field splitting), in contrast to the
16211behavior with @samp{-} passing the quoting through to the final
16212expansion.  However, @command{bash} 4.1 does not obey this rule.
16213
16214@example
16215$ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16216a  b
16217$ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16218a b
16219$ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16220a  b
16221@end example
16222
16223Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16224commands, it is unspecified whether the assignments affect the parent
16225shell environment.  It is best to perform assignments independently from
16226commands, to avoid the problems demonstrated in this example:
16227
16228@example
16229$ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16230+b+b+
16231-b-
16232$ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16233++b+
16234--
16235$ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16236+b+b+
16237--
16238@end example
16239
16240@item $@{@var{var}=@var{value}@}
16241@cindex @code{$@{@var{var}=@var{literal}@}}
16242Solaris @command{/bin/sh} has a frightening bug in its handling of
16243literal assignments.  Imagine you need set a variable to a string containing
16244@samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16245when the affected variable was already set.  This bug can be exercised
16246by running:
16247
16248@example
16249$ @kbd{unset foo}
16250$ @kbd{foo=$@{foo='@}'@}}
16251$ @kbd{echo $foo}
16252@}
16253$ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16254$ @kbd{echo $foo}
16255@}
16256$ @kbd{foo=$@{foo='@}'@}}
16257$ @kbd{echo $foo}
16258@}@}
16259 ^ ugh!
16260@end example
16261
16262It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16263though it is enclosed in single quotes.  The problem doesn't happen
16264using double quotes, or when using a temporary variable holding the
16265problematic string.
16266
16267@item $@{@var{var}=@var{expanded-value}@}
16268@cindex @code{$@{@var{var}=@var{expanded-value}@}}
16269On Ultrix,
16270running
16271
16272@example
16273default="yu,yaa"
16274: $@{var="$default"@}
16275@end example
16276
16277@noindent
16278sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16279each char is set.  You don't observe the phenomenon using a simple
16280@samp{echo $var} since apparently the shell resets the 8th bit when it
16281expands $var.  Here are two means to make this shell confess its sins:
16282
16283@example
16284$ @kbd{cat -v <<EOF
16285$var
16286EOF}
16287@end example
16288
16289@noindent
16290and
16291
16292@example
16293$ @kbd{set | grep '^var=' | cat -v}
16294@end example
16295
16296One classic incarnation of this bug is:
16297
16298@example
16299default="a b c"
16300: $@{list="$default"@}
16301for c in $list; do
16302  echo $c
16303done
16304@end example
16305
16306@noindent
16307You'll get @samp{a b c} on a single line.  Why?  Because there are no
16308spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16309bit set, hence no IFS splitting is performed!!!
16310
16311One piece of good news is that Ultrix works fine with @samp{:
16312$@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16313then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16314@var{default}!
16315
16316The portable way out consists in using a double assignment, to switch
16317the 8th bit twice on Ultrix:
16318
16319@example
16320list=$@{list="$default"@}
16321@end example
16322
16323@noindent
16324@dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16325use:
16326
16327@example
16328test "$@{var+set@}" = set || var=@var{@{value@}}
16329@end example
16330
16331@item $@{#@var{var}@}
16332@itemx $@{@var{var}%@var{word}@}
16333@itemx $@{@var{var}%%@var{word}@}
16334@itemx $@{@var{var}#@var{word}@}
16335@itemx $@{@var{var}##@var{word}@}
16336@cindex @code{$@{#@var{var}@}}
16337@cindex @code{$@{@var{var}%@var{word}@}}
16338@cindex @code{$@{@var{var}%%@var{word}@}}
16339@cindex @code{$@{@var{var}#@var{word}@}}
16340@cindex @code{$@{@var{var}##@var{word}@}}
16341Posix requires support for these usages, but they do not work with many
16342traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16343
16344Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16345example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16346@samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16347yields the empty string.
16348
16349
16350@item `@var{commands}`
16351@cindex @code{`@var{commands}`}
16352@cindex Command Substitution
16353Posix requires shells to trim all trailing newlines from command
16354output before substituting it, so assignments like
16355@samp{dir=`echo "$file" | tr a A`} do not work as expected if
16356@samp{$file} ends in a newline.
16357
16358While in general it makes no sense, do not substitute a single builtin
16359with side effects, because Ash 0.2, trying to optimize, does not fork a
16360subshell to perform the command.
16361
16362For instance, if you wanted to check that @command{cd} is silent, do not
16363use @samp{test -z "`cd /`"} because the following can happen:
16364
16365@example
16366$ @kbd{pwd}
16367/tmp
16368$ @kbd{test -z "`cd /`" && pwd}
16369/
16370@end example
16371
16372@noindent
16373The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16374
16375The MSYS shell leaves a stray byte in the expansion of a double-quoted
16376command substitution of a native program, if the end of the substitution
16377is not aligned with the end of the double quote.  This may be worked
16378around by inserting another pair of quotes:
16379
16380@example
16381$ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16382$ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16383- broken differ: char 4, line 1
16384@end example
16385
16386Upon interrupt or SIGTERM, some shells may abort a command substitution,
16387replace it with a null string, and wrongly evaluate the enclosing
16388command before entering the trap or ending the script.  This can lead to
16389spurious errors:
16390
16391@example
16392$ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16393$ @kbd{^C}
16394sh: test: hi: unexpected operator/operand
16395@end example
16396
16397@noindent
16398You can avoid this by assigning the command substitution to a temporary
16399variable:
16400
16401@example
16402$ @kbd{sh -c 'res=`sleep 5; echo hi`
16403         if test "x$res" = xhi; then echo yes; fi'}
16404$ @kbd{^C}
16405@end example
16406
16407@item $(@var{commands})
16408@cindex @code{$(@var{commands})}
16409This construct is meant to replace @samp{`@var{commands}`},
16410and it has most of the problems listed under @code{`@var{commands}`}.
16411
16412This construct can be
16413nested while this is impossible to do portably with back quotes.
16414Unfortunately it is not yet universally supported.  Most notably, even recent
16415releases of Solaris don't support it:
16416
16417@example
16418$ @kbd{showrev -c /bin/sh | grep version}
16419Command version: SunOS 5.10 Generic 121005-03 Oct 2006
16420$ @kbd{echo $(echo blah)}
16421syntax error: `(' unexpected
16422@end example
16423
16424@noindent
16425nor does IRIX 6.5's Bourne shell:
16426@example
16427$ @kbd{uname -a}
16428IRIX firebird-image 6.5 07151432 IP22
16429$ @kbd{echo $(echo blah)}
16430$(echo blah)
16431@end example
16432
16433If you do use @samp{$(@var{commands})}, make sure that the commands
16434do not start with a parenthesis, as that would cause confusion with
16435a different notation @samp{$((@var{expression}))} that in modern
16436shells is an arithmetic expression not a command.  To avoid the
16437confusion, insert a space between the two opening parentheses.
16438
16439Avoid @var{commands} that contain unbalanced parentheses in
16440here-documents, comments, or case statement patterns, as many shells
16441mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
164425.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16443
16444@example
16445echo $(case x in x) echo hello;; esac)
16446@end example
16447
16448
16449@item $((@var{expression}))
16450@cindex @code{$((@var{expression}))}
16451Arithmetic expansion is not portable as some shells (most
16452notably Solaris 10 @command{/bin/sh}) don't support it.
16453
16454Among shells that do support @samp{$(( ))}, not all of them obey the
16455Posix rule that octal and hexadecimal constants must be recognized:
16456
16457@example
16458$ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
1645924
16460$ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
1646126
16462$ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
1646324
16464$ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16465pdksh:  010 + 0x10 : bad number `0x10'
16466$ @kbd{pdksh -c 'echo $(( 010 ))'}
1646710
16468@end example
16469
16470When it is available, using arithmetic expansion provides a noticeable
16471speedup in script execution; but testing for support requires
16472@command{eval} to avoid syntax errors.  The following construct is used
16473by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16474arguments are provided in decimal and without a leading zero, and all
16475operators are properly quoted and appear as distinct arguments:
16476
16477@example
16478if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16479  eval 'func_arith ()
16480  @{
16481    func_arith_result=$(( $* ))
16482  @}'
16483else
16484  func_arith ()
16485  @{
16486    func_arith_result=`expr "$@@"`
16487  @}
16488fi
16489func_arith 1 + 1
16490foo=$func_arith_result
16491@end example
16492
16493
16494@item ^
16495@cindex @code{^} quoting
16496Always quote @samp{^}, otherwise traditional shells such as
16497@command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16498
16499@end table
16500
16501
16502@node Assignments
16503@section Assignments
16504@cindex Shell assignments
16505
16506When setting several variables in a row, be aware that the order of the
16507evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16508gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16509You must use
16510@samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16511
16512Don't rely on the following to find @file{subdir/program}:
16513
16514@example
16515PATH=subdir$PATH_SEPARATOR$PATH program
16516@end example
16517
16518@noindent
16519as this does not work with Zsh 3.0.6.  Use something like this
16520instead:
16521
16522@example
16523(PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16524@end example
16525
16526Don't rely on the exit status of an assignment: Ash 0.2 does not change
16527the status and propagates that of the last statement:
16528
16529@example
16530$ @kbd{false || foo=bar; echo $?}
165311
16532$ @kbd{false || foo=`:`; echo $?}
165330
16534@end example
16535
16536@noindent
16537and to make things even worse, QNX 4.25 just sets the exit status
16538to 0 in any case:
16539
16540@example
16541$ @kbd{foo=`exit 1`; echo $?}
165420
16543@end example
16544
16545To assign default values, follow this algorithm:
16546
16547@enumerate
16548@item
16549If the default value is a literal and does not contain any closing
16550brace, use:
16551
16552@example
16553: "$@{var='my literal'@}"
16554@end example
16555
16556@item
16557If the default value contains no closing brace, has to be expanded, and
16558the variable being initialized is not intended to be IFS-split
16559(i.e., it's not a list), then use:
16560
16561@example
16562: $@{var="$default"@}
16563@end example
16564
16565@item
16566If the default value contains no closing brace, has to be expanded, and
16567the variable being initialized is intended to be IFS-split (i.e., it's a list),
16568then use:
16569
16570@example
16571var=$@{var="$default"@}
16572@end example
16573
16574@item
16575If the default value contains a closing brace, then use:
16576
16577@example
16578test "$@{var+set@}" = set || var="has a '@}'"
16579@end example
16580@end enumerate
16581
16582In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16583doubt, just use the last form.  @xref{Shell Substitutions}, items
16584@samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16585for the rationale.
16586
16587@node Parentheses
16588@section Parentheses in Shell Scripts
16589@cindex Shell parentheses
16590
16591Beware of two opening parentheses in a row, as many shell
16592implementations treat them specially, and Posix says that a portable
16593script cannot use @samp{((} outside the @samp{$((} form used for shell
16594arithmetic.  In traditional shells, @samp{((cat))} behaves like
16595@samp{(cat)}; but many shells, including
16596Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16597expression equivalent to @samp{let "cat"}, and may or may not report an
16598error when they detect that @samp{cat} is not a number.  As another
16599example, @samp{pdksh} 5.2.14 does not treat the following code
16600as a traditional shell would:
16601
16602@example
16603if ((true) || false); then
16604  echo ok
16605fi
16606@end example
16607
16608@noindent
16609To work around this problem, insert a space between the two opening
16610parentheses.  There is a similar problem and workaround with
16611@samp{$((}; see @ref{Shell Substitutions}.
16612
16613@node Slashes
16614@section Slashes in Shell Scripts
16615@cindex Shell slashes
16616
16617Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16618arguments that contain two trailing slashes:
16619
16620@example
16621$ @kbd{echo / // /// //// .// //.}
16622/ / // /// ./ //.
16623$ @kbd{x=//}
16624$ @kbd{eval "echo \$x"}
16625/
16626$ @kbd{set -x}
16627$ @kbd{echo abc | tr -t ab //}
16628+ echo abc
16629+ tr -t ab /
16630/bc
16631@end example
16632
16633Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16634variable is empty and the second double-quote is followed by a word that
16635begins and ends with slash:
16636
16637@example
16638$ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16639p=
16640+ echo //ouch/
16641//ouch/
16642@end example
16643
16644However, our understanding is that patches are available, so perhaps
16645it's not worth worrying about working around these horrendous bugs.
16646
16647@node Special Shell Variables
16648@section Special Shell Variables
16649@cindex Shell variables
16650@cindex Special shell variables
16651
16652Some shell variables should not be used, since they can have a deep
16653influence on the behavior of the shell.  In order to recover a sane
16654behavior from the shell, some variables should be unset; M4sh takes
16655care of this and provides fallback values, whenever needed, to cater
16656for a very old @file{/bin/sh} that does not support @command{unset}.
16657(@pxref{Portable Shell, , Portable Shell Programming}).
16658
16659As a general rule, shell variable names containing a lower-case letter
16660are safe; you can define and use these variables without worrying about
16661their effect on the underlying system, and without worrying about
16662whether the shell changes them unexpectedly.  (The exception is the
16663shell variable @code{status}, as described below.)
16664
16665Here is a list of names that are known to cause trouble.  This list is
16666not exhaustive, but you should be safe if you avoid the name
16667@code{status} and names containing only upper-case letters and
16668underscores.
16669
16670@c Alphabetical order, case insensitive, `A' before `a'.
16671@table @code
16672@item ?
16673Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16674, Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16675correctly in shell functions (@pxref{Shell Functions}) or in traps
16676(@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16677@samp{$?} to zero after an empty command.
16678
16679@example
16680$ @kbd{bash -c 'false; $empty; echo $?'}
166810
16682$ @kbd{zsh -c 'false; $empty; echo $?'}
166831
16684@end example
16685
16686@item _
16687@evindex _
16688Many shells reserve @samp{$_} for various purposes, e.g., the name of
16689the last command executed.
16690
16691@item BIN_SH
16692@evindex BIN_SH
16693In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16694the standard shell conform to Posix.
16695
16696@item CDPATH
16697@evindex CDPATH
16698When this variable is set it specifies a list of directories to search
16699when invoking @code{cd} with a relative file name that did not start
16700with @samp{./} or @samp{../}.  Posix
167011003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16702is used successfully, @code{cd} prints the resulting absolute
16703file name.  Unfortunately this output can break idioms like
16704@samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16705Also, many shells do not conform to this part of Posix; for
16706example, @command{zsh} prints the result only if a directory name
16707other than @file{.} was chosen from @env{CDPATH}.
16708
16709In practice the shells that have this problem also support
16710@command{unset}, so you can work around the problem as follows:
16711
16712@example
16713(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16714@end example
16715
16716You can also avoid output by ensuring that your directory name is
16717absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16718
16719Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16720possible, so you need not worry about this problem in those scripts.
16721
16722@item CLICOLOR_FORCE
16723@evindex CLICOLOR_FORCE
16724When this variable is set, some implementations of tools like
16725@command{ls} attempt to add color to their output via terminal escape
16726sequences, even when the output is not directed to a terminal, and can
16727thus cause spurious failures in scripts.  Configure scripts use M4sh,
16728which automatically unsets this variable.
16729
16730@item DUALCASE
16731@evindex DUALCASE
16732In the MKS shell, case statements and file name generation are
16733case-insensitive unless @env{DUALCASE} is nonzero.
16734Autoconf-generated scripts export this variable when they start up.
16735
16736@item ENV
16737@itemx MAIL
16738@itemx MAILPATH
16739@itemx PS1
16740@itemx PS2
16741@itemx PS4
16742@evindex ENV
16743@evindex MAIL
16744@evindex MAILPATH
16745@evindex PS1
16746@evindex PS2
16747@evindex PS4
16748These variables should not matter for shell scripts, since they are
16749supposed to affect only interactive shells.  However, at least one
16750shell (the pre-3.0 UWIN Korn shell) gets confused about
16751whether it is interactive, which means that (for example) a @env{PS1}
16752with a side effect can unexpectedly modify @samp{$?}.  To work around
16753this bug, M4sh scripts (including @file{configure} scripts) do something
16754like this:
16755
16756@example
16757(unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16758PS1='$ '
16759PS2='> '
16760PS4='+ '
16761@end example
16762
16763@noindent
16764(actually, there is some complication due to bugs in @command{unset};
16765@pxref{unset, , Limitations of Shell Builtins}).
16766
16767@item FPATH
16768@evindex FPATH
16769The Korn shell uses @env{FPATH} to find shell functions, so avoid
16770@env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16771@env{PATH}, but you still need to be wary of tests that use @env{PATH}
16772to find whether a command exists, since they might report the wrong
16773result if @env{FPATH} is also set.
16774
16775@item GREP_OPTIONS
16776@evindex GREP_OPTIONS
16777When this variable is set, some implementations of @command{grep} honor
16778these options, even if the options include direction to enable colored
16779output via terminal escape sequences, and the result can cause spurious
16780failures when the output is not directed to a terminal.  Configure
16781scripts use M4sh, which automatically unsets this variable.
16782
16783@item IFS
16784@evindex IFS
16785Long ago, shell scripts inherited @env{IFS} from the environment,
16786but this caused many problems so modern shells ignore any environment
16787settings for @env{IFS}.
16788
16789Don't set the first character of @env{IFS} to backslash.  Indeed,
16790Bourne shells use the first character (backslash) when joining the
16791components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16792backslash escapes, so you can end up with backspace and other strange
16793characters.
16794
16795The proper value for @env{IFS} (in regular code, not when performing
16796splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16797especially important, as it is used to join the arguments in @samp{$*};
16798however, note that traditional shells, but also bash-2.04, fail to adhere
16799to this and join with a space anyway.
16800
16801M4sh guarantees that @env{IFS} will have the default value at the
16802beginning of a script, and many macros within autoconf rely on this
16803setting.  It is okay to use blocks of shell code that temporarily change
16804the value of @env{IFS} in order to split on another character, but
16805remember to restore it before expanding further macros.
16806
16807Unsetting @code{IFS} instead of resetting it to the default sequence
16808is not suggested, since code that tries to save and restore the
16809variable's value will incorrectly reset it to an empty value, thus
16810disabling field splitting:
16811
16812@example
16813unset IFS
16814# default separators used for field splitting
16815
16816save_IFS=$IFS
16817IFS=:
16818# ...
16819IFS=$save_IFS
16820# no field splitting performed
16821@end example
16822
16823@item LANG
16824@itemx LC_ALL
16825@itemx LC_COLLATE
16826@itemx LC_CTYPE
16827@itemx LC_MESSAGES
16828@itemx LC_MONETARY
16829@itemx LC_NUMERIC
16830@itemx LC_TIME
16831@evindex LANG
16832@evindex LC_ALL
16833@evindex LC_COLLATE
16834@evindex LC_CTYPE
16835@evindex LC_MESSAGES
16836@evindex LC_MONETARY
16837@evindex LC_NUMERIC
16838@evindex LC_TIME
16839
16840You should set all these variables to @samp{C} because so much
16841configuration code assumes the C locale and Posix requires that locale
16842environment variables be set to @samp{C} if the C locale is desired;
16843@file{configure} scripts and M4sh do that for you.
16844Export these variables after setting them.
16845
16846@c  However, some older, nonstandard
16847@c  systems (notably SCO) break if locale environment variables
16848@c  are set to @samp{C}, so when running on these systems
16849@c  Autoconf-generated scripts unset the variables instead.
16850
16851@item LANGUAGE
16852@evindex LANGUAGE
16853
16854@env{LANGUAGE} is not specified by Posix, but it is a GNU
16855extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16856should set it too.
16857
16858@item LC_ADDRESS
16859@itemx LC_IDENTIFICATION
16860@itemx LC_MEASUREMENT
16861@itemx LC_NAME
16862@itemx LC_PAPER
16863@itemx LC_TELEPHONE
16864@evindex LC_ADDRESS
16865@evindex LC_IDENTIFICATION
16866@evindex LC_MEASUREMENT
16867@evindex LC_NAME
16868@evindex LC_PAPER
16869@evindex LC_TELEPHONE
16870
16871These locale environment variables are GNU extensions.  They
16872are treated like their Posix brethren (@env{LC_COLLATE},
16873etc.)@: as described above.
16874
16875@item LINENO
16876@evindex LINENO
16877Most modern shells provide the current line number in @code{LINENO}.
16878Its value is the line number of the beginning of the current command.
16879M4sh, and hence Autoconf, attempts to execute @command{configure} with
16880a shell that supports @code{LINENO}.  If no such shell is available, it
16881attempts to implement @code{LINENO} with a Sed prepass that replaces each
16882instance of the string @code{$LINENO} (not followed by an alphanumeric
16883character) with the line's number.  In M4sh scripts you should execute
16884@code{AS_LINENO_PREPARE} so that these workarounds are included in
16885your script; configure scripts do this automatically in @code{AC_INIT}.
16886
16887You should not rely on @code{LINENO} within @command{eval} or shell
16888functions, as the behavior differs in practice.  The presence of a
16889quoted newline within simple commands can alter which line number is
16890used as the starting point for @code{$LINENO} substitutions within that
16891command.  Also, the possibility of the Sed prepass means that you should
16892not rely on @code{$LINENO} when quoted, when in here-documents, or when
16893line continuations are used.  Subshells should be OK, though.  In the
16894following example, lines 1, 9, and 14 are portable, but the other
16895instances of @code{$LINENO} do not have deterministic values:
16896
16897@example
16898@group
16899$ @kbd{cat lineno}
16900echo 1. $LINENO
16901echo "2. $LINENO
169023. $LINENO"
16903cat <<EOF
169045. $LINENO
169056. $LINENO
169067. \$LINENO
16907EOF
16908( echo 9. $LINENO )
16909eval 'echo 10. $LINENO'
16910eval 'echo 11. $LINENO
16911echo 12. $LINENO'
16912echo 13. '$LINENO'
16913echo 14. $LINENO '
1691415.' $LINENO
16915f () @{ echo $1 $LINENO;
16916echo $1 $LINENO @}
16917f 18.
16918echo 19. \
16919$LINENO
16920@end group
16921@group
16922$ @kbd{bash-3.2 ./lineno}
169231. 1
169242. 3
169253. 3
169265. 4
169276. 4
169287. $LINENO
169299. 9
1693010. 10
1693111. 12
1693212. 13
1693313. $LINENO
1693414. 14
1693515. 14
1693618. 16
1693718. 17
1693819. 19
16939@end group
16940@group
16941$ @kbd{zsh-4.3.4 ./lineno}
169421. 1
169432. 2
169443. 2
169455. 4
169466. 4
169477. $LINENO
169489. 9
1694910. 1
1695011. 1
1695112. 2
1695213. $LINENO
1695314. 14
1695415. 14
1695518. 0
1695618. 1
1695719. 19
16958@end group
16959@group
16960$ @kbd{pdksh-5.2.14 ./lineno}
169611. 1
169622. 2
169633. 2
169645. 4
169656. 4
169667. $LINENO
169679. 9
1696810. 0
1696911. 0
1697012. 0
1697113. $LINENO
1697214. 14
1697315. 14
1697418. 16
1697518. 17
1697619. 19
16977@end group
16978@group
16979$ @kbd{sed '=' <lineno |}
16980> @kbd{  sed '}
16981> @kbd{    N}
16982> @kbd{    s,$,-,}
16983> @kbd{    t loop}
16984> @kbd{    :loop}
16985> @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16986> @kbd{    t loop}
16987> @kbd{    s,-$,,}
16988> @kbd{    s,^[0-9]*\n,,}
16989> @kbd{  ' |}
16990> @kbd{  sh}
169911. 1
169922. 2
169933. 3
169945. 5
169956. 6
169967. \7
169979. 9
1699810. 10
1699911. 11
1700012. 12
1700113. 13
1700214. 14
1700315. 15
1700418. 16
1700518. 17
1700619. 20
17007@end group
17008@end example
17009
17010In particular, note that @file{config.status} (and any other subsidiary
17011script created by @code{AS_INIT_GENERATED}) might report line numbers
17012relative to the parent script as a result of the potential Sed pass.
17013
17014@item NULLCMD
17015@evindex NULLCMD
17016When executing the command @samp{>foo}, @command{zsh} executes
17017@samp{$NULLCMD >foo} unless it is operating in Bourne shell
17018compatibility mode and the @command{zsh} version is newer
17019than 3.1.6-dev-18.  If you are using an older @command{zsh}
17020and forget to set @env{NULLCMD},
17021your script might be suspended waiting for data on its standard input.
17022
17023@item options
17024@evindex options
17025For @command{zsh} 4.3.10, @env{options} is treated as an associative
17026array even after @code{emulate sh}, so it should not be used.
17027
17028@item PATH_SEPARATOR
17029@evindex PATH_SEPARATOR
17030On DJGPP systems, the @env{PATH_SEPARATOR} environment
17031variable can be set to either @samp{:} or @samp{;} to control the path
17032separator Bash uses to set up certain environment variables (such as
17033@env{PATH}).  You can set this variable to @samp{;} if you want
17034@command{configure} to use @samp{;} as a separator; this might be useful
17035if you plan to use non-Posix shells to execute files.  @xref{File System
17036Conventions}, for more information about @code{PATH_SEPARATOR}.
17037
17038@item POSIXLY_CORRECT
17039@evindex POSIXLY_CORRECT
17040In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17041(even empty) causes programs to try harder to conform to Posix.
17042Autoconf does not directly manipulate this variable, but @command{bash}
17043ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17044running in Posix mode.  Therefore, take care when exporting or unsetting
17045this variable, so as not to change whether @command{bash} is in Posix
17046mode.
17047
17048@example
17049$ @kbd{bash --posix -c 'set -o | grep posix}
17050> @kbd{unset POSIXLY_CORRECT}
17051> @kbd{set -o | grep posix'}
17052posix           on
17053posix           off
17054@end example
17055
17056@item PWD
17057@evindex PWD
17058Posix 1003.1-2001 requires that @command{cd} and
17059@command{pwd} must update the @env{PWD} environment variable to point
17060to the logical name of the current directory, but traditional shells
17061do not support this.  This can cause confusion if one shell instance
17062maintains @env{PWD} but a subsidiary and different shell does not know
17063about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17064points to the wrong directory.  Use @samp{`pwd`} rather than
17065@samp{$PWD}.
17066
17067@item RANDOM
17068@evindex RANDOM
17069Many shells provide @code{RANDOM}, a variable that returns a different
17070integer each time it is used.  Most of the time, its value does not
17071change when it is not used, but on IRIX 6.5 the value changes all
17072the time.  This can be observed by using @command{set}.  It is common
17073practice to use @code{$RANDOM} as part of a file name, but code
17074shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17075
17076@item status
17077@evindex status
17078This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17079hence read-only.  Do not use it.
17080@end table
17081
17082@node Shell Functions
17083@section Shell Functions
17084@cindex Shell Functions
17085
17086Nowadays, it is difficult to find a shell that does not support
17087shell functions at all.  However, some differences should be expected.
17088
17089When declaring a shell function, you must include whitespace between the
17090@samp{)} after the function name and the start of the compound
17091expression, to avoid upsetting @command{ksh}.  While it is possible to
17092use any compound command, most scripts use @samp{@{@dots{}@}}.
17093
17094@example
17095$ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17096hi
17097$ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17098ksh: syntax error at line 1: `@}' unexpected
17099$ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17100hi
17101@end example
17102
17103Inside a shell function, you should not rely on the error status of a
17104subshell if the last command of that subshell was @code{exit} or
17105@code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17106find a shell that does not exhibit the bug, zsh might be the only shell
17107present on the user's machine.
17108
17109Likewise, the state of @samp{$?} is not reliable when entering a shell
17110function.  This has the effect that using a function as the first
17111command in a @command{trap} handler can cause problems.
17112
17113@example
17114$ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
171152
171162
17117$ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
171180
171192
17120@end example
17121
17122DJGPP bash 2.04 has a bug in that @command{return} from a
17123shell function which also used a command substitution causes a
17124segmentation fault.  To work around the issue, you can use
17125@command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17126in the execution flow of the function (@pxref{Common Shell Constructs}).
17127
17128Not all shells treat shell functions as simple commands impacted by
17129@samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17130
17131@example
17132$ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17133$ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17134oops
17135@end example
17136
17137Shell variables and functions may share the same namespace, for example
17138with Solaris 10 @command{/bin/sh}:
17139
17140@example
17141$ @kbd{f () @{ :; @}; f=; f}
17142f: not found
17143@end example
17144
17145@noindent
17146For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17147uses the prefix @samp{as_fn_} for its functions.
17148
17149Handling of positional parameters and shell options varies among shells.
17150For example, Korn shells reset and restore trace output (@samp{set -x})
17151and other options upon function entry and exit.  Inside a function,
17152IRIX sh sets @samp{$0} to the function name.
17153
17154It is not portable to pass temporary environment variables to shell
17155functions.  Solaris @command{/bin/sh} does not see the variable.
17156Meanwhile, not all shells follow the Posix rule that the assignment must
17157affect the current environment in the same manner as special built-ins.
17158
17159@example
17160$ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17161@result{}
17162@result{}
17163$ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17164@result{}1
17165@result{}
17166$ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17167@result{}1
17168@result{}1
17169@end example
17170
17171Some ancient Bourne shell variants with function support did not reset
17172@samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17173arguments of the script were lost after the first function invocation.
17174It is probably not worth worrying about these shells any more.
17175
17176With AIX sh, a @command{trap} on 0 installed in a shell function
17177triggers at function exit rather than at script exit.  @xref{trap, ,
17178Limitations of Shell Builtins}.
17179
17180@node Limitations of Builtins
17181@section Limitations of Shell Builtins
17182@cindex Shell builtins
17183@cindex Limitations of shell builtins
17184
17185No, no, we are serious: some shells do have limitations!  :)
17186
17187You should always keep in mind that any builtin or command may support
17188options, and therefore differ in behavior with arguments
17189starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17190can give unexpected results when @code{word} starts with a dash.  It is
17191often possible to avoid this problem using @samp{echo "x$word"}, taking
17192the @samp{x} into account later in the pipe.  Many of these limitations
17193can be worked around using M4sh (@pxref{Programming in M4sh}).
17194
17195@c This table includes things like `@command{test} (files)', so we can't
17196@c use @table @command.
17197@table @asis
17198@item @command{.}
17199@c --------------
17200@prindex @command{.}
17201Use @command{.} only with regular files (use @samp{test -f}).  Bash
172022.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17203@command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17204some shells, including bash 3.2, implicitly append the current directory
17205to this @env{PATH} search, even though Posix forbids it.  So if you want
17206to use @command{.} on a file @file{foo} in the current directory, you
17207must use @samp{. ./foo}.
17208
17209Not all shells gracefully handle syntax errors within a sourced file.
17210On one extreme, some non-interactive shells abort the entire script.  On
17211the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17212syntax error.
17213
17214@example
17215$ @kbd{echo 'fi' > syntax}
17216$ @kbd{bash -c '. ./syntax; echo $?'}
17217./syntax: line 1: syntax error near unexpected token `fi'
17218./syntax: line 1: `fi'
172191
17220$ @kbd{ash -c '. ./syntax; echo $?'}
17221./syntax: 1: Syntax error: "fi" unexpected
17222$ @kbd{zsh -c '. ./syntax; echo $?'}
17223./syntax:1: parse error near `fi'
172240
17225@end example
17226
17227@item @command{!}
17228@c --------------
17229@prindex @command{!}
17230The Unix version 7 shell did not support
17231negating the exit status of commands with @command{!}, and this feature
17232is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17233Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17234bugs when using @command{!}:
17235
17236@example
17237$ @kbd{sh -c '! : | :'; echo $?}
172381
17239$ @kbd{ash -c '! : | :'; echo $?}
172400
17241$ @kbd{sh -c '! @{ :; @}'; echo $?}
172421
17243$ @kbd{ash -c '! @{ :; @}'; echo $?}
17244@{: not found
17245Syntax error: "@}" unexpected
172462
17247@end example
17248
17249Shell code like this:
17250
17251@example
17252if ! cmp file1 file2 >/dev/null 2>&1; then
17253  echo files differ or trouble
17254fi
17255@end example
17256
17257is therefore not portable in practice.  Typically it is easy to rewrite
17258such code, e.g.:
17259
17260@example
17261cmp file1 file2 >/dev/null 2>&1 ||
17262  echo files differ or trouble
17263@end example
17264
17265More generally, one can always rewrite @samp{! @var{command}} as:
17266
17267@example
17268if @var{command}; then (exit 1); else :; fi
17269@end example
17270
17271
17272@item @command{@{...@}}
17273@c --------------------
17274@prindex @command{@{...@}}
17275Bash 3.2 (and earlier versions) sometimes does not properly set
17276@samp{$?} when failing to write redirected output of a compound command.
17277This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17278not occur with @samp{(@dots{})}.  For example:
17279
17280@example
17281$ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17282bash: line 1: /bad: Permission denied
172830
17284$ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17285bash: line 1: /bad: Permission denied
172860
17287@end example
17288
17289To work around the bug, prepend @samp{:;}:
17290
17291@example
17292$ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17293bash: line 1: /bad: Permission denied
172941
17295@end example
17296
17297Posix requires a syntax error if a brace list has no contents.  However,
17298not all shells obey this rule; and on shells where empty lists are
17299permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17300ensure that a brace list is never empty.
17301
17302@example
17303$ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17304bash: line 1: syntax error near unexpected token `@}'
17305bash: line 1: `false; @{ @}; echo $?'
173062
17307$ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
173081
17309$ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
173100
17311@end example
17312
17313
17314@item @command{break}
17315@c ------------------
17316@prindex @command{break}
17317The use of @samp{break 2} etc.@: is safe.
17318
17319
17320@anchor{case}
17321@item @command{case}
17322@c -----------------
17323@prindex @command{case}
17324You don't need to quote the argument; no splitting is performed.
17325
17326You don't need the final @samp{;;}, but you should use it.
17327
17328Posix requires support for @code{case} patterns with opening
17329parentheses like this:
17330
17331@example
17332case $file_name in
17333  (*.c) echo "C source code";;
17334esac
17335@end example
17336
17337@noindent
17338but the @code{(} in this example is not portable to many Bourne
17339shell implementations, which is a pity for those of us using tools that
17340rely on balanced parentheses.  For instance, with Solaris
17341@command{/bin/sh}:
17342
17343@example
17344$ @kbd{case foo in (foo) echo foo;; esac}
17345@error{}syntax error: `(' unexpected
17346@end example
17347
17348@noindent
17349The leading @samp{(} can be omitted safely.  Unfortunately, there are
17350contexts where unbalanced parentheses cause other problems, such as when
17351using a syntax-highlighting editor that searches for the balancing
17352counterpart, or more importantly, when using a case statement as an
17353underquoted argument to an Autoconf macro.  @xref{Balancing
17354Parentheses}, for tradeoffs involved in various styles of dealing with
17355unbalanced @samp{)}.
17356
17357Zsh handles pattern fragments derived from parameter expansions or
17358command substitutions as though quoted:
17359
17360@example
17361$ pat=\?; case aa in ?$pat) echo match;; esac
17362$ pat=\?; case a? in ?$pat) echo match;; esac
17363match
17364@end example
17365
17366@noindent
17367Because of a bug in its @code{fnmatch}, Bash fails to properly
17368handle backslashes in character classes:
17369
17370@example
17371bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17372bash-2.02$
17373@end example
17374
17375@noindent
17376This is extremely unfortunate, since you are likely to use this code to
17377handle Posix or MS-DOS absolute file names.  To work around this
17378bug, always put the backslash first:
17379
17380@example
17381bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17382OK
17383bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17384OK
17385@end example
17386
17387Many Bourne shells cannot handle closing brackets in character classes
17388correctly.
17389
17390Some shells also have problems with backslash escaping in case you do not want
17391to match the backslash: both a backslash and the escaped character match this
17392pattern.  To work around this, specify the character class in a variable, so
17393that quote removal does not apply afterwards, and the special characters don't
17394have to be backslash-escaped:
17395
17396@example
17397$ @kbd{case '\' in [\<]) echo OK;; esac}
17398OK
17399$ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17400$
17401@end example
17402
17403Even with this, Solaris @command{ksh} matches a backslash if the set
17404contains any
17405of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17406
17407Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17408a closing parenthesis if not specified in a character class:
17409
17410@example
17411$ @kbd{case foo in *\)*) echo fail ;; esac}
17412fail
17413$ @kbd{case foo in *')'*) echo fail ;; esac}
17414fail
17415@end example
17416
17417Some shells, such as Ash 0.3.8, are confused by an empty
17418@code{case}/@code{esac}:
17419
17420@example
17421ash-0.3.8 $ @kbd{case foo in esac;}
17422@error{}Syntax error: ";" unexpected (expecting ")")
17423@end example
17424
17425Posix requires @command{case} to give an exit status of 0 if no cases
17426match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17427rule.  Meanwhile, it is unclear whether a case that matches, but
17428contains no statements, must also change the exit status to 0.  The M4sh
17429macro @code{AS_CASE} works around these inconsistencies.
17430
17431@example
17432$ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
174330
17434$ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17435255
17436@end example
17437
17438
17439@item @command{cd}
17440@c ---------------
17441@prindex @command{cd}
17442Posix 1003.1-2001 requires that @command{cd} must support
17443the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17444with @option{-L} being the default.  However, traditional shells do
17445not support these options, and their @command{cd} command has the
17446@option{-P} behavior.
17447
17448Portable scripts should assume neither option is supported, and should
17449assume neither behavior is the default.  This can be a bit tricky,
17450since the Posix default behavior means that, for example,
17451@samp{ls ..} and @samp{cd ..} may refer to different directories if
17452the current logical directory is a symbolic link.  It is safe to use
17453@code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17454Also, Autoconf-generated scripts check for this problem when computing
17455variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17456so it is safe to @command{cd} to these variables.
17457
17458Posix states that behavior is undefined if @command{cd} is given an
17459explicit empty argument.  Some shells do nothing, some change to the
17460first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17461the shell rather than returning an error.  Unfortunately, this means
17462that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17463than @samp{cd $var} (at least the latter is well-behaved in all shells
17464at changing to @env{HOME}, although this is probably not what you wanted
17465in a script).  You should check that a directory name was supplied
17466before trying to change locations.
17467
17468@xref{Special Shell Variables}, for portability problems involving
17469@command{cd} and the @env{CDPATH} environment variable.
17470Also please see the discussion of the @command{pwd} command.
17471
17472
17473@anchor{echo}
17474@item @command{echo}
17475@c -----------------
17476@prindex @command{echo}
17477The simple @command{echo} is probably the most surprising source of
17478portability troubles.  It is not possible to use @samp{echo} portably
17479unless both options and escape sequences are omitted.  Don't expect any
17480option.
17481
17482Do not use backslashes in the arguments, as there is no consensus on
17483their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17484Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17485The problem is truly @command{echo}: all the shells
17486understand @samp{'\n'} as the string composed of a backslash and an
17487@samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17488mess up the internal state of ksh88 on AIX 6.1 so that it will print
17489the first character @samp{s} only, followed by a newline, and then
17490entirely drop the output of the next echo in a command substitution.
17491
17492Because of these problems, do not pass a string containing arbitrary
17493characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17494only if you know that @var{foo}'s value cannot contain backslashes and
17495cannot start with @samp{-}.
17496
17497If this may not be true, @command{printf} is in general safer and
17498easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
17499where portability is not a major concern should use @command{printf
17500'%s\n'} whenever @command{echo} could fail, and similarly use
17501@command{printf %s} instead of @command{echo -n}. For portable shell
17502scripts, instead, it is suggested to use a here-document like this:
17503
17504@example
17505cat <<EOF
17506$foo
17507EOF
17508@end example
17509
17510Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
17511which choose between various portable implementations: @samp{echo}
17512or @samp{print} where they work, @command{printf} if it is available,
17513or else other creative tricks in order to work around the above problems.
17514
17515
17516@item @command{eval}
17517@c -----------------
17518@prindex @command{eval}
17519The @command{eval} command is useful in limited circumstances, e.g.,
17520using commands like @samp{eval table_$key=\$value} and @samp{eval
17521value=table_$key} to simulate a hash table when the key is known to be
17522alphanumeric.
17523
17524You should also be wary of common bugs in @command{eval} implementations.
17525In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17526@command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
175274.2.5), the arguments of @samp{eval} are evaluated in a context where
17528@samp{$?} is 0, so they exhibit behavior like this:
17529
17530@example
17531$ @kbd{false; eval 'echo $?'}
175320
17533@end example
17534
17535The correct behavior here is to output a nonzero value,
17536but portable scripts should not rely on this.
17537
17538You should not rely on @code{LINENO} within @command{eval}.
17539@xref{Special Shell Variables}.
17540
17541Note that, even though these bugs are easily avoided,
17542@command{eval} is tricky to use on arbitrary arguments.
17543It is obviously unwise to use @samp{eval $cmd} if the string value of
17544@samp{cmd} was derived from an untrustworthy source.  But even if the
17545string value is valid, @samp{eval $cmd} might not work as intended,
17546since it causes field splitting and file name expansion to occur twice,
17547once for the @command{eval} and once for the command itself.  It is
17548therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17549has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17550equivalent of @samp{cat test;.c} if there happens to be a file named
17551@file{test;.c} in the current directory; and this in turn
17552mistakenly attempts to invoke @command{cat} on the file @file{test} and
17553then execute the command @command{.c}.  To avoid this problem, use
17554@samp{eval "$cmd"} rather than @samp{eval $cmd}.
17555
17556However, suppose that you want to output the text of the evaluated
17557command just before executing it.  Assuming the previous example,
17558@samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17559this output doesn't show the user that @samp{test;.c} is the actual name
17560of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17561works on this example, but it fails with @samp{cmd='cat foo >bar'},
17562since it mistakenly replaces the contents of @file{bar} by the
17563string @samp{cat foo}.  No simple, general, and portable solution to
17564this problem is known.
17565
17566@item @command{exec}
17567@c -----------------
17568@prindex @command{exec}
17569Posix describes several categories of shell built-ins.  Special
17570built-ins (such as @command{exit}) must impact the environment of the
17571current shell, and need not be available through @command{exec}.  All
17572other built-ins are regular, and must not propagate variable assignments
17573to the environment of the current shell.  However, the group of regular
17574built-ins is further distinguished by commands that do not require a
17575@env{PATH} search (such as @command{cd}), in contrast to built-ins that
17576are offered as a more efficient version of something that must still be
17577found in a @env{PATH} search (such as @command{echo}).  Posix is not
17578clear on whether @command{exec} must work with the list of 17 utilities
17579that are invoked without a @env{PATH} search, and many platforms lack an
17580executable for some of those built-ins:
17581
17582@example
17583$ @kbd{sh -c 'exec cd /tmp'}
17584sh: line 0: exec: cd: not found
17585@end example
17586
17587All other built-ins that provide utilities specified by Posix must have
17588a counterpart executable that exists on @env{PATH}, although Posix
17589allows @command{exec} to use the built-in instead of the executable.
17590For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17591
17592@example
17593$ @kbd{bash -c 'pwd --version' | head -n1}
17594bash: line 0: pwd: --: invalid option
17595pwd: usage: pwd [-LP]
17596$ @kbd{bash -c 'exec pwd --version' | head -n1}
17597pwd (GNU coreutils) 6.10
17598$ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17599pdksh: pwd: --: unknown option
17600@end example
17601
17602When it is desired to avoid a regular shell built-in, the workaround is
17603to use some other forwarding command, such as @command{env} or
17604@command{nice}, that will ensure a path search:
17605
17606@example
17607$ @kbd{pdksh -c 'exec true --version' | head -n1}
17608$ @kbd{pdksh -c 'nice true --version' | head -n1}
17609true (GNU coreutils) 6.10
17610$ @kbd{pdksh -c 'env true --version' | head -n1}
17611true (GNU coreutils) 6.10
17612@end example
17613
17614@item @command{exit}
17615@c -----------------
17616@prindex @command{exit}
17617The default value of @command{exit} is supposed to be @code{$?};
17618unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17619perform @samp{exit 0}.
17620
17621@example
17622bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17623fail
17624bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17625fail
17626bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17627bash-2.04$
17628@end example
17629
17630Using @samp{exit $?} restores the expected behavior.
17631
17632Some shell scripts, such as those generated by @command{autoconf}, use a
17633trap to clean up before exiting.  If the last shell command exited with
17634nonzero status, the trap also exits with nonzero status so that the
17635invoker can tell that an error occurred.
17636
17637Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17638trap ignores the @code{exit} command's argument.  In these shells, a trap
17639cannot determine whether it was invoked by plain @code{exit} or by
17640@code{exit 1}.  Instead of calling @code{exit} directly, use the
17641@code{AC_MSG_ERROR} macro that has a workaround for this problem.
17642
17643
17644@anchor{export}
17645@item @command{export}
17646@c -------------------
17647@prindex @command{export}
17648The builtin @command{export} dubs a shell variable @dfn{environment
17649variable}.  Each update of exported variables corresponds to an update
17650of the environment variables.  Conversely, each environment variable
17651received by the shell when it is launched should be imported as a shell
17652variable marked as exported.
17653
17654Alas, many shells, such as Solaris @command{/bin/sh},
17655IRIX 6.3, IRIX 5.2,
17656AIX 4.1.5, and Digital Unix 4.0, forget to
17657@command{export} the environment variables they receive.  As a result,
17658two variables coexist: the environment variable and the shell
17659variable.  The following code demonstrates this failure:
17660
17661@example
17662#!/bin/sh
17663echo $FOO
17664FOO=bar
17665echo $FOO
17666exec /bin/sh $0
17667@end example
17668
17669@noindent
17670when run with @samp{FOO=foo} in the environment, these shells print
17671alternately @samp{foo} and @samp{bar}, although they should print only
17672@samp{foo} and then a sequence of @samp{bar}s.
17673
17674Therefore you should @command{export} again each environment variable
17675that you update; the export can occur before or after the assignment.
17676
17677Posix is not clear on whether the @command{export} of an undefined
17678variable causes the variable to be defined with the value of an empty
17679string, or merely marks any future definition of a variable by that name
17680for export.  Various shells behave differently in this regard:
17681
17682@example
17683$ @kbd{sh -c 'export foo; env | grep foo'}
17684$ @kbd{ash -c 'export foo; env | grep foo'}
17685foo=
17686@end example
17687
17688Posix requires @command{export} to honor assignments made as arguments,
17689but older shells do not support this, including @command{/bin/sh} in
17690Solaris 10.  Portable scripts should separate assignments and exports
17691into different statements.
17692
17693@example
17694$ @kbd{bash -c 'export foo=bar; echo $foo'}
17695bar
17696$ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17697/bin/sh: foo=bar: is not an identifier
17698$ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17699bar
17700@end example
17701
17702@item @command{false}
17703@c ------------------
17704@prindex @command{false}
17705Don't expect @command{false} to exit with status 1: in native
17706Solaris @file{/bin/false} exits with status 255.
17707
17708
17709@item @command{for}
17710@c ----------------
17711@prindex @command{for}
17712To loop over positional arguments, use:
17713
17714@example
17715for arg
17716do
17717  echo "$arg"
17718done
17719@end example
17720
17721@noindent
17722You may @emph{not} leave the @code{do} on the same line as @code{for},
17723since some shells improperly grok:
17724
17725@example
17726for arg; do
17727  echo "$arg"
17728done
17729@end example
17730
17731If you want to explicitly refer to the positional arguments, given the
17732@samp{$@@} bug (@pxref{Shell Substitutions}), use:
17733
17734@example
17735for arg in $@{1+"$@@"@}; do
17736  echo "$arg"
17737done
17738@end example
17739
17740@noindent
17741But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17742word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17743item @samp{$@@}, for more.
17744
17745In Solaris @command{/bin/sh}, when the list of arguments of a
17746@command{for} loop starts with @emph{unquoted} tokens looking like
17747variable assignments, the loop is not executed on those tokens:
17748
17749@example
17750$ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17751x
17752e=f
17753@end example
17754
17755@noindent
17756Thankfully, quoting the assignment-like tokens, or starting the list
17757with other tokens (including unquoted variable expansion that results in
17758an assignment-like result), avoids the problem, so it is easy to work
17759around:
17760
17761@example
17762$ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17763a=b
17764$ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17765a=b
17766c=d
17767@end example
17768
17769@anchor{if}
17770@item @command{if}
17771@c ---------------
17772@prindex @command{if}
17773Using @samp{!} is not portable.  Instead of:
17774
17775@example
17776if ! cmp -s file file.new; then
17777  mv file.new file
17778fi
17779@end example
17780
17781@noindent
17782use:
17783
17784@example
17785if cmp -s file file.new; then :; else
17786  mv file.new file
17787fi
17788@end example
17789
17790@noindent
17791Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17792In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17793of conditionals:
17794
17795@example
17796AS_IF([cmp -s file file.new], [], [mv file.new file])
17797@end example
17798
17799This is especially useful in other M4 macros, where the @dfn{then} and
17800@dfn{else} branches might be macro arguments.
17801
17802Some very old shells did not reset the exit status from an @command{if}
17803with no @command{else}:
17804
17805@example
17806$ @kbd{if (exit 42); then true; fi; echo $?}
1780742
17808@end example
17809
17810@noindent
17811whereas a proper shell should have printed @samp{0}.  But this is no
17812longer a portability problem; any shell that supports functions gets it
17813correct.  However, it explains why some makefiles have lengthy
17814constructs:
17815
17816@example
17817if test -f "$file"; then
17818  install "$file" "$dest"
17819else
17820  :
17821fi
17822@end example
17823
17824
17825@item @command{printf}
17826@c ------------------
17827@prindex @command{printf}
17828A format string starting with a @samp{-} can cause problems.
17829Bash interprets it as an option and
17830gives an error.  And @samp{--} to mark the end of options is not good
17831in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17832literally as the format string.  Putting the @samp{-} in a @samp{%c}
17833or @samp{%s} is probably easiest:
17834
17835@example
17836printf %s -foo
17837@end example
17838
17839Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17840
17841@example
17842$ @kbd{printf '\045'}
17843bash: printf: `%': missing format character
17844@end example
17845
17846Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17847example, @file{/usr/bin/printf} is buggy, so when using
17848@command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17849core.
17850
17851Since @command{printf} is not always a shell builtin, there is a
17852potential speed penalty for using @code{printf '%s\n'} as a replacement
17853for an @command{echo} that does not interpret @samp{\} or leading
17854@samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17855-r --} for this role instead.
17856
17857@xref{echo, , Limitations of Shell Builtins} for a discussion of
17858portable alternatives to both @command{printf} and @command{echo}.
17859
17860
17861@item @command{pwd}
17862@c ----------------
17863@prindex @command{pwd}
17864With modern shells, plain @command{pwd} outputs a ``logical''
17865directory name, some of whose components may be symbolic links.  These
17866directory names are in contrast to ``physical'' directory names, whose
17867components are all directories.
17868
17869Posix 1003.1-2001 requires that @command{pwd} must support
17870the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17871with @option{-L} being the default.  However, traditional shells do
17872not support these options, and their @command{pwd} command has the
17873@option{-P} behavior.
17874
17875Portable scripts should assume neither option is supported, and should
17876assume neither behavior is the default.  Also, on many hosts
17877@samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17878does not require this behavior and portable scripts should not rely on
17879it.
17880
17881Typically it's best to use plain @command{pwd}.  On modern hosts this
17882outputs logical directory names, which have the following advantages:
17883
17884@itemize @bullet
17885@item
17886Logical names are what the user specified.
17887@item
17888Physical names may not be portable from one installation
17889host to another due to network file system gymnastics.
17890@item
17891On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17892some parent directory, but plain @command{pwd} cannot fail for this
17893reason.
17894@end itemize
17895
17896Also please see the discussion of the @command{cd} command.
17897
17898
17899@item @command{read}
17900@c -----------------
17901@prindex @command{read}
17902No options are portable, not even support @option{-r} (Solaris
17903@command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
17904@command{read} as a special built-in, so it may exit if input is
17905redirected from a non-existent or unreadable file.
17906
17907
17908@anchor{set}
17909@item @command{set}
17910@c ----------------
17911@prindex @command{set}
17912With the FreeBSD 6.0 shell, the @command{set} command (without
17913any options) does not sort its output.
17914
17915The @command{set} builtin faces the usual problem with arguments
17916starting with a
17917dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17918the end of the options (any argument after @option{--} is a parameter,
17919even @samp{-x} for instance), but many traditional shells (e.g., Solaris
1792010 @command{/bin/sh}) simply stop option
17921processing as soon as a non-option argument is found.  Therefore, use
17922@samp{dummy} or simply @samp{x} to end the option processing, and use
17923@command{shift} to pop it out:
17924
17925@example
17926set x $my_list; shift
17927@end example
17928
17929Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17930longer requires support for this command, and in traditional shells
17931@samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17932makes scripts harder to debug.
17933
17934Some nonstandard shells do not recognize more than one option
17935(e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17936better to combine them:
17937
17938@example
17939set -ex
17940@end example
17941
17942@cindex @command{set -e}
17943The option @option{-e} has historically been underspecified, with enough
17944ambiguities to cause numerous differences across various shell
17945implementations; see for example
17946@uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
17947or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
17948documenting a change to Posix 2008 to match @command{ksh88} behavior.
17949Note that mixing @code{set -e} and shell functions is asking for surprises:
17950
17951@example
17952set -e
17953doit()
17954@{
17955  rm file
17956  echo one
17957@}
17958doit || echo two
17959@end example
17960
17961@noindent
17962According to the recommendation, @samp{one} should always be output
17963regardless of whether the @command{rm} failed, because it occurs within
17964the body of the shell function @samp{doit} invoked on the left side of
17965@samp{||}, where the effects of @samp{set -e} are not enforced.
17966Likewise, @samp{two} should never be printed, since the failure of
17967@command{rm} does not abort the function, such that the status of
17968@samp{doit} is 0.
17969
17970The BSD shell has had several problems with the @option{-e}
17971option.  Older versions of the BSD
17972shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17973@samp{case} when @option{-e} was in effect, causing the shell to exit
17974unexpectedly in some cases.  This was particularly a problem with
17975makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17976touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17977wrapper works around the bug (@pxref{Failure in Make Rules}).
17978
17979Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17980wrongly exit with @option{-e} if the last command within a compound
17981statement fails and is guarded by an @samp{&&} only.  For example:
17982
17983@example
17984#! /bin/sh
17985set -e
17986foo=''
17987test -n "$foo" && exit 1
17988echo one
17989if :; then
17990  test -n "$foo" && exit 1
17991  echo two
17992  test -n "$foo" && exit 1
17993fi
17994echo three
17995@end example
17996
17997@noindent
17998does not print @samp{three}.  One workaround is to change the last
17999instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18000"$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18001users not to use @samp{sh -e}.
18002
18003When @samp{set -e} is in effect, a failed command substitution in
18004Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
18005
18006@example
18007$ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18008$ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18009foo
18010bar
18011@end example
18012
18013@noindent
18014Moreover, a command substitution, successful or not, causes this shell to
18015exit from a failing outer command even in presence of an @samp{&&} list:
18016
18017@example
18018$ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18019ok
18020$ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18021$
18022@end example
18023
18024Portable scripts should not use @samp{set -e} if @command{trap} is used
18025to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18026sometimes enters the trap handler with the exit status of the command
18027prior to the one that triggered the errexit handler:
18028
18029@example
18030$ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
180310
18032$ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
180331
18034@end example
18035
18036@noindent
18037Thus, when writing a script in M4sh, rather than trying to rely on
18038@samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18039statement where it is desirable to abort on failure.
18040
18041@cindex @command{set -b}
18042@cindex @command{set -m}
18043Job control is not provided by all shells, so the use of @samp{set -m}
18044or @samp{set -b} must be done with care.  When using @command{zsh} in
18045native mode, asynchronous notification (@samp{set -b}) is enabled by
18046default, and using @samp{emulate sh} to switch to Posix mode does not
18047clear this setting (although asynchronous notification has no impact
18048unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18049earlier have a bug where job control can be manipulated in interactive
18050shells, but not in subshells or scripts.  Furthermore, some shells, like
18051@command{pdksh}, fail to treat subshells as interactive, even though the
18052parent shell was.
18053
18054@example
18055$ @kbd{echo $ZSH_VERSION}
180564.3.10
18057$ @kbd{set -m; echo $?}
180580
18059$ @kbd{zsh -c 'set -m; echo $?'}
18060set: can't change option: -m
18061$ @kbd{(set -m); echo $?}
18062set: can't change option: -m
180631
18064$ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18065cim
18066c
18067@end example
18068
18069@cindex @command{set -n}
18070Use of @command{set -n} (typically via @command{sh -n script}) to
18071validate a script is not foolproof.  Modern @command{ksh93} tries to be
18072helpful by informing you about better syntax, but switching the script
18073to use the suggested syntax in order to silence the warnings would
18074render the script no longer portable to older shells:
18075
18076@example
18077$ @kbd{ksh -nc '``'}
18078ksh: warning: line 1: `...` obsolete, use $(...)
180790
18080@end example
18081
18082Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18083into an infinite loop; even with that bug fixed, Solaris 8
18084@command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18085itself uses @command{sh -n} within its testsuite to check that correct
18086scripts were generated, but only after first probing for other shell
18087features (such as @code{test -n "$@{BASH_VERSION+set@}"}) that indicate
18088a reasonably fast and working implementation.
18089
18090@item @command{shift}
18091@c ------------------
18092@prindex @command{shift}
18093Not only is @command{shift}ing a bad idea when there is nothing left to
18094shift, but in addition it is not portable: the shell of MIPS
18095RISC/OS 4.52 refuses to do it.
18096
18097Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18098it is also absent in many pre-Posix shells.
18099
18100
18101@item @command{source}
18102@c -------------------
18103@prindex @command{source}
18104This command is not portable, as Posix does not require it; use
18105@command{.} instead.
18106
18107
18108@item @command{test}
18109@c -----------------
18110@prindex @command{test}
18111The @code{test} program is the way to perform many file and string
18112tests.  It is often invoked by the alternate name @samp{[}, but using
18113that name in Autoconf code is asking for trouble since it is an M4 quote
18114character.
18115
18116The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18117present in all implementations, and have been marked obsolete by Posix
181182008.  This is because there are inherent ambiguities in using them.
18119For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18120check whether two strings are both non-empty, but if @samp{$1} is the
18121literal @samp{!}, then some implementations of @command{test} treat it
18122as a negation of the unary operator @option{-a}.
18123
18124Thus, portable uses of @command{test} should never have more than four
18125arguments, and scripts should use shell constructs like @samp{&&} and
18126@samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18127statement, keep in mind that they have equal precedence, so it is often
18128better to parenthesize even when this is redundant.  For example:
18129
18130@smallexample
18131# Not portable:
18132test "X$a" = "X$b" -a \
18133  '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18134
18135# Portable:
18136test "X$a" = "X$b" &&
18137  @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18138@end smallexample
18139
18140@command{test} does not process options like most other commands do; for
18141example, it does not recognize the @option{--} argument as marking the
18142end of options.
18143
18144It is safe to use @samp{!} as a @command{test} operator.  For example,
18145@samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18146-d foo; @dots{}} is not.
18147
18148
18149@item @command{test} (files)
18150@c -------------------------
18151To enable @command{configure} scripts to support cross-compilation, they
18152shouldn't do anything that tests features of the build system instead of
18153the host system.  But occasionally you may find it necessary to check
18154whether some arbitrary file exists.  To do so, use @samp{test -f},
18155@samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18156Solaris 10 @command{/bin/sh}
18157lacks it.  To test for symbolic links on systems that have them, use
18158@samp{test -h} rather than @samp{test -L}; either form conforms to
18159Posix 1003.1-2001, but older shells like Solaris 8
18160@code{/bin/sh} support only @option{-h}.
18161
18162For historical reasons, Posix reluctantly allows implementations of
18163@samp{test -x} that will succeed for the root user, even if no execute
18164permissions are present.  Furthermore, shells do not all agree on
18165whether Access Control Lists should affect @samp{test -r}, @samp{test
18166-w}, and @samp{test -x}; some shells base test results strictly on the
18167current user id compared to file owner and mode, as if by
18168@code{stat(2)}; while other shells base test results on whether the
18169current user has the given right, even if that right is only granted by
18170an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18171time of check to time of use race between any use of @command{test}
18172followed by operating on the just-checked file.  Therefore, it is a good
18173idea to write scripts that actually attempt an operation, and are
18174prepared for the resulting failure if permission is denied, rather than
18175trying to avoid an operation based solely on whether @command{test}
18176guessed that it might not be permitted.
18177
18178@item @command{test} (strings)
18179@c ---------------------------
18180Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18181not null, but this usage is not portable to traditional platforms like
18182Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18183@samp{-n}.
18184
18185Posix also says that @samp{test ! "@var{string}"},
18186@samp{test -n "@var{string}"} and
18187@samp{test -z "@var{string}"} work with any string, but many
18188shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18189Digital Unix 4, etc.)@: get confused if
18190@var{string} looks like an operator:
18191
18192@example
18193$ @kbd{test -n =}
18194test: argument expected
18195$ @kbd{test ! -n}
18196test: argument expected
18197$ @kbd{test -z ")"; echo $?}
181980
18199@end example
18200
18201Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18202and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18203strings, but in practice this is not true for troublesome strings that
18204look like operators or parentheses, or that begin with @samp{-}.
18205
18206It is best to protect such strings with a leading @samp{X}, e.g.,
18207@samp{test "X@var{string}" != X} rather than @samp{test -n
18208"@var{string}"} or @samp{test ! "@var{string}"}.
18209
18210It is common to find variations of the following idiom:
18211
18212@example
18213test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18214  @var{action}
18215@end example
18216
18217@noindent
18218to take an action when a token matches a given pattern.  Such constructs
18219should be avoided by using:
18220
18221@example
18222case $ac_feature in
18223  *[!-a-zA-Z0-9_]*) @var{action};;
18224esac
18225@end example
18226
18227If the pattern is a complicated regular expression that cannot be
18228expressed as a shell pattern, use something like this instead:
18229
18230@example
18231expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18232  @var{action}
18233@end example
18234
18235@samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18236"X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18237@samp{@var{foo}} contains backslashes.
18238
18239
18240@anchor{trap}
18241@item @command{trap}
18242@c -----------------
18243@prindex @command{trap}
18244It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18245trap 0, i.e., have the @command{trap} run when the script ends (either via an
18246explicit @command{exit}, or the end of the script).  The trap for 0 should be
18247installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18248will invoke the trap at the end of this function.
18249
18250Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18251specified signals to their default values, but many common shells (e.g.,
18252Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18253``command'' named @command{-} when the specified conditions arise.
18254Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18255reset traps, as this is supported by a larger set of shells, but there
18256are still shells like @command{dash} that mistakenly try to execute
18257@command{1} instead of resetting the traps.  Therefore, there is no
18258portable workaround, except for @samp{trap - 0}, for which
18259@samp{trap '' 0} is a portable substitute.
18260
18261Although Posix is not absolutely clear on this point, it is widely
18262admitted that when entering the trap @samp{$?} should be set to the exit
18263status of the last command run before the trap.  The ambiguity can be
18264summarized as: ``when the trap is launched by an @command{exit}, what is
18265the @emph{last} command run: that before @command{exit}, or
18266@command{exit} itself?''
18267
18268Bash considers @command{exit} to be the last command, while Zsh and
18269Solaris @command{/bin/sh} consider that when the trap is run it is
18270@emph{still} in the @command{exit}, hence it is the previous exit status
18271that the trap receives:
18272
18273@example
18274$ @kbd{cat trap.sh}
18275trap 'echo $?' 0
18276(exit 42); exit 0
18277$ @kbd{zsh trap.sh}
1827842
18279$ @kbd{bash trap.sh}
182800
18281@end example
18282
18283The portable solution is then simple: when you want to @samp{exit 42},
18284run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18285set the exit status to 42 for Zsh, and the second to trigger the trap
18286and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18287@code{AS_EXIT}.
18288
18289The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18290reset to 0 by empty lines if the code is inside @command{trap}.
18291
18292@example
18293$ @kbd{trap 'false}
18294
18295echo $?' 0
18296$ @kbd{exit}
182970
18298@end example
18299
18300@noindent
18301Fortunately, this bug only affects @command{trap}.
18302
18303Several shells fail to execute an exit trap that is defined inside a
18304subshell, when the last command of that subshell is not a builtin.  A
18305workaround is to use @samp{exit $?} as the shell builtin.
18306
18307@example
18308$ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18309hi
18310$ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18311$ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18312hi
18313@end example
18314
18315@noindent
18316Likewise, older implementations of @command{bash} failed to preserve
18317@samp{$?} across an exit trap consisting of a single cleanup command.
18318
18319@example
18320$ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
183212
18322$ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
183230
18324$ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
183252
18326@end example
18327
18328@item @command{true}
18329@c -----------------
18330@prindex @command{true}
18331@c Info cannot handle `:' in index entries.
18332@c @prindex @command{:}
18333Don't worry: as far as we know @command{true} is portable.
18334Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18335portable shell community tends to prefer using @command{:}.  This has a
18336funny side effect: when asked whether @command{false} is more portable
18337than @command{true} Alexandre Oliva answered:
18338
18339@quotation
18340In a sense, yes, because if it doesn't exist, the shell will produce an
18341exit status of failure, which is correct for @command{false}, but not
18342for @command{true}.
18343@end quotation
18344
18345Remember that even though @samp{:} ignores its arguments, it still takes
18346time to compute those arguments.  It is a good idea to use double quotes
18347around any arguments to @samp{:} to avoid time spent in field splitting
18348and file name expansion.
18349
18350
18351@anchor{unset}
18352@item @command{unset}
18353@c ------------------
18354@prindex @command{unset}
18355In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18356@command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18357@code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18358with @code{set -e} operation.  You can use
18359
18360@smallexample
18361FOO=; unset FOO
18362@end smallexample
18363
18364@noindent
18365if you are not sure that @code{FOO} is set.
18366
18367A few ancient shells lack @command{unset} entirely.  For some variables
18368such as @code{PS1}, you can use a neutralizing value instead:
18369
18370@smallexample
18371PS1='$ '
18372@end smallexample
18373
18374Usually, shells that do not support @command{unset} need less effort to
18375make the environment sane, so for example is not a problem if you cannot
18376unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18377@code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18378So, you should do something like
18379
18380@smallexample
18381( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18382@end smallexample
18383
18384@noindent
18385@xref{Special Shell Variables}, for some neutralizing values.  Also, see
18386@ref{export, , Limitations of Builtins}, for
18387the case of environment variables.
18388
18389@item @command{wait}
18390@c -----------------
18391@prindex @command{wait}
18392The exit status of @command{wait} is not always reliable.
18393@end table
18394
18395@node Limitations of Usual Tools
18396@section Limitations of Usual Tools
18397@cindex Limitations of usual tools
18398
18399The small set of tools you can expect to find on any machine can still
18400include some limitations you should be aware of.
18401
18402@comment Between this list and the list of builtins above, we should
18403@comment mention all the tools in GNU Coding Standards ``Utilities in
18404@comment Makefiles''.
18405
18406@c This table includes things like `@command{expr} (|)', so we can't
18407@c use @table @command.
18408@table @asis
18409@anchor{awk}
18410@item @command{awk}
18411@c ----------------
18412@prindex @command{awk}
18413Don't leave white space before the opening parenthesis in a user function call.
18414Posix does not allow this and GNU Awk rejects it:
18415
18416@example
18417$ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18418        BEGIN @{ die () @}'}
18419gawk: cmd. line:2:         BEGIN @{ die () @}
18420gawk: cmd. line:2:                      ^ parse error
18421$ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18422        BEGIN @{ die() @}'}
18423Aaaaarg!
18424@end example
18425
18426Posix says that if a program contains only @samp{BEGIN} actions, and
18427contains no instances of @code{getline}, then the program merely
18428executes the actions without reading input.  However, traditional Awk
18429implementations (such as Solaris 10 @command{awk}) read and discard
18430input in this case.  Portable scripts can redirect input from
18431@file{/dev/null} to work around the problem.  For example:
18432
18433@example
18434awk 'BEGIN @{print "hello world"@}' </dev/null
18435@end example
18436
18437Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18438@samp{$1}) retain their value from the last record read, if no
18439intervening @samp{getline} occurred.  However, some implementations
18440(such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18441@samp{awk}) reset these variables.  A workaround is to use an
18442intermediate variable prior to the @samp{END} block.  For example:
18443
18444@example
18445$ @kbd{cat end.awk}
18446@{ tmp = $1 @}
18447END @{ print "a", $1, $NF, "b", tmp @}
18448$ @kbd{echo 1 | awk -f end.awk}
18449a   b 1
18450$ @kbd{echo 1 | gawk -f end.awk}
18451a 1 1 b 1
18452@end example
18453
18454If you want your program to be deterministic, don't depend on @code{for}
18455on arrays:
18456
18457@example
18458$ @kbd{cat for.awk}
18459END @{
18460  arr["foo"] = 1
18461  arr["bar"] = 1
18462  for (i in arr)
18463    print i
18464@}
18465$ @kbd{gawk -f for.awk </dev/null}
18466foo
18467bar
18468$ @kbd{nawk -f for.awk </dev/null}
18469bar
18470foo
18471@end example
18472
18473Some Awk implementations, such as HP-UX 11.0's native one,
18474mishandle anchors:
18475
18476@example
18477$ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18478$ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18479bar
18480$ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18481xfoo
18482$ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18483bar
18484@end example
18485
18486@noindent
18487Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18488or use a simple test to reject such implementations.
18489
18490On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18491after @code{%u}:
18492
18493@example
18494$ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
184950 0
18496@end example
18497
18498AIX version 5.2 has an arbitrary limit of 399 on the
18499length of regular expressions and literal strings in an Awk program.
18500
18501Traditional Awk implementations derived from Unix version 7, such as
18502Solaris @command{/bin/awk}, have many limitations and do not
18503conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18504Programs}) finds you an Awk that doesn't have these problems, but if
18505for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18506address them.  For more detailed descriptions, see @ref{Language
18507History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18508
18509Traditional Awk does not support multidimensional arrays or user-defined
18510functions.
18511
18512Traditional Awk does not support the @option{-v} option.  You can use
18513assignments after the program instead, e.g., @code{$AWK '@{print v
18514$1@}' v=x}; however, don't forget that such assignments are not
18515evaluated until they are encountered (e.g., after any @code{BEGIN}
18516action).
18517
18518Traditional Awk does not support the keywords @code{delete} or @code{do}.
18519
18520Traditional Awk does not support the expressions
18521@code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18522or @code{@var{a}^=@var{b}}.
18523
18524Traditional Awk does not support the predefined @code{CONVFMT} or
18525@code{ENVIRON} variables.
18526
18527Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18528@code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18529@code{sqrt}, and @code{substr}.
18530
18531Traditional Awk @code{getline} is not at all compatible with Posix;
18532avoid it.
18533
18534Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18535@code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18536
18537In code portable to both traditional and modern Awk, @code{FS} must be a
18538string containing just one ordinary character, and similarly for the
18539field-separator argument to @code{split}.
18540
18541Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18542implementations, like Tru64's, split the input even if you don't refer
18543to any field in the script, to circumvent this problem, set @samp{FS}
18544to an unusual character and use @code{split}.
18545
18546Traditional Awk has a limit of at most 99 bytes in a number formatted by
18547@code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18548dumps core.
18549
18550The original version of Awk had a limit of at most 99 bytes per
18551@code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18552per run of non-special characters in a @code{printf} format, but these
18553bugs have been fixed on all practical hosts that we know of.
18554
18555HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18556of at most 3070 bytes.
18557
18558@item @command{basename}
18559@c ---------------------
18560@prindex @command{basename}
18561Not all hosts have a working @command{basename}.
18562You can use @command{expr} instead.
18563
18564@c AS_BASENAME is to be replaced by a better API.
18565@ignore
18566Not all hosts have a working @command{basename}, and you should instead
18567use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18568@command{expr} if you need to strip a suffix.  For example:
18569
18570@example
18571a=`basename "$aname"`       # This is not portable.
18572a=`AS_BASENAME(["$aname"])` # This is more portable.
18573
18574# This is not portable.
18575c=`basename "$cname" .c`
18576
18577# This is more portable.
18578c=`AS_BASENAME(["$cname"])`
18579case $c in
18580?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18581esac
18582@end example
18583@end ignore
18584
18585
18586@item @command{cat}
18587@c ----------------
18588@prindex @command{cat}
18589Don't rely on any option.
18590
18591
18592@item @command{cc}
18593@c ---------------
18594@prindex @command{cc}
18595The command @samp{cc -c foo.c} traditionally produces an object file
18596named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18597with @option{-o} to specify a different object file name, but
18598Posix does not require this combination and a few compilers
18599lack support for it.  @xref{C Compiler}, for how GNU Make
18600tests for this feature with @code{AC_PROG_CC_C_O}.
18601
18602When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18603(such as CDS on Reliant Unix) leave a @file{foo.o}.
18604
18605HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18606assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18607nothing.
18608
18609The default executable, produced by @samp{cc foo.c}, can be
18610
18611@itemize
18612@item @file{a.out} --- usual Posix convention.
18613@item @file{b.out} --- i960 compilers (including @command{gcc}).
18614@item @file{a.exe} --- DJGPP port of @command{gcc}.
18615@item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
18616@item @file{foo.exe} --- various MS-DOS compilers.
18617@end itemize
18618
18619The C compiler's traditional name is @command{cc}, but other names like
18620@command{gcc} are common.  Posix 1003.1-2001 specifies the
18621name @command{c99}, but older Posix editions specified
18622@command{c89} and anyway these standard names are rarely used in
18623practice.  Typically the C compiler is invoked from makefiles that use
18624@samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18625compiler name.
18626
18627@item @command{chgrp}
18628@itemx @command{chown}
18629@c -------------------
18630@prindex @command{chgrp}
18631@prindex @command{chown}
18632It is not portable to change a file's group to a group that the owner
18633does not belong to.
18634
18635@item @command{chmod}
18636@c ------------------
18637@prindex @command{chmod}
18638Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18639instead, for two reasons.  First, plain @option{-w} does not necessarily
18640make the file unwritable, since it does not affect mode bits that
18641correspond to bits in the file mode creation mask.  Second,
18642Posix says that the @option{-w} might be interpreted as an
18643implementation-specific option, not as a mode; Posix suggests
18644using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18645@samp{--} does not work on some older hosts.
18646
18647
18648@item @command{cmp}
18649@c ----------------
18650@prindex @command{cmp}
18651@command{cmp} performs a raw data comparison of two files, while
18652@command{diff} compares two text files.  Therefore, if you might compare
18653DOS files, even if only checking whether two files are different, use
18654@command{diff} to avoid spurious differences due to differences of
18655newline encoding.
18656
18657
18658@item @command{cp}
18659@c ---------------
18660@prindex @command{cp}
18661Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18662obsolescent and its behavior on special files is implementation-defined.
18663Use @option{-R} instead.  On GNU hosts the two options
18664are equivalent, but on Solaris hosts (for example) @code{cp -r}
18665reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18666corrupt its own memory with some directory hierarchies and error out or
18667dump core:
18668
18669@example
18670@kbd{mkdir -p 12345678/12345678/12345678/12345678}
18671@kbd{touch 12345678/12345678/x}
18672@kbd{cp -R 12345678 t}
18673cp: 0653-440 12345678/12345678/: name too long.
18674@end example
18675
18676Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18677trailing slashes at the end of nonexistent destination directories.  To
18678avoid this problem, omit the trailing slashes.  For example, use
18679@samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18680/tmp/newdir/} if @file{/tmp/newdir} does not exist.
18681
18682@c This is thanks to Ian.
18683The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18684its @command{mv} does.
18685
18686@cindex timestamp resolution
18687Traditionally, file timestamps had 1-second resolution, and @samp{cp
18688-p} copied the timestamps exactly.  However, many modern file systems
18689have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18690@samp{cp -p} implementations truncate timestamps when copying files,
18691which can cause the destination file to appear to be older than the
18692source.  The exact amount of truncation depends on the resolution of
18693the system calls that @command{cp} uses.  Traditionally this was
18694@code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18695implementations such as GNU Core Utilities 5.0.91 (2003) use
18696@code{utimes}, which has 1-microsecond resolution.  Modern
18697implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18698the full nanosecond resolution, using the modern system calls
18699@code{futimens} and @code{utimensat} when they are available.  As of
187002011, though, many platforms do not yet fully support these new system
18701calls.
18702
18703Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18704ownerships.  But whether it actually does copy ownerships or not is a
18705system dependent policy decision implemented by the kernel.  If the
18706kernel allows it then it happens.  If the kernel does not allow it then
18707it does not happen.  It is not something @command{cp} itself has control
18708over.
18709
18710In Unix System V any user can chown files to any other user, and System
18711V also has a non-sticky @file{/tmp}.  That probably derives from the
18712heritage of System V in a business environment without hostile users.
18713BSD changed this
18714to be a more secure model where only root can @command{chown} files and
18715a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18716of BSD in a campus environment.
18717
18718GNU/Linux and Solaris by default follow BSD, but
18719can be configured to allow a System V style @command{chown}.  On the
18720other hand, HP-UX follows System V, but can
18721be configured to use the modern security model and disallow
18722@command{chown}.  Since it is an administrator-configurable parameter
18723you can't use the name of the kernel as an indicator of the behavior.
18724
18725
18726
18727@item @command{date}
18728@c -----------------
18729@prindex @command{date}
18730Some versions of @command{date} do not recognize special @samp{%} directives,
18731and unfortunately, instead of complaining, they just pass them through,
18732and exit with success:
18733
18734@example
18735$ @kbd{uname -a}
18736OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18737$ @kbd{date "+%s"}
18738%s
18739@end example
18740
18741
18742@item @command{diff}
18743@c -----------------
18744@prindex @command{diff}
18745Option @option{-u} is nonportable.
18746
18747Some implementations, such as Tru64's, fail when comparing to
18748@file{/dev/null}.  Use an empty file instead.
18749
18750
18751@item @command{dirname}
18752@c --------------------
18753@prindex @command{dirname}
18754Not all hosts have a working @command{dirname}, and you should instead
18755use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18756
18757@example
18758dir=`dirname "$file"`       # This is not portable.
18759dir=`AS_DIRNAME(["$file"])` # This is more portable.
18760@end example
18761
18762
18763@item @command{egrep}
18764@c ------------------
18765@prindex @command{egrep}
18766Posix 1003.1-2001 no longer requires @command{egrep},
18767but many hosts do not yet support the Posix
18768replacement @code{grep -E}.  Also, some traditional implementations do
18769not work on long input lines.  To work around these problems, invoke
18770@code{AC_PROG_EGREP} and then use @code{$EGREP}.
18771
18772Portable extended regular expressions should use @samp{\} only to escape
18773characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18774is not portable, even though it typically matches @samp{@}}.
18775
18776The empty alternative is not portable.  Use @samp{?} instead.  For
18777instance with Digital Unix v5.0:
18778
18779@example
18780> printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18781|foo
18782> printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18783bar|
18784> printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18785foo
18786|bar
18787@end example
18788
18789@command{$EGREP} also suffers the limitations of @command{grep}
18790(@pxref{grep, , Limitations of Usual Tools}).
18791
18792@item @command{expr}
18793@c -----------------
18794@prindex @command{expr}
18795Not all implementations obey the Posix rule that @samp{--} separates
18796options from arguments; likewise, not all implementations provide the
18797extension to Posix that the first argument can be treated as part of a
18798valid expression rather than an invalid option if it begins with
18799@samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18800@samp{$var} might be a negative number, to keep @command{expr} from
18801interpreting it as an option.
18802
18803No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18804X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18805misinterpreting @var{word}.
18806
18807Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18808
18809@item @command{expr} (@samp{|})
18810@prindex @command{expr} (@samp{|})
18811You can use @samp{|}.  Although Posix does require that @samp{expr
18812''} return the empty string, it does not specify the result when you
18813@samp{|} together the empty string (or zero) with the empty string.  For
18814example:
18815
18816@example
18817expr '' \| ''
18818@end example
18819
18820Posix 1003.2-1992 returns the empty string
18821for this case, but traditional Unix returns @samp{0} (Solaris is
18822one such example).  In Posix 1003.1-2001, the specification was
18823changed to match traditional Unix's behavior (which is
18824bizarre, but it's too late to fix this).  Please note that the same
18825problem does arise when the empty string results from a computation,
18826as in:
18827
18828@example
18829expr bar : foo \| foo : bar
18830@end example
18831
18832@noindent
18833Avoid this portability problem by avoiding the empty string.
18834
18835
18836@item @command{expr} (@samp{:})
18837@c ----------------------------
18838@prindex @command{expr}
18839Portable @command{expr} regular expressions should use @samp{\} to
18840escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18841For example, alternation, @samp{\|}, is common but Posix does not
18842require its support, so it should be avoided in portable scripts.
18843Similarly, @samp{\+} and @samp{\?} should be avoided.
18844
18845Portable @command{expr} regular expressions should not begin with
18846@samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18847not needed anyway.
18848
18849On the other hand, the behavior of the @samp{$} anchor is not portable
18850on multi-line strings.  Posix is ambiguous whether the anchor applies to
18851each line, as was done in older versions of the GNU Core Utilities, or
18852whether it applies only to the end of the overall string, as in
18853Coreutils 6.0 and most other implementations.
18854
18855@example
18856$ @kbd{baz='foo}
18857> @kbd{bar'}
18858$ @kbd{expr "X$baz" : 'X\(foo\)$'}
18859
18860$ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18861foo
18862@end example
18863
18864The Posix standard is ambiguous as to whether
18865@samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18866In practice, it outputs the empty string on most platforms, but portable
18867scripts should not assume this.  For instance, the QNX 4.25 native
18868@command{expr} returns @samp{0}.
18869
18870One might think that a way to get a uniform behavior would be to use
18871the empty string as a default value:
18872
18873@example
18874expr a : '\(b\)' \| ''
18875@end example
18876
18877@noindent
18878Unfortunately this behaves exactly as the original expression; see the
18879@command{expr} (@samp{|}) entry for more information.
18880
18881Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18882Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18883@command{expr} to fail if the matched substring is longer than 120
18884bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18885@command{expr} fails.  Nowadays this is of practical importance only for
18886the rare installer who mistakenly puts @file{/usr/ucb} before
18887@file{/usr/bin} in @env{PATH}.
18888
18889On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18890some cases.  For example, the command
18891@example
18892expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18893@end example
18894
18895@noindent
18896outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18897This particular case can be worked around by substituting @samp{[^--]}
18898for @samp{[^-]}.
18899
18900Don't leave, there is some more!
18901
18902The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18903the empty string, has a funny behavior in its exit status: it's always 1
18904when parentheses are used!
18905
18906@example
18907$ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
189080: 1
18909$ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
189101: 0
18911
18912$ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
189131: a
18914$ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
189151: 0
18916@end example
18917
18918@noindent
18919In practice this can be a big problem if you are ready to catch failures
18920of @command{expr} programs with some other method (such as using
18921@command{sed}), since you may get twice the result.  For instance
18922
18923@example
18924$ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18925@end example
18926
18927@noindent
18928outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18929simple workaround consists of testing @command{expr} and using a variable
18930set to @command{expr} or to @command{false} according to the result.
18931
18932Tru64 @command{expr} incorrectly treats the result as a number, if it
18933can be interpreted that way:
18934
18935@example
18936$ @kbd{expr 00001 : '.*\(...\)'}
189371
18938@end example
18939
18940On HP-UX 11, @command{expr} only supports a single
18941sub-expression.
18942
18943@example
18944$ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18945expr: More than one '\(' was used.
18946@end example
18947
18948
18949@item @command{fgrep}
18950@c ------------------
18951@prindex @command{fgrep}
18952Posix 1003.1-2001 no longer requires @command{fgrep},
18953but many hosts do not yet support the Posix
18954replacement @code{grep -F}.  Also, some traditional implementations do
18955not work on long input lines.  To work around these problems, invoke
18956@code{AC_PROG_FGREP} and then use @code{$FGREP}.
18957
18958Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18959
18960
18961@item @command{find}
18962@c -----------------
18963@prindex @command{find}
18964The option @option{-maxdepth} seems to be GNU specific.
18965Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18966commands do not understand it.
18967
18968The replacement of @samp{@{@}} is guaranteed only if the argument is
18969exactly @emph{@{@}}, not if it's only a part of an argument.  For
18970instance on DU, and HP-UX 10.20 and HP-UX 11:
18971
18972@example
18973$ @kbd{touch foo}
18974$ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18975@{@}-@{@}
18976@end example
18977
18978@noindent
18979while GNU @command{find} reports @samp{./foo-./foo}.
18980
18981
18982@anchor{grep}
18983@item @command{grep}
18984@c -----------------
18985@prindex @command{grep}
18986Portable scripts can rely on the @command{grep} options @option{-c},
18987@option{-l}, @option{-n}, and @option{-v}, but should avoid other
18988options.  For example, don't use @option{-w}, as Posix does not require
18989it and Irix 6.5.16m's @command{grep} does not support it.  Also,
18990portable scripts should not combine @option{-c} with @option{-l},
18991as Posix does not allow this.
18992
18993Some of the options required by Posix are not portable in practice.
18994Don't use @samp{grep -q} to suppress output, because many @command{grep}
18995implementations (e.g., Solaris) do not support @option{-q}.
18996Don't use @samp{grep -s} to suppress output either, because Posix
18997says @option{-s} does not suppress output, only some error messages;
18998also, the @option{-s} option of traditional @command{grep} behaved
18999like @option{-q} does in most modern implementations.  Instead,
19000redirect the standard output and standard error (in case the file
19001doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19002status of @code{grep} to determine whether it found a match.
19003
19004The QNX4 implementation fails to count lines with @code{grep -c '$'},
19005but works with @code{grep -c '^'}.  Other alternatives for counting
19006lines are to use @code{sed -n '$='} or @code{wc -l}.
19007
19008Some traditional @command{grep} implementations do not work on long
19009input lines.  On AIX the default @code{grep} silently truncates long
19010lines on the input before matching.
19011
19012Also, many implementations do not support multiple regexps
19013with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19014or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19015work around these problems, invoke @code{AC_PROG_GREP} and then use
19016@code{$GREP}.
19017
19018Another possible workaround for the multiple @option{-e} problem is to
19019separate the patterns by newlines, for example:
19020
19021@example
19022grep 'foo
19023bar' in.txt
19024@end example
19025
19026@noindent
19027except that this fails with traditional @command{grep}
19028implementations and with OpenBSD 3.8 @command{grep}.
19029
19030Traditional @command{grep} implementations (e.g., Solaris) do not
19031support the @option{-E} or @option{-F} options.  To work around these
19032problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19033similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19034willing to require support for Posix @command{grep}, your script should
19035not use both @option{-E} and @option{-F}, since Posix does not allow
19036this combination.
19037
19038Portable @command{grep} regular expressions should use @samp{\} only to
19039escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19040alternation, @samp{\|}, is common but Posix does not require its
19041support in basic regular expressions, so it should be avoided in
19042portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19043Similarly, the following escape sequences should also be avoided:
19044@samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19045@samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19046
19047Posix does not specify the behavior of @command{grep} on binary files.
19048An example where this matters is using BSD @command{grep} to
19049search text that includes embedded ANSI escape sequences for
19050colored output to terminals (@samp{\033[m} is the sequence to restore
19051normal output); the behavior depends on whether input is seekable:
19052
19053@example
19054$ @kbd{printf 'esc\033[mape\n' > sample}
19055$ @kbd{grep . sample}
19056Binary file sample matches
19057$ @kbd{cat sample | grep .}
19058escape
19059@end example
19060
19061
19062@item @command{join}
19063@c -----------------
19064@prindex @command{join}
19065Solaris 8 @command{join} has bugs when the second operand is standard
19066input, and when standard input is a pipe.  For example, the following
19067shell script causes Solaris 8 @command{join} to loop forever:
19068
19069@example
19070cat >file <<'EOF'
190711 x
190722 y
19073EOF
19074cat file | join file -
19075@end example
19076
19077Use @samp{join - file} instead.
19078
19079On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19080@command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19081the workaround is to use @command{join -a1 file1 file2} instead.
19082
19083@item @command{ln}
19084@c ---------------
19085@prindex @command{ln}
19086@cindex Symbolic links
19087Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
19088are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
19089
19090For versions of the DJGPP before 2.04,
19091@command{ln} emulates symbolic links
19092to executables by generating a stub that in turn calls the real
19093program.  This feature also works with nonexistent files like in the
19094Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19095which attempts to call @file{file.exe} if run.  But this feature only
19096works for executables, so @samp{cp -p} is used instead for these
19097systems.  DJGPP versions 2.04 and later have full support
19098for symbolic links.
19099
19100
19101@item @command{ls}
19102@c ---------------
19103@prindex @command{ls}
19104@cindex Listing directories
19105The portable options are @option{-acdilrtu}.  Current practice is for
19106@option{-l} to output both owner and group, even though ancient versions
19107of @command{ls} omitted the group.
19108
19109On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19110to standard output if @file{foo} did not exist.  Hence a shell command
19111like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19112was equivalent to @samp{sources='*.c not found'} in the absence of
19113@samp{.c} files.  This is no longer a practical problem, since current
19114@command{ls} implementations send diagnostics to standard error.
19115
19116The behavior of @command{ls} on a directory that is being concurrently
19117modified is not always predictable, because of a data race where cached
19118information returned by @code{readdir} does not match the current
19119directory state.  In fact, MacOS 10.5 has an intermittent bug where
19120@code{readdir}, and thus @command{ls}, sometimes lists a file more than
19121once if other files were added or removed from the directory immediately
19122prior to the @command{ls} call.  Since @command{ls} already sorts its
19123output, the duplicate entries can be avoided by piping the results
19124through @code{uniq}.
19125
19126@anchor{mkdir}
19127@item @command{mkdir}
19128@c ------------------
19129@prindex @command{mkdir}
19130@cindex Making directories
19131No @command{mkdir} option is portable to older systems.  Instead of
19132@samp{mkdir -p @var{file-name}}, you should use
19133@code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19134or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19135
19136Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19137go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19138@command{mkdir} incorrectly attempts to change the permissions of
19139@var{dir} even if it already exists.  HP-UX 11.23 and
19140IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19141any newly-created parents of @var{dir}.
19142
19143Posix does not clearly specify whether @samp{mkdir -p foo}
19144should succeed when @file{foo} is a symbolic link to an already-existing
19145directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19146succeeds, but Solaris @command{mkdir} fails.
19147
19148Traditional @code{mkdir -p} implementations suffer from race conditions.
19149For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19150at the same time, both processes might detect that @file{a} is missing,
19151one might create @file{a}, then the other might try to create @file{a}
19152and fail with a @code{File exists} diagnostic.  The GNU Core
19153Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19154NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19155race-free when two processes invoke @code{mkdir -p} simultaneously, but
19156earlier versions are vulnerable.  Solaris @command{mkdir} is still
19157vulnerable as of Solaris 10, and other traditional Unix systems are
19158probably vulnerable too.  This possible race is harmful in parallel
19159builds when several Make rules call @code{mkdir -p} to
19160construct directories.  You may use
19161@code{install-sh -d} as a safe replacement, provided this script is
19162recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19163OK, but copies from older versions are vulnerable.
19164
19165
19166@item @command{mkfifo}
19167@itemx @command{mknod}
19168@c -------------------
19169@prindex @command{mkfifo}
19170@prindex @command{mknod}
19171The GNU Coding Standards state that @command{mknod} is safe to use on
19172platforms where it has been tested to exist; but it is generally portable
19173only for creating named FIFOs, since device numbers are
19174platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19175testsuites.  Posix states that behavior is unspecified when opening a
19176named FIFO for both reading and writing; on at least Cygwin, this
19177results in failure on any attempt to read or write to that file
19178descriptor.
19179
19180@item @command{mktemp}
19181@c -------------------
19182@prindex @command{mktemp}
19183@cindex Creating temporary files
19184Shell scripts can use temporary files safely with @command{mktemp}, but
19185it does not exist on all systems.  A portable way to create a safe
19186temporary file name is to create a temporary directory with mode 700 and
19187use a file inside this directory.  Both methods prevent attackers from
19188gaining control, though @command{mktemp} is far less likely to fail
19189gratuitously under attack.
19190
19191Here is sample code to create a new temporary directory @samp{$dir} safely:
19192
19193@example
19194# Create a temporary directory $dir in $TMPDIR (default /tmp).
19195# Use mktemp if possible; otherwise fall back on mkdir,
19196# with $RANDOM to make collisions less likely.
19197: "$@{TMPDIR:=/tmp@}"
19198@{
19199  dir=`
19200    (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19201  ` &&
19202  test -d "$dir"
19203@} || @{
19204  dir=$TMPDIR/foo$$-$RANDOM
19205@c $$ restore font-lock
19206  (umask 077 && mkdir "$dir")
19207@} || exit $?
19208@end example
19209
19210
19211@item @command{mv}
19212@c ---------------
19213@prindex @command{mv}
19214@cindex Moving open files
19215The only portable options are @option{-f} and @option{-i}.
19216
19217Moving individual files between file systems is portable (it was in Unix
19218version 6),
19219but it is not always atomic: when doing @samp{mv new existing}, there's
19220a critical section where neither the old nor the new version of
19221@file{existing} actually exists.
19222
19223On some systems moving files from @file{/tmp} can sometimes cause
19224undesirable (but perfectly valid) warnings, even if you created these
19225files.  This is because @file{/tmp} belongs to a group that ordinary
19226users are not members of, and files created in @file{/tmp} inherit
19227the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19228a diagnostic without failing:
19229
19230@smallexample
19231$ @kbd{touch /tmp/foo}
19232$ @kbd{mv /tmp/foo .}
19233@error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19234$ @kbd{echo $?}
192350
19236$ @kbd{ls foo}
19237foo
19238@end smallexample
19239
19240@noindent
19241This annoying behavior conforms to Posix, unfortunately.
19242
19243Moving directories across mount points is not portable, use @command{cp}
19244and @command{rm}.
19245
19246DOS variants cannot rename or remove open files, and do not
19247support commands like @samp{mv foo bar >foo}, even though this is
19248perfectly portable among Posix hosts.
19249
19250
19251@item @command{od}
19252@c ---------------
19253@prindex @command{od}
19254
19255In Mac OS X 10.3, @command{od} does not support the
19256standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19257@option{-t}, or the XSI option @option{-s}.  The only
19258supported Posix option is @option{-v}, and the only supported
19259XSI options are those in @option{-bcdox}.  The BSD
19260@command{hexdump} program can be used instead.
19261
19262This problem no longer exists in Mac OS X 10.4.3.
19263
19264
19265@item @command{rm}
19266@c ---------------
19267@prindex @command{rm}
19268The @option{-f} and @option{-r} options are portable.
19269
19270It is not portable to invoke @command{rm} without options or operands.
19271On the other hand, Posix now requires @command{rm -f} to silently
19272succeed when there are no operands (useful for constructs like
19273@command{rm -rf $filelist} without first checking if @samp{$filelist}
19274was empty).  But this was not always portable; at least NetBSD
19275@command{rm} built before 2008 would fail with a diagnostic.
19276
19277A file might not be removed even if its parent directory is writable
19278and searchable.  Many Posix hosts cannot remove a mount point, a named
19279stream, a working directory, or a last link to a file that is being
19280executed.
19281
19282DOS variants cannot rename or remove open files, and do not
19283support commands like @samp{rm foo >foo}, even though this is
19284perfectly portable among Posix hosts.
19285
19286@item @command{rmdir}
19287@c ------------------
19288@prindex @command{rmdir}
19289Just as with @command{rm}, some platforms refuse to remove a working
19290directory.
19291
19292@anchor{sed}
19293@item @command{sed}
19294@c ----------------
19295@prindex @command{sed}
19296Patterns should not include the separator (unless escaped), even as part
19297of a character class.  In conformance with Posix, the Cray
19298@command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19299Even when escaped, patterns should not include separators that are also
19300used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19301@samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19302before evaluating the basic regular expression.
19303
19304Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19305not require support for empty patterns, and Unicos 9 @command{sed} rejects
19306them.
19307
19308Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19309
19310Sed scripts should not use branch labels longer than 7 characters and
19311should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19312HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
1931348 labels, which cannot be circumvented by using more than one script
19314file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19315Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19316about 6000 bytes for the internal representation of commands.
19317
19318Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19319NetBSD 1.4.2's, incorrectly try to interpret the second
19320@samp{;} as a command:
19321
19322@example
19323$ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19324sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19325@end example
19326
19327Some @command{sed} implementations have a buffer limited to 4000 bytes,
19328and this limits the size of input lines, output lines, and internal
19329buffers that can be processed portably.  Likewise,
19330not all @command{sed} implementations can handle embedded @code{NUL} or
19331a missing trailing newline.
19332
19333Remember that ranges within a bracket expression of a regular expression
19334are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19335Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19336yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19337it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19338than to rely on @samp{[A-Z]}.
19339
19340Additionally, Posix states that regular expressions are only
19341well-defined on characters.  Unfortunately, there exist platforms such
19342as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19343even though that platform has a single-byte @samp{C} locale.  And Posix
19344allows the existence of a multi-byte @samp{C} locale, although that does
19345not yet appear to be a common implementation.  At any rate, it means
19346that not all bytes will be matched by the regular expression @samp{.}:
19347
19348@example
19349$ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
193500
19351$ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
193521
19353@end example
19354
19355Portable @command{sed} regular expressions should use @samp{\} only to escape
19356characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19357alternation, @samp{\|}, is common but Posix does not require its
19358support, so it should be avoided in portable scripts.  Solaris
19359@command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19360deletes only lines that contain the literal string @samp{a|b}.
19361Similarly, @samp{\+} and @samp{\?} should be avoided.
19362
19363Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19364
19365Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19366quite portable to current hosts, but was not supported by some ancient
19367@command{sed} implementations like SVR3.
19368
19369Some @command{sed} implementations, e.g., Solaris, restrict the special
19370role of the asterisk @samp{*} to one-character regular expressions and
19371back-references, and the special role of interval expressions
19372@samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19373to one-character regular expressions.  This may lead to unexpected behavior:
19374
19375@example
19376$ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19377x2x4
19378$ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19379x
19380@end example
19381
19382The @option{-e} option is mostly portable.
19383However, its argument
19384cannot start with @samp{a}, @samp{c}, or @samp{i},
19385as this runs afoul of a Tru64 5.1 bug.
19386Also, its argument cannot be empty, as this fails on AIX 5.3.
19387Some people prefer to use @samp{-e}:
19388
19389@example
19390sed -e '@var{command-1}' \
19391    -e '@var{command-2}'
19392@end example
19393
19394@noindent
19395as opposed to the equivalent:
19396
19397@example
19398sed '
19399  @var{command-1}
19400  @var{command-2}
19401'
19402@end example
19403
19404@noindent
19405The following usage is sometimes equivalent:
19406
19407@example
19408sed '@var{command-1};@var{command-2}'
19409@end example
19410
19411but Posix says that this use of a semicolon has undefined effect if
19412@var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19413@samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19414should use semicolon only with simple scripts that do not use these
19415verbs.
19416
19417Posix up to the 2008 revision requires the argument of the @option{-e}
19418option to be a syntactically complete script.  GNU @command{sed} allows
19419to pass multiple script fragments, each as argument of a separate
19420@option{-e} option, that are then combined, with newlines between the
19421fragments, and a future Posix revision may allow this as well.  This
19422approach is not portable with script fragments ending in backslash; for
19423example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19424don't allow splitting in this case:
19425
19426@example
19427$ @kbd{echo a | sed -n -e 'i\}
19428@kbd{0'}
194290
19430$ @kbd{echo a | sed -n -e 'i\' -e 0}
19431Unrecognized command: 0
19432@end example
19433
19434@noindent
19435In practice, however, this technique of joining fragments
19436through @option{-e} works for multiple @command{sed} functions within
19437@samp{@{} and @samp{@}}, even if that is not specified by Posix:
19438
19439@example
19440@c The quote around the closing brace silences interactive zsh.
19441$ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19442b
19443@end example
19444
19445Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19446they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19447each command must be followed immediately by a newline, without any
19448intervening blanks or semicolons.  The closing bracket must be alone on
19449a line, other than white space preceding or following it.  However, a
19450future version of Posix may standardize the use of addresses within brackets.
19451
19452Contrary to yet another urban legend, you may portably use @samp{&} in
19453the replacement part of the @code{s} command to mean ``what was
19454matched''.  All descendants of Unix version 7 @command{sed}
19455(at least; we
19456don't have first hand experience with older @command{sed} implementations) have
19457supported it.
19458
19459Posix requires that you must not have any white space between
19460@samp{!} and the following command.  It is OK to have blanks between
19461the address and the @samp{!}.  For instance, on Solaris:
19462
19463@example
19464$ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19465@error{}Unrecognized command: /bar/ ! p
19466$ @kbd{echo "foo" | sed -n '/bar/! p'}
19467@error{}Unrecognized command: /bar/! p
19468$ @kbd{echo "foo" | sed -n '/bar/ !p'}
19469foo
19470@end example
19471
19472Posix also says that you should not combine @samp{!} and @samp{;}.  If
19473you use @samp{!}, it is best to put it on a command that is delimited by
19474newlines rather than @samp{;}.
19475
19476Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19477@samp{w} commands be followed by exactly one space before their argument.
19478On the other hand, no white space is allowed between @samp{:} and the
19479subsequent label name.
19480
19481If a sed script is specified on the command line and ends in an
19482@samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19483should be followed by a newline.  Otherwise some @command{sed}
19484implementations (e.g., OpenBSD 3.9) do not append a newline to the
19485inserted text.
19486
19487Many @command{sed} implementations (e.g., MacOS X 10.4,
19488OpenBSD 3.9, Solaris 10
19489@command{/usr/ucb/sed}) strip leading white space from the text of
19490@samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19491work around this incompatibility with Posix:
19492
19493@example
19494$ @kbd{echo flushleft | sed 'a\}
19495> @kbd{   indented}
19496> @kbd{'}
19497flushleft
19498indented
19499$ @kbd{echo foo | sed 'a\}
19500> @kbd{\   indented}
19501> @kbd{'}
19502flushleft
19503   indented
19504@end example
19505
19506Posix requires that with an empty regular expression, the last non-empty
19507regular expression from either an address specification or substitution
19508command is applied.  However, busybox 1.6.1 complains when using a
19509substitution command with a replacement containing a back-reference to
19510an empty regular expression; the workaround is repeating the regular
19511expression.
19512
19513@example
19514$ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19515sed: No previous regexp.
19516$ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19517b
19518@end example
19519
19520
19521@item @command{sed} (@samp{t})
19522@c ---------------------------
19523@prindex @command{sed} (@samp{t})
19524Some old systems have @command{sed} that ``forget'' to reset their
19525@samp{t} flag when starting a new cycle.  For instance on MIPS
19526RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19527script (the line numbers are not actual part of the texts):
19528
19529@example
19530s/keep me/kept/g  # a
19531t end             # b
19532s/.*/deleted/g    # c
19533:end              # d
19534@end example
19535
19536@noindent
19537on
19538
19539@example
19540delete me         # 1
19541delete me         # 2
19542keep me           # 3
19543delete me         # 4
19544@end example
19545
19546@noindent
19547you get
19548
19549@example
19550deleted
19551delete me
19552kept
19553deleted
19554@end example
19555
19556@noindent
19557instead of
19558
19559@example
19560deleted
19561deleted
19562kept
19563deleted
19564@end example
19565
19566Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19567flag, and the output is produced.  When processing
19568line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19569fails to match, but @command{sed} is not supposed to clear the @samp{t}
19570flag when a substitution fails.  Command (b) sees that the flag is set,
19571therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19572instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19573(a) matches, so the flag is set, hence (b) clears the flags and jumps.
19574Finally, since the flag is clear, line 4 is processed properly.
19575
19576There are two things one should remember about @samp{t} in @command{sed}.
19577Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19578succeeded, not only the immediately preceding substitution.  Therefore,
19579always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19580line, to reset the @samp{t} flag where needed.
19581
19582Secondly, you cannot rely on @command{sed} to clear the flag at each new
19583cycle.
19584
19585One portable implementation of the script above is:
19586
19587@example
19588t clear
19589:clear
19590s/keep me/kept/g
19591t end
19592s/.*/deleted/g
19593:end
19594@end example
19595
19596@item @command{sleep}
19597@c ------------------
19598@prindex @command{sleep}
19599Using @command{sleep} is generally portable.  However, remember that
19600adding a @command{sleep} to work around timestamp issues, with a minimum
19601granularity of one second, doesn't scale well for parallel builds on
19602modern machines with sub-second process completion.
19603
19604@item @command{sort}
19605@c -----------------
19606@prindex @command{sort}
19607Remember that sort order is influenced by the current locale.  Inside
19608@file{configure}, the C locale is in effect, but in Makefile snippets,
19609you may need to specify @code{LC_ALL=C sort}.
19610
19611@item @command{tar}
19612@c ----------------
19613@prindex @command{tar}
19614There are multiple file formats for @command{tar}; if you use Automake,
19615the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19616level of portability to use.
19617
19618@anchor{touch}
19619@item @command{touch}
19620@c ------------------
19621@prindex @command{touch}
19622@cindex timestamp resolution
19623If you specify the desired timestamp (e.g., with the @option{-r}
19624option), older @command{touch} implementations use the @code{utime} or
19625@code{utimes} system call, which can result in the same kind of
19626timestamp truncation problems that @samp{cp -p} has.
19627
19628On ancient BSD systems, @command{touch} or any command that
19629results in an empty file does not update the timestamps, so use a
19630command like @command{echo} as a workaround.
19631Also,
19632GNU @command{touch} 3.16r (and presumably all before that)
19633fails to work on SunOS 4.1.3 when the empty file is on an
19634NFS-mounted 4.2 volume.
19635However, these problems are no longer of practical concern.
19636
19637@item @command{tr}
19638@c ---------------
19639@prindex @command{tr}
19640@cindex carriage return, deleting
19641@cindex newline, deleting
19642@cindex deleting carriage return
19643Not all versions of @command{tr} handle all backslash character escapes.
19644For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19645Solaris contains more modern @command{tr} in other locations.
19646Using octal escapes is more portable for carriage returns, since
19647@samp{\015} is the same for both ASCII and EBCDIC, and since use of
19648literal carriage returns in scripts causes a number of other problems.
19649But for other characters, like newline, using octal escapes ties the
19650operation to ASCII, so it is better to use literal characters.
19651
19652@example
19653$ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19654moo
19655light
19656$ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19657moonlight
19658$ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19659moonlight
19660$ @kbd{nl='}
19661@kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19662moonlight
19663@end example
19664
19665Not all versions of @command{tr} recognize direct ranges of characters: at
19666least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19667use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19668transliterate to themselves).
19669
19670@example
19671$ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19672HAZy FAntAZy
19673$ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19674HAZY FANTAZY
19675$ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19676HAZY FANTAZY
19677@end example
19678
19679When providing two arguments, be sure the second string is at least as
19680long as the first.
19681
19682@example
19683$ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19684adc
19685$ @kbd{echo abc | coreutils/tr bc d}
19686add
19687@end example
19688
19689Posix requires @command{tr} to operate on binary files.  But at least
19690Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19691@code{NUL} in the input prior to doing any translation.  When using
19692@command{tr} to process a binary file that may contain @code{NUL} bytes,
19693it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19694@command{/usr/xpg6/bin/tr} if that is available.
19695
19696@example
19697$ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19698 61 62
19699$ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19700 61 62
19701$ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19702 61 00 62
19703@end example
19704
19705Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19706octal escape for @code{NUL}.
19707
19708@example
19709$ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19710 61 62 63
19711$ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19712 61 00 64
19713$ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19714 61 00 64
19715@end example
19716
19717@end table
19718
19719
19720@node Portable Make
19721@chapter Portable Make Programming
19722@prindex @command{make}
19723@cindex Limitations of @command{make}
19724
19725Writing portable makefiles is an art.  Since a makefile's commands are
19726executed by the shell, you must consider the shell portability issues
19727already mentioned.  However, other issues are specific to @command{make}
19728itself.
19729
19730@menu
19731* $< in Ordinary Make Rules::   $< in ordinary rules
19732* Failure in Make Rules::       Failing portably in rules
19733* Special Chars in Names::      Special Characters in Macro Names
19734* Backslash-Newline-Empty::     Empty lines after backslash-newline
19735* Backslash-Newline Comments::  Spanning comments across line boundaries
19736* Long Lines in Makefiles::     Line length limitations
19737* Macros and Submakes::         @code{make macro=value} and submakes
19738* The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19739* The Make Macro SHELL::        @code{$(SHELL)} portability issues
19740* Parallel Make::               Parallel @command{make} quirks
19741* Comments in Make Rules::      Other problems with Make comments
19742* Newlines in Make Rules::      Using literal newlines in rules
19743* Comments in Make Macros::     Other problems with Make comments in macros
19744* Trailing whitespace in Make Macros::  Macro substitution problems
19745* Command-line Macros and whitespace::  Whitespace trimming of values
19746* obj/ and Make::               Don't name a subdirectory @file{obj}
19747* make -k Status::              Exit status of @samp{make -k}
19748* VPATH and Make::              @code{VPATH} woes
19749* Single Suffix Rules::         Single suffix rules and separated dependencies
19750* Timestamps and Make::         Subsecond timestamp resolution
19751@end menu
19752
19753@node $< in Ordinary Make Rules
19754@section @code{$<} in Ordinary Make Rules
19755
19756Posix says that the @samp{$<} construct in makefiles can be
19757used only in inference rules and in the @samp{.DEFAULT} rule; its
19758meaning in ordinary rules is unspecified.  Solaris @command{make}
19759for instance replaces it with the empty string.  OpenBSD (3.0 and
19760later) @command{make} diagnoses these uses and errors out.
19761
19762@node Failure in Make Rules
19763@section Failure in Make Rules
19764
19765Posix 2008 requires that @command{make} must invoke each command with
19766the equivalent of a @samp{sh -e -c} subshell, which causes the
19767subshell to exit immediately if a subsidiary simple-command fails,
19768although not all @command{make} implementations have historically
19769followed this rule.  For
19770example, the command @samp{touch T; rm -f U} may attempt to
19771remove @file{U} even if the @command{touch} fails, although this is not
19772permitted with Posix make.  One way to work around failures in simple
19773commands is to reword them so that they always succeed, e.g., @samp{touch
19774T || :; rm -f U}.
19775However, even this approach can run into common bugs in BSD
19776implementations of the @option{-e} option of @command{sh} and
19777@command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19778are worried
19779about porting to buggy BSD shells it may be simpler to migrate
19780complicated @command{make} actions into separate scripts.
19781
19782@node Special Chars in Names
19783@section Special Characters in Make Macro Names
19784
19785Posix limits macro names to nonempty strings containing only
19786ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19787@command{make} implementations allow a wider variety of characters, but
19788portable makefiles should avoid them.  It is portable to start a name
19789with a special character, e.g., @samp{$(.FOO)}.
19790
19791Some ancient @command{make} implementations don't support leading
19792underscores in macro names.  An example is NEWS-OS 4.2R.
19793
19794@example
19795$ @kbd{cat Makefile}
19796_am_include = #
19797_am_quote =
19798all:; @@echo this is test
19799$ @kbd{make}
19800Make: Must be a separator on rules line 2.  Stop.
19801$ @kbd{cat Makefile2}
19802am_include = #
19803am_quote =
19804all:; @@echo this is test
19805$ @kbd{make -f Makefile2}
19806this is test
19807@end example
19808
19809@noindent
19810However, this problem is no longer of practical concern.
19811
19812@node Backslash-Newline-Empty
19813@section Backslash-Newline Before Empty Lines
19814
19815A bug in Bash 2.03 can cause problems if a Make rule contains a
19816backslash-newline followed by line that expands to nothing.
19817For example, on Solaris 8:
19818
19819@example
19820SHELL = /bin/bash
19821EMPTY =
19822foo:
19823	touch foo \
19824	$(EMPTY)
19825@end example
19826
19827@noindent
19828executes
19829
19830@example
19831/bin/bash -c 'touch foo \
19832'
19833@end example
19834
19835@noindent
19836which fails with a syntax error, due to the Bash bug.  To avoid this
19837problem, avoid nullable macros in the last line of a multiline command.
19838
19839@c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19840@c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19841@c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19842On some versions of HP-UX, @command{make} reads multiple newlines
19843following a backslash, continuing to the next non-empty line.  For
19844example,
19845
19846@example
19847FOO = one \
19848
19849BAR = two
19850
19851test:
19852        : FOO is "$(FOO)"
19853        : BAR is "$(BAR)"
19854@end example
19855
19856@noindent
19857shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19858sensibly let a backslash continue only to the immediately following
19859line.
19860
19861@node Backslash-Newline Comments
19862@section Backslash-Newline in Make Comments
19863
19864According to Posix, Make comments start with @code{#}
19865and continue until an unescaped newline is reached.
19866
19867@example
19868$ @kbd{cat Makefile}
19869# A = foo \
19870      bar \
19871      baz
19872
19873all:
19874        @@echo ok
19875$ @kbd{make}   # GNU make
19876ok
19877@end example
19878
19879@noindent
19880However this is not always the case.  Some implementations
19881discard everything from @code{#} through the end of the line, ignoring any
19882trailing backslash.
19883
19884@example
19885$ @kbd{pmake}  # BSD make
19886"Makefile", line 3: Need an operator
19887Fatal errors encountered -- cannot continue
19888@end example
19889
19890@noindent
19891Therefore, if you want to comment out a multi-line definition, prefix each
19892line with @code{#}, not only the first.
19893
19894@example
19895# A = foo \
19896#     bar \
19897#     baz
19898@end example
19899
19900@node Long Lines in Makefiles
19901@section Long Lines in Makefiles
19902
19903Tru64 5.1's @command{make} has been reported to crash when given a
19904makefile with lines longer than around 20 kB.  Earlier versions are
19905reported to exit with @code{Line too long} diagnostics.
19906
19907@node Macros and Submakes
19908@section @code{make macro=value} and Submakes
19909
19910A command-line variable definition such as @code{foo=bar} overrides any
19911definition of @code{foo} in a makefile.  Some @command{make}
19912implementations (such as GNU @command{make}) propagate this
19913override to subsidiary invocations of @command{make}.  Some other
19914implementations do not pass the substitution along to submakes.
19915
19916@example
19917$ @kbd{cat Makefile}
19918foo = foo
19919one:
19920        @@echo $(foo)
19921        $(MAKE) two
19922two:
19923        @@echo $(foo)
19924$ @kbd{make foo=bar}            # GNU make 3.79.1
19925bar
19926make two
19927make[1]: Entering directory `/home/adl'
19928bar
19929make[1]: Leaving directory `/home/adl'
19930$ @kbd{pmake foo=bar}           # BSD make
19931bar
19932pmake two
19933foo
19934@end example
19935
19936You have a few possibilities if you do want the @code{foo=bar} override
19937to propagate to submakes.  One is to use the @option{-e}
19938option, which causes all environment variables to have precedence over
19939the makefile macro definitions, and declare foo as an environment
19940variable:
19941
19942@example
19943$ @kbd{env foo=bar make -e}
19944@end example
19945
19946The @option{-e} option is propagated to submakes automatically,
19947and since the environment is inherited between @command{make}
19948invocations, the @code{foo} macro is overridden in
19949submakes as expected.
19950
19951This syntax (@code{foo=bar make -e}) is portable only when used
19952outside of a makefile, for instance from a script or from the
19953command line.  When run inside a @command{make} rule, GNU
19954@command{make} 3.80 and prior versions forget to propagate the
19955@option{-e} option to submakes.
19956
19957Moreover, using @option{-e} could have unexpected side effects if your
19958environment contains some other macros usually defined by the
19959makefile.  (See also the note about @code{make -e} and @code{SHELL}
19960below.)
19961
19962If you can foresee all macros that a user might want to override, then
19963you can propagate them to submakes manually, from your makefile:
19964
19965@example
19966foo = foo
19967one:
19968        @@echo $(foo)
19969        $(MAKE) foo=$(foo) two
19970two:
19971        @@echo $(foo)
19972@end example
19973
19974Another way to propagate a variable to submakes in a portable way is to
19975expand an extra variable in every invocation of @samp{$(MAKE)} within
19976your makefile:
19977
19978@example
19979foo = foo
19980one:
19981        @@echo $(foo)
19982        $(MAKE) $(SUBMAKEFLAGS) two
19983two:
19984        @@echo $(foo)
19985@end example
19986
19987Users must be aware that this technique is in use to take advantage of
19988it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
19989allows any macro to be overridden.  Makefiles generated by
19990@command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
19991on the command lines of submakes (@pxref{Subdirectories, , Automake,
19992automake, GNU Automake}).
19993
19994@node The Make Macro MAKEFLAGS
19995@section The Make Macro MAKEFLAGS
19996@cindex @code{MAKEFLAGS} and @command{make}
19997@cindex @command{make} and @code{MAKEFLAGS}
19998
19999Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20000current and recursive invocations of make, but allows implementations
20001several formats for the variable.  It is tricky to parse
20002@code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20003or @option{-k} for continued execution are in effect.  For example, you
20004cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20005contains single-letter options, since in the Cygwin version of
20006GNU @command{make} it is either @option{--unix} or
20007@option{--win32} with the second word containing single-letter options.
20008
20009@example
20010$ @kbd{cat Makefile}
20011all:
20012        @@echo MAKEFLAGS = $(MAKEFLAGS)
20013$ @kbd{make}
20014MAKEFLAGS = --unix
20015$ @kbd{make -k}
20016MAKEFLAGS = --unix -k
20017@end example
20018
20019@node The Make Macro SHELL
20020@section The Make Macro @code{SHELL}
20021@cindex @code{SHELL} and @command{make}
20022@cindex @command{make} and @code{SHELL}
20023
20024Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20025macro to spawn shell processes and execute Make rules.  This
20026is a builtin macro supplied by @command{make}, but it can be modified
20027by a makefile or by a command-line argument.
20028
20029Not all @command{make} implementations define this @code{SHELL} macro.
20030Tru64
20031@command{make} is an example; this implementation always uses
20032@code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20033your makefiles.  If you use Autoconf, do
20034
20035@example
20036SHELL = @@SHELL@@
20037@end example
20038
20039@noindent
20040If you use Automake, this is done for you.
20041
20042Do not force @code{SHELL = /bin/sh} because that is not correct
20043everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20044systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20045Additionally, DJGPP lacks @code{/bin/sh}, and when its
20046GNU @command{make} port sees such a setting it enters a
20047special emulation mode where features like pipes and redirections are
20048emulated on top of DOS's @command{command.com}.  Unfortunately this
20049emulation is incomplete; for instance it does not handle command
20050substitutions.  Using @code{@@SHELL@@} means that your makefile will
20051benefit from the same improved shell, such as @command{bash} or
20052@command{ksh}, that was discovered during @command{configure}, so that
20053you aren't fighting two different sets of shell bugs between the two
20054contexts.
20055
20056Posix-compliant @command{make} should never acquire the value of
20057$(SHELL) from the environment, even when @code{make -e} is used
20058(otherwise, think about what would happen to your rules if
20059@code{SHELL=/bin/tcsh}).
20060
20061However not all @command{make} implementations have this exception.
20062For instance it's not surprising that Tru64 @command{make} doesn't
20063protect @code{SHELL}, since it doesn't use it.
20064
20065@example
20066$ @kbd{cat Makefile}
20067SHELL = /bin/sh
20068FOO = foo
20069all:
20070        @@echo $(SHELL)
20071        @@echo $(FOO)
20072$ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20073/bin/tcsh
20074bar
20075$ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20076/bin/sh
20077bar
20078@end example
20079
20080Conversely, @command{make} is not supposed to export any changes to the
20081macro @code{SHELL} to child processes.  Again, many implementations
20082break this rule:
20083
20084@example
20085$ @kbd{cat Makefile}
20086all:
20087        @@echo $(SHELL)
20088        @@printenv SHELL
20089$ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20090/bin/ksh
20091/bin/ksh
20092$ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20093/bin/ksh
20094sh
20095@end example
20096
20097@node Parallel Make
20098@section Parallel Make
20099@cindex Parallel @command{make}
20100
20101Support for parallel execution in @command{make} implementation varies.
20102Generally, using GNU make is your best bet.
20103
20104When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20105reuse the same shell for multiple commands within one recipe.  This can
20106have various unexpected consequences.  For example, changes of directories
20107or variables persist between recipes, so that:
20108
20109@example
20110all:
20111        @@var=value; cd /; pwd; echo $$var; echo $$$$
20112        @@pwd; echo $$var; echo $$$$
20113@end example
20114
20115@noindent
20116may output the following with @code{make -j1}, at least on NetBSD up to
201175.1 and FreeBSD up to 8.2:
20118
20119@example
20120/
20121value
2012232235
20123/
20124value
2012532235
20126@end example
20127
20128@noindent
20129while without @option{-j1}, or with @option{-B}, the output looks less
20130surprising:
20131
20132@example
20133/
20134value
2013532238
20136/tmp
20137
2013832239
20139@end example
20140
20141@noindent
20142Another consequence is that, if one command in a recipe uses @code{exit 0}
20143to indicate a successful exit, the shell will be gone and the remaining
20144commands of this recipe will not be executed.
20145
20146The BSD @command{make} implementations, when run in parallel mode,
20147will also pass the @command{Makefile} recipes to the shell through
20148its standard input, thus making it unusable from the recipes:
20149
20150@example
20151$ @kbd{cat Makefile}
20152read:
20153        @@read line; echo LINE: $$line
20154@c $$ @c restore font-lock
20155$ @kbd{echo foo | make read}
20156LINE: foo
20157$ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20158LINE:
20159@end example
20160
20161@noindent
20162Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20163parallel mode, it implements the @code{@@} and @code{-} ``recipe
20164modifiers'' by dynamically modifying the active shell flags.  This
20165behavior has the effects of potentially clobbering the exit status
20166of recipes silenced with the @code{@@} modifier if they also unset
20167the @option{errexit} shell flag, and of mangling the output in
20168unexpected ways:
20169
20170@example
20171$ @kbd{cat Makefile}
20172a:
20173        @@echo $$-; set +e; false
20174b:
20175        -echo $$-; false; echo set -
20176$ @kbd{make a; echo status: $?}
20177ehBc
20178*** Error code 1
20179status: 1
20180$ @kbd{make -j1 a; echo status: $?}
20181ehB
20182status: 0
20183$ @kbd{make b}
20184echo $-; echo set -
20185hBc
20186set -
20187$ @kbd{make -j1 b}
20188echo $-; echo hvB
20189@end example
20190
20191@noindent
20192You can avoid all these issues by using the @option{-B} option to enable
20193compatibility semantics.  However, that will effectively also disable
20194all parallelism as that will cause prerequisites to be updated in the
20195order they are listed in a rule.
20196
20197Some make implementations (among them, FreeBSD @command{make}, NetBSD
20198@command{make}, and Solaris @command{dmake}), when invoked with a
20199@option{-j@var{N}} option, connect the standard output and standard
20200error of all their child processes to pipes or temporary regular
20201files.  This can lead to subtly different semantics in the behavior
20202of the spawned processes.  For example, even if the @command{make}
20203standard output is connected to a tty, the recipe command will not be:
20204
20205@example
20206$ @kbd{cat Makefile}
20207all:
20208        @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20209$ @kbd{make -j 2} # FreeBSD 8.2 make
20210Is not a tty
20211$ @kbd{make -j 2} # NetBSD 5.1 make
20212--- all ---
20213Is not a tty
20214$ @kbd{dmake -j 2} # Solaris 10 dmake
20215@var{hostname} --> 1 job
20216@var{hostname} --> Job output
20217Is not a tty
20218@end example
20219
20220@noindent
20221On the other hand:
20222
20223@example
20224$ @kbd{make -j 2} # GNU make, Heirloom make
20225Is a tty
20226@end example
20227
20228@noindent
20229The above examples also show additional status output produced in parallel
20230mode for targets being updated by Solaris @command{dmake} and NetBSD
20231@command{make} (but @emph{not} by FreeBSD @command{make}).
20232
20233Furthermore, parallel runs of those @command{make} implementations will
20234route standard error from commands that they spawn into their own
20235standard output, and may remove leading whitespace from output lines.
20236
20237
20238@node Comments in Make Rules
20239@section Comments in Make Rules
20240@cindex Comments in @file{Makefile} rules
20241@cindex @file{Makefile} rules and comments
20242
20243Never put comments in a rule.
20244
20245Some @command{make} treat anything starting with a tab as a command for
20246the current rule, even if the tab is immediately followed by a @code{#}.
20247The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20248makefile runs @code{# foo} through the shell.
20249
20250@example
20251all:
20252        # foo
20253@end example
20254
20255As a workaround, you can use the @command{:} no-op command with a string
20256argument that gets ignored:
20257
20258@example
20259all:
20260        : "foo"
20261@end example
20262
20263Conversely, if you want to use the @samp{#} character in some command,
20264you can only do so by expanding it inside a rule (@pxref{Comments in
20265Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20266@command{config.status} as @samp{#}, then the following substitutes
20267@samp{@@COMMENT_CHAR@@} in a generated header:
20268
20269@example
20270foo.h: foo.h.in
20271        sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20272            $(srcdir)/foo.h.in > $@@
20273@end example
20274
20275The funny shell quoting avoids a substitution at @command{config.status}
20276run time of the left-hand side of the @command{sed} @samp{s} command.
20277
20278@node Newlines in Make Rules
20279@section Newlines in Make Rules
20280@cindex Newlines in @file{Makefile} rules
20281@cindex @file{Makefile} rules and newlines
20282
20283In shell scripts, newlines can be used inside string literals.  But in
20284the shell statements of @file{Makefile} rules, this is not possible:
20285A newline not preceded by a backslash is a separator between shell
20286statements.  Whereas a newline that is preceded by a backslash becomes
20287part of the shell statement according to POSIX, but gets replaced,
20288together with the backslash that precedes it, by a space in GNU
20289@command{make} 3.80 and older.  So, how can a newline be used in a string
20290literal?
20291
20292The trick is to set up a shell variable that contains a newline:
20293
20294@example
20295nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20296@end example
20297
20298For example, in order to create a multiline @samp{sed} expression that
20299inserts a blank line after every line of a file, this code can be used:
20300
20301@example
20302nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20303sed -e "s/\$$/\\$$@{nl@}/" < input > output
20304@end example
20305
20306@node Comments in Make Macros
20307@section Comments in Make Macros
20308@cindex Comments in @file{Makefile} macros
20309@cindex @file{Makefile} macros and comments
20310
20311Avoid putting comments in macro values as far as possible.  Posix
20312specifies that the text starting from the @samp{#} sign until the end of
20313the line is to be ignored, which has the unfortunate effect of
20314disallowing them even within quotes.  Thus, the following might lead to
20315a syntax error at compile time:
20316
20317@example
20318CPPFLAGS = "-DCOMMENT_CHAR='#'"
20319@end example
20320
20321@noindent
20322as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20323
20324Most @command{make} implementations disregard this and treat single and
20325double quotes specially here.  Also, GNU @command{make} lets you put
20326@samp{#} into a macro value by escaping it with a backslash, i.e.,
20327@samp{\#}.  However, neither of these usages are portable.
20328@xref{Comments in Make Rules}, for a portable alternative.
20329
20330Even without quoting involved, comments can have surprising effects,
20331because the whitespace before them is part of the variable value:
20332
20333@example
20334foo = bar # trailing comment
20335print: ; @@echo "$(foo)."
20336@end example
20337
20338@noindent
20339prints @samp{bar .}, which is usually not intended, and can expose
20340@command{make} bugs as described below.
20341
20342@node Trailing whitespace in Make Macros
20343@section Trailing whitespace in Make Macros
20344@cindex whitespace in @file{Makefile} macros
20345@cindex @file{Makefile} macros and whitespace
20346
20347GNU @command{make} 3.80 mistreats trailing whitespace in macro
20348substitutions and appends another spurious suffix:
20349
20350@example
20351empty =
20352foo = bar $(empty)
20353print: ; @@echo $(foo:=.test)
20354@end example
20355
20356@noindent
20357prints @samp{bar.test .test}.
20358
20359BSD and Solaris @command{make} implementations do not honor trailing
20360whitespace in macro definitions as Posix requires:
20361
20362@example
20363foo = bar # Note the space after "bar".
20364print: ; @@echo $(foo)t
20365@end example
20366
20367@noindent
20368prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20369can use a helper macro as in the previous example.
20370
20371
20372@node Command-line Macros and whitespace
20373@section Command-line Macros and whitespace
20374@cindex whitespace in command-line macros
20375@cindex command-line, macros set on
20376@cindex environment, macros set from
20377
20378Some @command{make} implementations may strip trailing whitespace off
20379of macros set on the command line in addition to leading whitespace.
20380Further, some may strip leading whitespace off of macros set from
20381environment variables:
20382
20383@example
20384$ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20385  foo=' f f ' make -f - bar=' b b '}
20386x f f xb b x  # AIX, BSD, GNU make
20387xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20388x f f xb bx   # Solaris make
20389@end example
20390
20391
20392@node obj/ and Make
20393@section The @file{obj/} Subdirectory and Make
20394@cindex @file{obj/}, subdirectory
20395@cindex BSD @command{make} and @file{obj/}
20396
20397Never name one of your subdirectories @file{obj/} if you don't like
20398surprises.
20399
20400If an @file{obj/} directory exists, BSD @command{make} enters it
20401before reading the makefile.  Hence the makefile in the
20402current directory is not read.
20403
20404@example
20405$ @kbd{cat Makefile}
20406all:
20407        echo Hello
20408$ @kbd{cat obj/Makefile}
20409all:
20410        echo World
20411$ @kbd{make}      # GNU make
20412echo Hello
20413Hello
20414$ @kbd{pmake}     # BSD make
20415echo World
20416World
20417@end example
20418
20419@node make -k Status
20420@section Exit Status of @code{make -k}
20421@cindex @code{make -k}
20422
20423Do not rely on the exit status of @code{make -k}.  Some implementations
20424reflect whether they encountered an error in their exit status; other
20425implementations always succeed.
20426
20427@example
20428$ @kbd{cat Makefile}
20429all:
20430        false
20431$ @kbd{make -k; echo exit status: $?}    # GNU make
20432false
20433make: *** [all] Error 1
20434exit status: 2
20435$ @kbd{pmake -k; echo exit status: $?}   # BSD make
20436false
20437*** Error code 1 (continuing)
20438exit status: 0
20439@end example
20440
20441@node VPATH and Make
20442@section @code{VPATH} and Make
20443@cindex @code{VPATH}
20444
20445Posix does not specify the semantics of @code{VPATH}.  Typically,
20446@command{make} supports @code{VPATH}, but its implementation is not
20447consistent.
20448
20449Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20450portable to recent-enough popular implementations of @command{make}, but
20451to keep the resulting makefiles portable, a package's makefile
20452prototypes must take the following issues into account.  These issues
20453are complicated and are often poorly understood, and installers who use
20454@code{VPATH} should expect to find many bugs in this area.  If you use
20455@code{VPATH}, the simplest way to avoid these portability bugs is to
20456stick with GNU @command{make}, since it is the most
20457commonly-used @command{make} among Autoconf users.
20458
20459Here are some known issues with some @code{VPATH}
20460implementations.
20461
20462@menu
20463* Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20464* VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20465* $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20466* Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20467* Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20468* Make Target Lookup::          More details about @code{VPATH} lookup
20469@end menu
20470
20471@node Variables listed in VPATH
20472@subsection Variables listed in @code{VPATH}
20473@cindex @code{VPATH} and variables
20474@cindex variables and @code{VPATH}
20475
20476Do not set @code{VPATH} to the value of another variable, for example
20477@samp{VPATH = $(srcdir)}, because some ancient versions of
20478@command{make} do not do variable substitutions on the value of
20479@code{VPATH}.  For example, use this
20480
20481@example
20482srcdir = @@srcdir@@
20483VPATH = @@srcdir@@
20484@end example
20485
20486@noindent
20487rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20488Automake, there is no need to set this yourself.
20489
20490@node VPATH and Double-colon
20491@subsection @code{VPATH} and Double-colon Rules
20492@cindex @code{VPATH} and double-colon rules
20493@cindex double-colon rules and @code{VPATH}
20494
20495With ancient versions of Sun @command{make},
20496any assignment to @code{VPATH} causes @command{make} to execute only
20497the first set of double-colon rules.
20498However, this problem is no longer of practical concern.
20499
20500@node $< in Explicit Rules
20501@subsection @code{$<} Not Supported in Explicit Rules
20502@cindex explicit rules, @code{$<}, and @code{VPATH}
20503@cindex @code{$<}, explicit rules, and @code{VPATH}
20504@cindex @code{VPATH}, explicit rules, and @code{$<}
20505
20506Using @code{$<} in explicit rules is not portable.
20507The prerequisite file must be named explicitly in the rule.  If you want
20508to find the prerequisite via a @code{VPATH} search, you have to code the
20509whole thing manually.  @xref{Build Directories}.
20510
20511@node Automatic Rule Rewriting
20512@subsection Automatic Rule Rewriting
20513@cindex @code{VPATH} and automatic rule rewriting
20514@cindex automatic rule rewriting and @code{VPATH}
20515
20516Some @command{make} implementations, such as Solaris and Tru64,
20517search for prerequisites in @code{VPATH} and
20518then rewrite each occurrence as a plain word in the rule.
20519For instance:
20520
20521@example
20522# This isn't portable to GNU make.
20523VPATH = ../pkg/src
20524f.c: if.c
20525        cp if.c f.c
20526@end example
20527
20528@noindent
20529executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20530found in @file{../pkg/src}.
20531
20532However, this rule leads to real problems in practice.  For example, if
20533the source directory contains an ordinary file named @file{test} that is
20534used in a dependency, Solaris @command{make} rewrites commands like
20535@samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20536@dots{}}, which is typically undesirable.  In fact, @command{make} is
20537completely unaware of shell syntax used in the rules, so the VPATH
20538rewrite can potentially apply to @emph{any} whitespace-separated word
20539in a rule, including shell variables, functions, and keywords.
20540
20541@example
20542$ @kbd{mkdir build}
20543$ @kbd{cd build}
20544$ @kbd{cat > Makefile <<'END'}
20545VPATH = ..
20546all: arg func for echo
20547        func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20548        func "hello world"
20549END
20550$ @kbd{touch ../arg ../func ../for ../echo}
20551$ @kbd{make}
20552../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20553../func "hello world"
20554sh: syntax error at line 1: `do' unexpected
20555*** Error code 2
20556@end example
20557
20558@noindent
20559To avoid this problem, portable makefiles should never mention a source
20560file or dependency whose name is that of a shell keyword like @file{for}
20561or @file{until}, a shell command like @command{cat} or @command{gcc} or
20562@command{test}, or a shell function or variable used in the corresponding
20563@command{Makefile} recipe.
20564
20565Because of these problems GNU @command{make} and many other @command{make}
20566implementations do not rewrite commands, so portable makefiles should
20567search @code{VPATH} manually.  It is tempting to write this:
20568
20569@smallexample
20570# This isn't portable to Solaris make.
20571VPATH = ../pkg/src
20572f.c: if.c
20573        cp `test -f if.c || echo $(VPATH)/`if.c f.c
20574@end smallexample
20575
20576@noindent
20577However, the ``prerequisite rewriting'' still applies here.  So if
20578@file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20579execute
20580
20581@smallexample
20582cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20583@end smallexample
20584
20585@noindent
20586which reduces to
20587
20588@example
20589cp if.c f.c
20590@end example
20591
20592@noindent
20593and thus fails.  Oops.
20594
20595A simple workaround, and good practice anyway, is to use @samp{$?} and
20596@samp{$@@} when possible:
20597
20598@smallexample
20599VPATH = ../pkg/src
20600f.c: if.c
20601        cp $? $@@
20602@end smallexample
20603
20604@noindent
20605but this does not generalize well to commands with multiple
20606prerequisites.  A more general workaround is to rewrite the rule so that
20607the prerequisite @file{if.c} never appears as a plain word.  For
20608example, these three rules would be safe, assuming @file{if.c} is in
20609@file{../pkg/src} and the other files are in the working directory:
20610
20611@smallexample
20612VPATH = ../pkg/src
20613f.c: if.c f1.c
20614        cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20615g.c: if.c g1.c
20616        cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20617h.c: if.c h1.c
20618        cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20619@end smallexample
20620
20621Things get worse when your prerequisites are in a macro.
20622
20623@example
20624VPATH = ../pkg/src
20625HEADERS = f.h g.h h.h
20626install-HEADERS: $(HEADERS)
20627        for i in $(HEADERS); do \
20628          $(INSTALL) -m 644 \
20629            `test -f $$i || echo $(VPATH)/`$$i \
20630            $(DESTDIR)$(includedir)/$$i; \
20631@c $$ restore font-lock
20632        done
20633@end example
20634
20635The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20636i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20637where @code{f.h} and @code{g.h} are plain words and are hence
20638subject to @code{VPATH} adjustments.
20639
20640If the three files are in @file{../pkg/src}, the rule is run as:
20641
20642@example
20643for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20644  install -m 644 \
20645     `test -f $i || echo ../pkg/src/`$i \
20646     /usr/local/include/$i; \
20647done
20648@end example
20649
20650where the two first @command{install} calls fail.  For instance,
20651consider the @code{f.h} installation:
20652
20653@example
20654install -m 644 \
20655  `test -f ../pkg/src/f.h || \
20656    echo ../pkg/src/ \
20657  `../pkg/src/f.h \
20658  /usr/local/include/../pkg/src/f.h;
20659@end example
20660
20661@noindent
20662It reduces to:
20663
20664@example
20665install -m 644 \
20666  ../pkg/src/f.h \
20667  /usr/local/include/../pkg/src/f.h;
20668@end example
20669
20670Note that the manual @code{VPATH} search did not cause any problems here;
20671however this command installs @file{f.h} in an incorrect directory.
20672
20673Trying to quote @code{$(HEADERS)} in some way, as we did for
20674@code{foo.c} a few makefiles ago, does not help:
20675
20676@example
20677install-HEADERS: $(HEADERS)
20678        headers='$(HEADERS)'; \
20679        for i in $$headers; do \
20680          $(INSTALL) -m 644 \
20681            `test -f $$i || echo $(VPATH)/`$$i \
20682            $(DESTDIR)$(includedir)/$$i; \
20683        done
20684@end example
20685
20686Now, @code{headers='$(HEADERS)'} macro-expands to:
20687
20688@example
20689headers='f.h g.h h.h'
20690@end example
20691
20692@noindent
20693but @code{g.h} is still a plain word.  (As an aside, the idiom
20694@code{headers='$(HEADERS)'; for i in $$headers;} is a good
20695idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20696syntax error on @code{for i in;}.)
20697
20698One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20699
20700@example
20701VPATH = ../pkg/src
20702HEADERS = f.h g.h h.h
20703install-HEADERS: $(HEADERS)
20704        headers='$(HEADERS)'; \
20705        for i in $$headers; do \
20706          i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20707          $(INSTALL) -m 644 \
20708            `test -f $$i || echo $(VPATH)/`$$i \
20709            $(DESTDIR)$(includedir)/$$i; \
20710@c $$ restore font-lock
20711        done
20712@end example
20713
20714Automake does something similar.  However the above hack works only if
20715the files listed in @code{HEADERS} are in the current directory or a
20716subdirectory; they should not be in an enclosing directory.  If we had
20717@code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20718build with Tru64 @command{make}.  The reason is that not only does
20719Tru64 @command{make} rewrite dependencies, but it also simplifies
20720them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20721@code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20722a leading @file{../pkg/src/} component.
20723
20724The following example makes the behavior of Tru64 @command{make}
20725more apparent.
20726
20727@example
20728$ @kbd{cat Makefile}
20729VPATH = sub
20730all: ../foo
20731        echo ../foo
20732$ @kbd{ls}
20733Makefile foo
20734$ @kbd{make}
20735echo foo
20736foo
20737@end example
20738
20739@noindent
20740Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20741@command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20742directory does not even exist, this just means that the simplification
20743occurred before the file was checked for.)
20744
20745For the record here is how SunOS 4 @command{make} behaves on this
20746example.
20747
20748@smallexample
20749$ @kbd{make}
20750make: Fatal error: Don't know how to make target `../foo'
20751$ @kbd{mkdir sub}
20752$ @kbd{make}
20753echo sub/../foo
20754sub/../foo
20755@end smallexample
20756
20757
20758@node Tru64 Directory Magic
20759@subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20760@cindex @code{VPATH} and prerequisite directories
20761@cindex prerequisite directories and @code{VPATH}
20762
20763When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20764@command{make} creates it in the current directory.
20765
20766@example
20767$ @kbd{mkdir -p foo/bar build}
20768$ @kbd{cd build}
20769$ @kbd{cat >Makefile <<END
20770VPATH = ..
20771all: foo/bar
20772END}
20773$ @kbd{make}
20774mkdir foo
20775mkdir foo/bar
20776@end example
20777
20778This can yield unexpected results if a rule uses a manual @code{VPATH}
20779search as presented before.
20780
20781@example
20782VPATH = ..
20783all : foo/bar
20784        command `test -d foo/bar || echo ../`foo/bar
20785@end example
20786
20787The above @command{command} is run on the empty @file{foo/bar}
20788directory that was created in the current directory.
20789
20790@node Make Target Lookup
20791@subsection Make Target Lookup
20792@cindex @code{VPATH}, resolving target pathnames
20793
20794GNU @command{make} uses a complex algorithm to decide when it
20795should use files found via a @code{VPATH} search.  @xref{Search
20796Algorithm, , How Directory Searches are Performed, make, The GNU Make
20797Manual}.
20798
20799If a target needs to be rebuilt, GNU @command{make} discards the
20800file name found during the @code{VPATH} search for this target, and
20801builds the file locally using the file name given in the makefile.
20802If a target does not need to be rebuilt, GNU @command{make} uses the
20803file name found during the @code{VPATH} search.
20804
20805Other @command{make} implementations, like NetBSD @command{make}, are
20806easier to describe: the file name found during the @code{VPATH} search
20807is used whether the target needs to be rebuilt or not.  Therefore
20808new files are created locally, but existing files are updated at their
20809@code{VPATH} location.
20810
20811OpenBSD and FreeBSD @command{make}, however,
20812never perform a
20813@code{VPATH} search for a dependency that has an explicit rule.
20814This is extremely annoying.
20815
20816When attempting a @code{VPATH} build for an autoconfiscated package
20817(e.g., @code{mkdir build && cd build && ../configure}), this means
20818GNU
20819@command{make} builds everything locally in the @file{build}
20820directory, while BSD @command{make} builds new files locally and
20821updates existing files in the source directory.
20822
20823@example
20824$ @kbd{cat Makefile}
20825VPATH = ..
20826all: foo.x bar.x
20827foo.x bar.x: newer.x
20828        @@echo Building $@@
20829$ @kbd{touch ../bar.x}
20830$ @kbd{touch ../newer.x}
20831$ @kbd{make}        # GNU make
20832Building foo.x
20833Building bar.x
20834$ @kbd{pmake}       # NetBSD make
20835Building foo.x
20836Building ../bar.x
20837$ @kbd{fmake}       # FreeBSD make, OpenBSD make
20838Building foo.x
20839Building bar.x
20840$ @kbd{tmake}       # Tru64 make
20841Building foo.x
20842Building bar.x
20843$ @kbd{touch ../bar.x}
20844$ @kbd{make}        # GNU make
20845Building foo.x
20846$ @kbd{pmake}       # NetBSD make
20847Building foo.x
20848$ @kbd{fmake}       # FreeBSD make, OpenBSD make
20849Building foo.x
20850Building bar.x
20851$ @kbd{tmake}       # Tru64 make
20852Building foo.x
20853Building bar.x
20854@end example
20855
20856Note how NetBSD @command{make} updates @file{../bar.x} in its
20857VPATH location, and how FreeBSD, OpenBSD, and Tru64
20858@command{make} always
20859update @file{bar.x}, even when @file{../bar.x} is up to date.
20860
20861Another point worth mentioning is that once GNU @command{make} has
20862decided to ignore a @code{VPATH} file name (e.g., it ignored
20863@file{../bar.x} in the above example) it continues to ignore it when
20864the target occurs as a prerequisite of another rule.
20865
20866The following example shows that GNU @command{make} does not look up
20867@file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20868because it ignored the @code{VPATH} result of @file{bar.x} while running
20869the @code{bar.x: newer.x} rule.
20870
20871@example
20872$ @kbd{cat Makefile}
20873VPATH = ..
20874all: bar.y
20875bar.x: newer.x
20876        @@echo Building $@@
20877.SUFFIXES: .x .y
20878.x.y:
20879        cp $< $@@
20880$ @kbd{touch ../bar.x}
20881$ @kbd{touch ../newer.x}
20882$ @kbd{make}        # GNU make
20883Building bar.x
20884cp bar.x bar.y
20885cp: cannot stat `bar.x': No such file or directory
20886make: *** [bar.y] Error 1
20887$ @kbd{pmake}       # NetBSD make
20888Building ../bar.x
20889cp ../bar.x bar.y
20890$ @kbd{rm bar.y}
20891$ @kbd{fmake}       # FreeBSD make, OpenBSD make
20892echo Building bar.x
20893cp bar.x bar.y
20894cp: cannot stat `bar.x': No such file or directory
20895*** Error code 1
20896$ @kbd{tmake}       # Tru64 make
20897Building bar.x
20898cp: bar.x: No such file or directory
20899*** Exit 1
20900@end example
20901
20902Note that if you drop away the command from the @code{bar.x: newer.x}
20903rule, GNU @command{make} magically starts to work: it
20904knows that @code{bar.x} hasn't been updated, therefore it doesn't
20905discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
20906uses.  Tru64 also works, but FreeBSD and OpenBSD
20907still don't.
20908
20909@example
20910$ @kbd{cat Makefile}
20911VPATH = ..
20912all: bar.y
20913bar.x: newer.x
20914.SUFFIXES: .x .y
20915.x.y:
20916        cp $< $@@
20917$ @kbd{touch ../bar.x}
20918$ @kbd{touch ../newer.x}
20919$ @kbd{make}        # GNU make
20920cp ../bar.x bar.y
20921$ @kbd{rm bar.y}
20922$ @kbd{pmake}       # NetBSD make
20923cp ../bar.x bar.y
20924$ @kbd{rm bar.y}
20925$ @kbd{fmake}       # FreeBSD make, OpenBSD make
20926cp bar.x bar.y
20927cp: cannot stat `bar.x': No such file or directory
20928*** Error code 1
20929$ @kbd{tmake}       # Tru64 make
20930cp ../bar.x bar.y
20931@end example
20932
20933It seems the sole solution that would please every @command{make}
20934implementation is to never rely on @code{VPATH} searches for targets.
20935In other words, @code{VPATH} should be reserved to unbuilt sources.
20936
20937
20938@node Single Suffix Rules
20939@section Single Suffix Rules and Separated Dependencies
20940@cindex Single Suffix Inference Rule
20941@cindex Rule, Single Suffix Inference
20942A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
20943(@samp{.from.to:}), but which @emph{destination} suffix is empty
20944(@samp{.from:}).
20945
20946@cindex Separated Dependencies
20947@dfn{Separated dependencies} simply refers to listing the prerequisite
20948of a target, without defining a rule.  Usually one can list on the one
20949hand side, the rules, and on the other hand side, the dependencies.
20950
20951Solaris @command{make} does not support separated dependencies for
20952targets defined by single suffix rules:
20953
20954@example
20955$ @kbd{cat Makefile}
20956.SUFFIXES: .in
20957foo: foo.in
20958.in:
20959        cp $< $@@
20960$ @kbd{touch foo.in}
20961$ @kbd{make}
20962$ @kbd{ls}
20963Makefile  foo.in
20964@end example
20965
20966@noindent
20967while GNU Make does:
20968
20969@example
20970$ @kbd{gmake}
20971cp foo.in foo
20972$ @kbd{ls}
20973Makefile  foo       foo.in
20974@end example
20975
20976Note it works without the @samp{foo: foo.in} dependency.
20977
20978@example
20979$ @kbd{cat Makefile}
20980.SUFFIXES: .in
20981.in:
20982        cp $< $@@
20983$ @kbd{make foo}
20984cp foo.in foo
20985@end example
20986
20987@noindent
20988and it works with double suffix inference rules:
20989
20990@example
20991$ @kbd{cat Makefile}
20992foo.out: foo.in
20993.SUFFIXES: .in .out
20994.in.out:
20995        cp $< $@@
20996$ @kbd{make}
20997cp foo.in foo.out
20998@end example
20999
21000As a result, in such a case, you have to write target rules.
21001
21002@node Timestamps and Make
21003@section Timestamp Resolution and Make
21004@cindex timestamp resolution
21005Traditionally, file timestamps had 1-second resolution, and
21006@command{make} used those timestamps to determine whether one file was
21007newer than the other.  However, many modern file systems have
21008timestamps with 1-nanosecond resolution.  Some @command{make}
21009implementations look at the entire timestamp; others ignore the
21010fractional part, which can lead to incorrect results.  Normally this
21011is not a problem, but in some extreme cases you may need to use tricks
21012like @samp{sleep 1} to work around timestamp truncation bugs.
21013
21014Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21015file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21016Tools}).  Hence you should be wary of rules like this:
21017
21018@example
21019dest: src
21020        cp -p src dest
21021@end example
21022
21023as @file{dest} often appears to be older than @file{src} after the
21024timestamp is truncated, and this can cause @command{make} to do
21025needless rework the next time it is invoked.  To work around this
21026problem, you can use a timestamp file, e.g.:
21027
21028@example
21029dest-stamp: src
21030        cp -p src dest
21031        date >dest-stamp
21032@end example
21033
21034Apart from timestamp resolution, there are also differences in handling
21035equal timestamps.  HP-UX @command{make} updates targets if it has the
21036same time stamp as one of its prerequisites, in violation of Posix rules.
21037
21038This can cause spurious rebuilds for repeated runs of @command{make}.
21039This in turn can cause @command{make} to fail if it tries to rebuild
21040generated files in a possibly read-only source tree with tools not
21041present on the end-user machine.  Use GNU @command{make} instead.
21042
21043
21044
21045@c ======================================== Portable C and C++ Programming
21046
21047@node Portable C and C++
21048@chapter Portable C and C++ Programming
21049@cindex Portable C and C++ programming
21050
21051C and C++ programs often use low-level features of the underlying
21052system, and therefore are often more difficult to make portable to other
21053platforms.
21054
21055Several standards have been developed to help make your programs more
21056portable.  If you write programs with these standards in mind, you can
21057have greater confidence that your programs work on a wide variety
21058of systems.
21059@ifhtml
21060@uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21061Standards Supported by GCC}
21062@end ifhtml
21063@ifnothtml
21064@xref{Standards, , Language Standards Supported by
21065GCC, gcc, Using the GNU Compiler Collection
21066(GCC)},
21067@end ifnothtml
21068for a list of C-related standards.  Many programs also assume the
21069@uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
21070
21071Some old code is written to be portable to K&R C, which predates any C
21072standard.  K&R C compilers are no longer of practical interest, though,
21073and the rest of section assumes at least C89, the first C standard.
21074
21075Program portability is a huge topic, and this section can only briefly
21076introduce common pitfalls.  @xref{System Portability, , Portability
21077between System Types, standards, The GNU Coding Standards}, for
21078more information.
21079
21080@menu
21081* Varieties of Unportability::  How to make your programs unportable
21082* Integer Overflow::            When integers get too large
21083* Preprocessor Arithmetic::     @code{#if} expression problems
21084* Null Pointers::               Properties of null pointers
21085* Buffer Overruns::             Subscript errors and the like
21086* Volatile Objects::            @code{volatile} and signals
21087* Floating Point Portability::  Portable floating-point arithmetic
21088* Exiting Portably::            Exiting and the exit status
21089@end menu
21090
21091@node Varieties of Unportability
21092@section Varieties of Unportability
21093@cindex portability
21094
21095Autoconf tests and ordinary programs often need to test what is allowed
21096on a system, and therefore they may need to deliberately exceed the
21097boundaries of what the standards allow, if only to see whether an
21098optional feature is present.  When you write such a program, you should
21099keep in mind the difference between constraints, unspecified behavior,
21100and undefined behavior.
21101
21102In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21103example constraint is that C programs must not declare a bit-field with
21104negative width.  Tests can therefore reliably assume that programs with
21105negative-width bit-fields are rejected by a compiler that conforms
21106to the standard.
21107
21108@dfn{Unspecified behavior} is valid behavior, where the standard allows
21109multiple possibilities.  For example, the order of evaluation of
21110function arguments is unspecified.  Some unspecified behavior is
21111@dfn{implementation-defined}, i.e., documented by the implementation,
21112but since Autoconf tests cannot read the documentation they cannot
21113distinguish between implementation-defined and other unspecified
21114behavior.  It is common for Autoconf tests to probe implementations to
21115determine otherwise-unspecified behavior.
21116
21117@dfn{Undefined behavior} is invalid behavior, where the standard allows
21118the implementation to do anything it pleases.  For example,
21119dereferencing a null pointer leads to undefined behavior.  If possible,
21120test programs should avoid undefined behavior, since a program with
21121undefined behavior might succeed on a test that should fail.
21122
21123The above rules apply to programs that are intended to conform to the
21124standard.  However, strictly-conforming programs are quite rare, since
21125the standards are so limiting.  A major goal of Autoconf is to support
21126programs that use implementation features not described by the standard,
21127and it is fairly common for test programs to violate the above rules, if
21128the programs work well enough in practice.
21129
21130@node Integer Overflow
21131@section Integer Overflow
21132@cindex integer overflow
21133@cindex overflow, signed integer
21134@cindex signed integer overflow
21135@cindex wraparound arithmetic
21136
21137In practice many portable C programs assume that signed integer overflow wraps
21138around reliably using two's complement arithmetic.  Yet the C standard
21139says that program behavior is undefined on overflow, and in a few cases
21140C programs do not work on some modern implementations because their
21141overflows do not wrap around as their authors expected.  Conversely, in
21142signed integer remainder, the C standard requires overflow
21143behavior that is commonly not implemented.
21144
21145@menu
21146* Integer Overflow Basics::     Why integer overflow is a problem
21147* Signed Overflow Examples::    Examples of code assuming wraparound
21148* Optimization and Wraparound::  Optimizations that break uses of wraparound
21149* Signed Overflow Advice::      Practical advice for signed overflow issues
21150* Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21151@end menu
21152
21153@node Integer Overflow Basics
21154@subsection Basics of Integer Overflow
21155@cindex integer overflow
21156@cindex overflow, signed integer
21157@cindex signed integer overflow
21158@cindex wraparound arithmetic
21159
21160In languages like C, unsigned integer overflow reliably wraps around;
21161e.g., @code{UINT_MAX + 1} yields zero.
21162This is guaranteed by the C standard and is
21163portable in practice, unless you specify aggressive,
21164nonstandard optimization options
21165suitable only for special applications.
21166
21167In contrast, the C standard says that signed integer overflow leads to
21168undefined behavior where a program can do anything, including dumping
21169core or overrunning a buffer.  The misbehavior can even precede the
21170overflow.  Such an overflow can occur during addition, subtraction,
21171multiplication, division, and left shift.
21172
21173Despite this requirement of the standard, many C programs and Autoconf
21174tests assume that signed integer overflow silently wraps around modulo a
21175power of two, using two's complement arithmetic, so long as you cast the
21176resulting value to a signed integer type or store it into a signed
21177integer variable.  If you use conservative optimization flags, such
21178programs are generally portable to the vast majority of modern
21179platforms, with a few exceptions discussed later.
21180
21181For historical reasons the C standard also allows implementations with
21182ones' complement or signed magnitude arithmetic, but it is safe to
21183assume two's complement nowadays.
21184
21185Also, overflow can occur when converting an out-of-range value to a
21186signed integer type.  Here a standard implementation must define what
21187happens, but this might include raising an exception.  In practice all
21188known implementations support silent wraparound in this case, so you need
21189not worry about other possibilities.
21190
21191@node Signed Overflow Examples
21192@subsection Examples of Code Assuming Wraparound Overflow
21193@cindex integer overflow
21194@cindex overflow, signed integer
21195@cindex signed integer overflow
21196@cindex wraparound arithmetic
21197
21198There has long been a tension between what the C standard requires for
21199signed integer overflow, and what C programs commonly assume.  The
21200standard allows aggressive optimizations based on assumptions that
21201overflow never occurs, but many practical C programs rely on overflow
21202wrapping around.  These programs do not conform to the standard, but
21203they commonly work in practice because compiler writers are
21204understandably reluctant to implement optimizations that would break
21205many programs, unless perhaps a user specifies aggressive optimization.
21206
21207The C Standard says that if a program has signed integer overflow its
21208behavior is undefined, and the undefined behavior can even precede the
21209overflow.  To take an extreme example:
21210
21211@c Inspired by Robert Dewar's example in
21212@c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21213@example
21214if (password == expected_password)
21215  allow_superuser_privileges ();
21216else if (counter++ == INT_MAX)
21217  abort ();
21218else
21219  printf ("%d password mismatches\n", counter);
21220@end example
21221
21222@noindent
21223If the @code{int} variable @code{counter} equals @code{INT_MAX},
21224@code{counter++} must overflow and the behavior is undefined, so the C
21225standard allows the compiler to optimize away the test against
21226@code{INT_MAX} and the @code{abort} call.
21227Worse, if an earlier bug in the program lets the compiler deduce that
21228@code{counter == INT_MAX} or that @code{counter} previously overflowed,
21229the C standard allows the compiler to optimize away the password test
21230and generate code that allows superuser privileges unconditionally.
21231
21232Despite this requirement by the standard, it has long been common for C
21233code to assume wraparound arithmetic after signed overflow, and all
21234known practical C implementations support some C idioms that assume
21235wraparound signed arithmetic, even if the idioms do not conform
21236strictly to the standard.  If your code looks like the following
21237examples it will almost surely work with real-world compilers.
21238
21239Here is an example derived from the 7th Edition Unix implementation of
21240@code{atoi} (1979-01-10):
21241
21242@example
21243char *p;
21244int f, n;
21245@dots{}
21246while (*p >= '0' && *p <= '9')
21247  n = n * 10 + *p++ - '0';
21248return (f ? -n : n);
21249@end example
21250
21251@noindent
21252Even if the input string is in range, on most modern machines this has
21253signed overflow when computing the most negative integer (the @code{-n}
21254overflows) or a value near an extreme integer (the first @code{+}
21255overflows).
21256
21257Here is another example, derived from the 7th Edition implementation of
21258@code{rand} (1979-01-10).  Here the programmer expects both
21259multiplication and addition to wrap on overflow:
21260
21261@example
21262static long int randx = 1;
21263@dots{}
21264randx = randx * 1103515245 + 12345;
21265return (randx >> 16) & 077777;
21266@end example
21267
21268In the following example, derived from the GNU C Library 2.5
21269implementation of @code{mktime} (2006-09-09), the code assumes
21270wraparound arithmetic in @code{+} to detect signed overflow:
21271
21272@example
21273time_t t, t1, t2;
21274int sec_requested, sec_adjustment;
21275@dots{}
21276t1 = t + sec_requested;
21277t2 = t1 + sec_adjustment;
21278if (((t1 < t) != (sec_requested < 0))
21279    | ((t2 < t1) != (sec_adjustment < 0)))
21280  return -1;
21281@end example
21282
21283If your code looks like these examples, it is probably safe even though
21284it does not strictly conform to the C standard.  This might lead one to
21285believe that one can generally assume wraparound on overflow, but that
21286is not always true, as can be seen in the next section.
21287
21288@node Optimization and Wraparound
21289@subsection Optimizations That Break Wraparound Arithmetic
21290@cindex loop induction
21291
21292Compilers sometimes generate code that is incompatible with wraparound
21293integer arithmetic.  A simple example is an algebraic simplification: a
21294compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21295because it assumes that @code{i * 2000} does not overflow.  The
21296translation is not equivalent to the original when overflow occurs:
21297e.g., in the typical case of 32-bit signed two's complement wraparound
21298@code{int}, if @code{i} has type @code{int} and value @code{1073742},
21299the original expression returns @minus{}2147483 but the optimized
21300version returns the mathematically correct value 2147484.
21301
21302More subtly, loop induction optimizations often exploit the undefined
21303behavior of signed overflow.  Consider the following contrived function
21304@code{sumc}:
21305
21306@example
21307int
21308sumc (int lo, int hi)
21309@{
21310  int sum = 0;
21311  int i;
21312  for (i = lo; i <= hi; i++)
21313    sum ^= i * 53;
21314  return sum;
21315@}
21316@end example
21317
21318@noindent
21319To avoid multiplying by 53 each time through the loop, an optimizing
21320compiler might internally transform @code{sumc} to the equivalent of the
21321following:
21322
21323@example
21324int
21325transformed_sumc (int lo, int hi)
21326@{
21327  int sum = 0;
21328  int hic = hi * 53;
21329  int ic;
21330  for (ic = lo * 53; ic <= hic; ic += 53)
21331    sum ^= ic;
21332  return sum;
21333@}
21334@end example
21335
21336@noindent
21337This transformation is allowed by the C standard, but it is invalid for
21338wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21339overflow in computing expressions like @code{hi * 53} can cause the
21340expression @code{i <= hi} to yield a different value from the
21341transformed expression @code{ic <= hic}.
21342
21343For this reason, compilers that use loop induction and similar
21344techniques often do not support reliable wraparound arithmetic when a
21345loop induction variable like @code{ic} is involved.  Since loop
21346induction variables are generated by the compiler, and are not visible
21347in the source code, it is not always trivial to say whether the problem
21348affects your code.
21349
21350Hardly any code actually depends on wraparound arithmetic in cases like
21351these, so in practice these loop induction optimizations are almost
21352always useful.  However, edge cases in this area can cause problems.
21353For example:
21354
21355@example
21356int j;
21357for (j = 1; 0 < j; j *= 2)
21358  test (j);
21359@end example
21360
21361@noindent
21362Here, the loop attempts to iterate through all powers of 2 that
21363@code{int} can represent, but the C standard allows a compiler to
21364optimize away the comparison and generate an infinite loop,
21365under the argument that behavior is undefined on overflow.  As of this
21366writing this optimization is not done by any production version of
21367GCC with @option{-O2}, but it might be performed by other
21368compilers, or by more aggressive GCC optimization options,
21369and the GCC developers have not decided whether it will
21370continue to work with GCC and @option{-O2}.
21371
21372@node Signed Overflow Advice
21373@subsection Practical Advice for Signed Overflow Issues
21374@cindex integer overflow
21375@cindex overflow, signed integer
21376@cindex signed integer overflow
21377@cindex wraparound arithmetic
21378
21379Ideally the safest approach is to avoid signed integer overflow
21380entirely.  For example, instead of multiplying two signed integers, you
21381can convert them to unsigned integers, multiply the unsigned values,
21382then test whether the result is in signed range.
21383
21384Rewriting code in this way will be inconvenient, though, particularly if
21385the signed values might be negative.  Also, it may hurt
21386performance.  Using unsigned arithmetic to check for overflow is
21387particularly painful to do portably and efficiently when dealing with an
21388integer type like @code{uid_t} whose width and signedness vary from
21389platform to platform.
21390
21391Furthermore, many C applications pervasively assume wraparound behavior
21392and typically it is not easy to find and remove all these assumptions.
21393Hence it is often useful to maintain nonstandard code that assumes
21394wraparound on overflow, instead of rewriting the code.  The rest of this
21395section attempts to give practical advice for this situation.
21396
21397If your code wants to detect signed integer overflow in @code{sum = a +
21398b}, it is generally safe to use an expression like @code{(sum < a) != (b
21399< 0)}.
21400
21401If your code uses a signed loop index, make sure that the index cannot
21402overflow, along with all signed expressions derived from the index.
21403Here is a contrived example of problematic code with two instances of
21404overflow.
21405
21406@example
21407for (i = INT_MAX - 10; i <= INT_MAX; i++)
21408  if (i + 1 < 0)
21409    @{
21410      report_overflow ();
21411      break;
21412    @}
21413@end example
21414
21415@noindent
21416Because of the two overflows, a compiler might optimize away or
21417transform the two comparisons in a way that is incompatible with the
21418wraparound assumption.
21419
21420If your code uses an expression like @code{(i * 2000) / 1000} and you
21421actually want the multiplication to wrap around on overflow, use
21422unsigned arithmetic
21423to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21424
21425If your code assumes wraparound behavior and you want to insulate it
21426against any GCC optimizations that would fail to support that
21427behavior, you should use GCC's @option{-fwrapv} option, which
21428causes signed overflow to wrap around reliably (except for division and
21429remainder, as discussed in the next section).
21430
21431If you need to port to platforms where signed integer overflow does not
21432reliably wrap around (e.g., due to hardware overflow checking, or to
21433highly aggressive optimizations), you should consider debugging with
21434GCC's @option{-ftrapv} option, which causes signed overflow to
21435raise an exception.
21436
21437@node Signed Integer Division
21438@subsection Signed Integer Division and Integer Overflow
21439@cindex division, integer
21440
21441Overflow in signed
21442integer division is not always harmless: for example, on CPUs of the
21443i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21444which by default terminates the program.  Worse, taking the remainder
21445of these two values typically yields the same signal on these CPUs,
21446even though the C standard requires @code{INT_MIN % -1} to yield zero
21447because the expression does not overflow.
21448
21449@node Preprocessor Arithmetic
21450@section Preprocessor Arithmetic
21451@cindex preprocessor arithmetic
21452
21453In C99, preprocessor arithmetic, used for @code{#if} expressions, must
21454be evaluated as if all signed values are of type @code{intmax_t} and all
21455unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21456this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21457LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21458@code{long long int}.  Also, some older preprocessors mishandle
21459constants ending in @code{LL}.  To work around these problems, you can
21460compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21461@code{configure}-time rather than at @code{#if}-time.
21462
21463@node Null Pointers
21464@section Properties of Null Pointers
21465@cindex null pointers
21466
21467Most modern hosts reliably fail when you attempt to dereference a null
21468pointer.
21469
21470On almost all modern hosts, null pointers use an all-bits-zero internal
21471representation, so you can reliably use @code{memset} with 0 to set all
21472the pointers in an array to null values.
21473
21474If @code{p} is a null pointer to an object type, the C expression
21475@code{p + 0} always evaluates to @code{p} on modern hosts, even though
21476the standard says that it has undefined behavior.
21477
21478@node Buffer Overruns
21479@section Buffer Overruns and Subscript Errors
21480@cindex buffer overruns
21481
21482Buffer overruns and subscript errors are the most common dangerous
21483errors in C programs.  They result in undefined behavior because storing
21484outside an array typically modifies storage that is used by some other
21485object, and most modern systems lack runtime checks to catch these
21486errors.  Programs should not rely on buffer overruns being caught.
21487
21488There is one exception to the usual rule that a portable program cannot
21489address outside an array.  In C, it is valid to compute the address just
21490past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21491so long as you do not dereference the resulting pointer.  But it is not
21492valid to compute the address just before an object, e.g., @code{&a[-1]};
21493nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21494most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21495reliable in general, and it is usually easy enough to avoid the
21496potential portability problem, e.g., by allocating an extra unused array
21497element at the start or end.
21498
21499@uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21500GCC
21501users might also consider using the @option{-fmudflap} option to catch
21502overruns.
21503
21504Buffer overruns are usually caused by off-by-one errors, but there are
21505more subtle ways to get them.
21506
21507Using @code{int} values to index into an array or compute array sizes
21508causes problems on typical 64-bit hosts where an array index might
21509be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21510problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21511are signed, and are wide enough in practice.
21512
21513If you add or multiply two numbers to calculate an array size, e.g.,
21514@code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21515multiplication overflows.
21516
21517Many implementations of the @code{alloca} function silently misbehave
21518and can generate buffer overflows if given sizes that are too large.
21519The size limits are implementation dependent, but are at least 4000
21520bytes on all platforms that we know about.
21521
21522The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21523@code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21524portable code should not use them unless the inputs are known to be
21525within certain limits.  The time-related functions can overflow their
21526buffers if given timestamps out of range (e.g., a year less than -999
21527or greater than 9999).  Time-related buffer overflows cannot happen with
21528recent-enough versions of the GNU C library, but are possible
21529with other
21530implementations.  The @code{gets} function is the worst, since it almost
21531invariably overflows its buffer when presented with an input line larger
21532than the buffer.
21533
21534@node Volatile Objects
21535@section Volatile Objects
21536@cindex volatile objects
21537
21538The keyword @code{volatile} is often misunderstood in portable code.
21539Its use inhibits some memory-access optimizations, but programmers often
21540wish that it had a different meaning than it actually does.
21541
21542@code{volatile} was designed for code that accesses special objects like
21543memory-mapped device registers whose contents spontaneously change.
21544Such code is inherently low-level, and it is difficult to specify
21545portably what @code{volatile} means in these cases.  The C standard
21546says, ``What constitutes an access to an object that has
21547volatile-qualified type is implementation-defined,'' so in theory each
21548implementation is supposed to fill in the gap by documenting what
21549@code{volatile} means for that implementation.  In practice, though,
21550this documentation is usually absent or incomplete.
21551
21552One area of confusion is the distinction between objects defined with
21553volatile types, and volatile lvalues.  From the C standard's point of
21554view, an object defined with a volatile type has externally visible
21555behavior.  You can think of such objects as having little oscilloscope
21556probes attached to them, so that the user can observe some properties of
21557accesses to them, just as the user can observe data written to output
21558files.  However, the standard does not make it clear whether users can
21559observe accesses by volatile lvalues to ordinary objects.  For example:
21560
21561@example
21562/* Declare and access a volatile object.
21563   Accesses to X are "visible" to users.  */
21564static int volatile x;
21565x = 1;
21566
21567/* Access two ordinary objects via a volatile lvalue.
21568   It's not clear whether accesses to *P are "visible".  */
21569int y;
21570int *z = malloc (sizeof (int));
21571int volatile *p;
21572p = &y;
21573*p = 1;
21574p = z;
21575*p = 1;
21576@end example
21577
21578Programmers often wish that @code{volatile} meant ``Perform the memory
21579access here and now, without merging several memory accesses, without
21580changing the memory word size, and without reordering.''  But the C
21581standard does not require this.  For objects defined with a volatile
21582type, accesses must be done before the next sequence point; but
21583otherwise merging, reordering, and word-size change is allowed.  Worse,
21584it is not clear from the standard whether volatile lvalues provide more
21585guarantees in general than nonvolatile lvalues, if the underlying
21586objects are ordinary.
21587
21588Even when accessing objects defined with a volatile type,
21589the C standard allows only
21590extremely limited signal handlers: the behavior is undefined if a signal
21591handler reads any nonlocal object, or writes to any nonlocal object
21592whose type is not @code{sig_atomic_t volatile}, or calls any standard
21593library function other than @code{abort}, @code{signal}, and (if C99)
21594@code{_Exit}.  Hence C compilers need not worry about a signal handler
21595disturbing ordinary computation, unless the computation accesses a
21596@code{sig_atomic_t volatile} lvalue that is not a local variable.
21597(There is an obscure exception for accesses via a pointer to a volatile
21598character, since it may point into part of a @code{sig_atomic_t
21599volatile} object.)  Posix
21600adds to the list of library functions callable from a portable signal
21601handler, but otherwise is like the C standard in this area.
21602
21603Some C implementations allow memory-access optimizations within each
21604translation unit, such that actual behavior agrees with the behavior
21605required by the standard only when calling a function in some other
21606translation unit, and a signal handler acts like it was called from a
21607different translation unit.  The C standard hints that in these
21608implementations, objects referred to by signal handlers ``would require
21609explicit specification of @code{volatile} storage, as well as other
21610implementation-defined restrictions.''  But unfortunately even for this
21611special case these other restrictions are often not documented well.
21612@xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21613GNU Compiler Collection (GCC)}, for some
21614restrictions imposed by GCC.  @xref{Defining Handlers, ,
21615Defining Signal Handlers, libc, The GNU C Library}, for some
21616restrictions imposed by the GNU C library.  Restrictions
21617differ on other platforms.
21618
21619If possible, it is best to use a signal handler that fits within the
21620limits imposed by the C and Posix standards.
21621
21622If this is not practical, you can try the following rules of thumb.  A
21623signal handler should access only volatile lvalues, preferably lvalues
21624that refer to objects defined with a volatile type, and should not
21625assume that the accessed objects have an internally consistent state
21626if they are larger than a machine word.  Furthermore, installers
21627should employ compilers and compiler options that are commonly used
21628for building operating system kernels, because kernels often need more
21629from @code{volatile} than the C Standard requires, and installers who
21630compile an application in a similar environment can sometimes benefit
21631from the extra constraints imposed by kernels on compilers.
21632Admittedly we are handwaving somewhat here, as there are few
21633guarantees in this area; the rules of thumb may help to fix some bugs
21634but there is a good chance that they will not fix them all.
21635
21636For @code{volatile}, C++ has the same problems that C does.
21637Multithreaded applications have even more problems with @code{volatile},
21638but they are beyond the scope of this section.
21639
21640The bottom line is that using @code{volatile} typically hurts
21641performance but should not hurt correctness.  In some cases its use
21642does help correctness, but these cases are often so poorly understood
21643that all too often adding @code{volatile} to a data structure merely
21644alleviates some symptoms of a bug while not fixing the bug in general.
21645
21646@node Floating Point Portability
21647@section Floating Point Portability
21648@cindex floating point
21649
21650Almost all modern systems use IEEE-754 floating point, and it is safe to
21651assume IEEE-754 in most portable code these days.  For more information,
21652please see David Goldberg's classic paper
21653@uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21654Scientist Should Know About Floating-Point Arithmetic}.
21655
21656@node Exiting Portably
21657@section Exiting Portably
21658@cindex exiting portably
21659
21660A C or C++ program can exit with status @var{N} by returning
21661@var{N} from the @code{main} function.  Portable programs are supposed
21662to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21663status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21664fail by exiting with status 1, and test programs that assume Posix can
21665fail by exiting with status values from 1 through 255.  Programs on
21666SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21667status when @code{main} returned nonzero, but ancient systems like these
21668are no longer of practical concern.
21669
21670A program can also exit with status @var{N} by passing @var{N} to the
21671@code{exit} function, and a program can fail by calling the @code{abort}
21672function.  If a program is specialized to just some platforms, it can fail
21673by calling functions specific to those platforms, e.g., @code{_exit}
21674(Posix) and @code{_Exit} (C99).  However, like other functions, an exit
21675function should be declared, typically by including a header.  For
21676example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21677either directly or via the default includes (@pxref{Default Includes}).
21678
21679A program can fail due to undefined behavior such as dereferencing a null
21680pointer, but this is not recommended as undefined behavior allows an
21681implementation to do whatever it pleases and this includes exiting
21682successfully.
21683
21684
21685@c ================================================== Manual Configuration
21686
21687@node Manual Configuration
21688@chapter Manual Configuration
21689
21690A few kinds of features can't be guessed automatically by running test
21691programs.  For example, the details of the object-file format, or
21692special options that need to be passed to the compiler or linker.  You
21693can check for such features using ad-hoc means, such as having
21694@command{configure} check the output of the @code{uname} program, or
21695looking for libraries that are unique to particular systems.  However,
21696Autoconf provides a uniform method for handling unguessable features.
21697
21698@menu
21699* Specifying Target Triplets::  Specifying target triplets
21700* Canonicalizing::              Getting the canonical system type
21701* Using System Type::           What to do with the system type
21702@end menu
21703
21704@node Specifying Target Triplets
21705@section Specifying target triplets
21706@cindex System type
21707@cindex Target triplet
21708@c This node used to be named Specifying Names.  The @anchor allows old
21709@c links to still work.
21710@anchor{Specifying Names}
21711
21712Autoconf-generated
21713@command{configure} scripts can make decisions based on a canonical name
21714for the system type, or @dfn{target triplet}, which has the form:
21715@samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21716@samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21717
21718@command{configure} can usually guess the canonical name for the type of
21719system it's running on.  To do so it runs a script called
21720@command{config.guess}, which infers the name using the @code{uname}
21721command or symbols predefined by the C preprocessor.
21722
21723Alternately, the user can specify the system type with command line
21724arguments to @command{configure} (@pxref{System Type}.  Doing so is
21725necessary when
21726cross-compiling.  In the most complex case of cross-compiling, three
21727system types are involved.  The options to specify them are:
21728
21729@table @option
21730@item --build=@var{build-type}
21731the type of system on which the package is being configured and
21732compiled.  It defaults to the result of running @command{config.guess}.
21733Specifying a @var{build-type} that differs from @var{host-type} enables
21734cross-compilation mode.
21735
21736@item --host=@var{host-type}
21737the type of system on which the package runs.  By default it is the
21738same as the build machine.  Specifying a @var{host-type} that differs
21739from @var{build-type}, when @var{build-type} was also explicitly
21740specified, enables cross-compilation mode.
21741
21742@item --target=@var{target-type}
21743the type of system for which any compiler tools in the package
21744produce code (rarely needed).  By default, it is the same as host.
21745@end table
21746
21747If you mean to override the result of @command{config.guess}, use
21748@option{--build}, not @option{--host}, since the latter enables
21749cross-compilation.  For historical reasons,
21750whenever you specify @option{--host},
21751be sure to specify @option{--build} too; this will be fixed in the
21752future.  So, to enter cross-compilation mode, use a command like this
21753
21754@example
21755./configure --build=i686-pc-linux-gnu --host=m68k-coff
21756@end example
21757
21758@noindent
21759Note that if you do not specify @option{--host}, @command{configure}
21760fails if it can't run the code generated by the specified compiler.  For
21761example, configuring as follows fails:
21762
21763@example
21764./configure CC=m68k-coff-gcc
21765@end example
21766
21767When cross-compiling, @command{configure} will warn about any tools
21768(compilers, linkers, assemblers) whose name is not prefixed with the
21769host type.  This is an aid to users performing cross-compilation.
21770Continuing the example above, if a cross-compiler named @command{cc} is
21771used with a native @command{pkg-config}, then libraries found by
21772@command{pkg-config} will likely cause subtle build failures; but using
21773the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21774avoids any confusion.  Avoiding the warning is as simple as creating the
21775correct symlinks naming the cross tools.
21776
21777@cindex @command{config.sub}
21778@command{configure} recognizes short aliases for many system types; for
21779example, @samp{decstation} can be used instead of
21780@samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21781@command{config.sub} to canonicalize system type aliases.
21782
21783This section deliberately omits the description of the obsolete
21784interface; see @ref{Hosts and Cross-Compilation}.
21785
21786
21787@node Canonicalizing
21788@section Getting the Canonical System Type
21789@cindex System type
21790@cindex Canonical system type
21791
21792The following macros make the system type available to @command{configure}
21793scripts.
21794
21795@ovindex build_alias
21796@ovindex host_alias
21797@ovindex target_alias
21798
21799The variables @samp{build_alias}, @samp{host_alias}, and
21800@samp{target_alias} are always exactly the arguments of @option{--build},
21801@option{--host}, and @option{--target}; in particular, they are left empty
21802if the user did not use them, even if the corresponding
21803@code{AC_CANONICAL} macro was run.  Any configure script may use these
21804variables anywhere.  These are the variables that should be used when in
21805interaction with the user.
21806
21807If you need to recognize some special environments based on their system
21808type, run the following macros to get canonical system names.  These
21809variables are not set before the macro call.
21810
21811If you use these macros, you must distribute @command{config.guess} and
21812@command{config.sub} along with your source code.  @xref{Output}, for
21813information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21814to control in which directory @command{configure} looks for those scripts.
21815
21816
21817@defmac AC_CANONICAL_BUILD
21818@acindex{CANONICAL_BUILD}
21819@ovindex build
21820@ovindex build_cpu
21821@ovindex build_vendor
21822@ovindex build_os
21823Compute the canonical build-system type variable, @code{build}, and its
21824three individual parts @code{build_cpu}, @code{build_vendor}, and
21825@code{build_os}.
21826
21827If @option{--build} was specified, then @code{build} is the
21828canonicalization of @code{build_alias} by @command{config.sub},
21829otherwise it is determined by the shell script @command{config.guess}.
21830@end defmac
21831
21832@defmac AC_CANONICAL_HOST
21833@acindex{CANONICAL_HOST}
21834@ovindex host
21835@ovindex host_cpu
21836@ovindex host_vendor
21837@ovindex host_os
21838Compute the canonical host-system type variable, @code{host}, and its
21839three individual parts @code{host_cpu}, @code{host_vendor}, and
21840@code{host_os}.
21841
21842If @option{--host} was specified, then @code{host} is the
21843canonicalization of @code{host_alias} by @command{config.sub},
21844otherwise it defaults to @code{build}.
21845@end defmac
21846
21847@defmac AC_CANONICAL_TARGET
21848@acindex{CANONICAL_TARGET}
21849@ovindex target
21850@ovindex target_cpu
21851@ovindex target_vendor
21852@ovindex target_os
21853Compute the canonical target-system type variable, @code{target}, and its
21854three individual parts @code{target_cpu}, @code{target_vendor}, and
21855@code{target_os}.
21856
21857If @option{--target} was specified, then @code{target} is the
21858canonicalization of @code{target_alias} by @command{config.sub},
21859otherwise it defaults to @code{host}.
21860@end defmac
21861
21862Note that there can be artifacts due to the backward compatibility
21863code.  @xref{Hosts and Cross-Compilation}, for more.
21864
21865@node Using System Type
21866@section Using the System Type
21867
21868In @file{configure.ac} the system type is generally used by one or more
21869@code{case} statements to select system-specifics.  Shell wildcards can
21870be used to match a group of system types.
21871
21872For example, an extra assembler code object file could be chosen, giving
21873access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
21874following would be used in a makefile to add the object to a
21875program or library.
21876
21877@example
21878AS_CASE([$host],
21879  [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
21880  [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
21881  [CYCLE_OBJ=""]
21882)
21883AC_SUBST([CYCLE_OBJ])
21884@end example
21885
21886@code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
21887to select variant source files, for example optimized code for some
21888CPUs.  The configured CPU type doesn't always indicate exact CPU types,
21889so some runtime capability checks may be necessary too.
21890
21891@example
21892case $host in
21893  alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
21894  powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
21895  *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
21896esac
21897@end example
21898
21899The host system type can also be used to find cross-compilation tools
21900with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
21901
21902The above examples all show @samp{$host}, since this is where the code
21903is going to run.  Only rarely is it necessary to test @samp{$build}
21904(which is where the build is being done).
21905
21906Whenever you're tempted to use @samp{$host} it's worth considering
21907whether some sort of probe would be better.  New system types come along
21908periodically or previously missing features are added.  Well-written
21909probes can adapt themselves to such things, but hard-coded lists of
21910names can't.  Here are some guidelines,
21911
21912@itemize @bullet
21913@item
21914Availability of libraries and library functions should always be checked
21915by probing.
21916@item
21917Variant behavior of system calls is best identified with runtime tests
21918if possible, but bug workarounds or obscure difficulties might have to
21919be driven from @samp{$host}.
21920@item
21921Assembler code is inevitably highly CPU-specific and is best selected
21922according to @samp{$host_cpu}.
21923@item
21924Assembler variations like underscore prefix on globals or ELF versus
21925COFF type directives are however best determined by probing, perhaps
21926even examining the compiler output.
21927@end itemize
21928
21929@samp{$target} is for use by a package creating a compiler or similar.
21930For ordinary packages it's meaningless and should not be used.  It
21931indicates what the created compiler should generate code for, if it can
21932cross-compile.  @samp{$target} generally selects various hard-coded CPU
21933and system conventions, since usually the compiler or tools under
21934construction themselves determine how the target works.
21935
21936
21937@c ===================================================== Site Configuration.
21938
21939@node Site Configuration
21940@chapter Site Configuration
21941
21942@command{configure} scripts support several kinds of local configuration
21943decisions.  There are ways for users to specify where external software
21944packages are, include or exclude optional features, install programs
21945under modified names, and set default values for @command{configure}
21946options.
21947
21948@menu
21949* Help Formatting::             Customizing @samp{configure --help}
21950* External Software::           Working with other optional software
21951* Package Options::             Selecting optional features
21952* Pretty Help Strings::         Formatting help string
21953* Option Checking::             Controlling checking of @command{configure} options
21954* Site Details::                Configuring site details
21955* Transforming Names::          Changing program names when installing
21956* Site Defaults::               Giving @command{configure} local defaults
21957@end menu
21958
21959@node Help Formatting
21960@section Controlling Help Output
21961
21962Users consult @samp{configure --help} to learn of configuration
21963decisions specific to your package.  By default, @command{configure}
21964breaks this output into sections for each type of option; within each
21965section, help strings appear in the order @file{configure.ac} defines
21966them:
21967
21968@example
21969Optional Features:
21970  @dots{}
21971  --enable-bar            include bar
21972
21973Optional Packages:
21974  @dots{}
21975  --with-foo              use foo
21976@end example
21977
21978@defmac AC_PRESERVE_HELP_ORDER
21979@acindex{PRESERVE_HELP_ORDER}
21980
21981Request an alternate @option{--help} format, in which options of all
21982types appear together, in the order defined.  Call this macro before any
21983@code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
21984
21985@example
21986Optional Features and Packages:
21987  @dots{}
21988  --enable-bar            include bar
21989  --with-foo              use foo
21990@end example
21991
21992@end defmac
21993
21994@node External Software
21995@section Working With External Software
21996@cindex External software
21997
21998Some packages require, or can optionally use, other software packages
21999that are already installed.  The user can give @command{configure}
22000command line options to specify which such external software to use.
22001The options have one of these forms:
22002
22003@c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22004@c awful.
22005@example
22006--with-@var{package}@r{[}=@var{arg}@r{]}
22007--without-@var{package}
22008@end example
22009
22010For example, @option{--with-gnu-ld} means work with the GNU linker
22011instead of some other linker.  @option{--with-x} means work with The X
22012Window System.
22013
22014The user can give an argument by following the package name with
22015@samp{=} and the argument.  Giving an argument of @samp{no} is for
22016packages that are used by default; it says to @emph{not} use the
22017package.  An argument that is neither @samp{yes} nor @samp{no} could
22018include a name or number of a version of the other package, to specify
22019more precisely which other package this program is supposed to work
22020with.  If no argument is given, it defaults to @samp{yes}.
22021@option{--without-@var{package}} is equivalent to
22022@option{--with-@var{package}=no}.
22023
22024Normally @command{configure} scripts complain about
22025@option{--with-@var{package}} options that they do not support.
22026@xref{Option Checking}, for details, and for how to override the
22027defaults.
22028
22029For each external software package that may be used, @file{configure.ac}
22030should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22031user asked to use it.  Whether each package is used or not by default,
22032and which arguments are valid, is up to you.
22033
22034@anchor{AC_ARG_WITH}
22035@defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22036  @ovar{action-if-given}, @ovar{action-if-not-given})
22037@acindex{ARG_WITH}
22038If the user gave @command{configure} the option @option{--with-@var{package}}
22039or @option{--without-@var{package}}, run shell commands
22040@var{action-if-given}.  If neither option was given, run shell commands
22041@var{action-if-not-given}.  The name @var{package} indicates another
22042software package that this program should work with.  It should consist
22043only of alphanumeric characters, dashes, plus signs, and dots.
22044
22045The option's argument is available to the shell commands
22046@var{action-if-given} in the shell variable @code{withval}, which is
22047actually just the value of the shell variable named
22048@code{with_@var{package}}, with any non-alphanumeric characters in
22049@var{package} changed into @samp{_}.  You may use that variable instead,
22050if you wish.
22051
22052The argument @var{help-string} is a description of the option that
22053looks like this:
22054@example
22055  --with-readline         support fancy command line editing
22056@end example
22057
22058@noindent
22059@var{help-string} may be more than one line long, if more detail is
22060needed.  Just make sure the columns line up in @samp{configure
22061--help}.  Avoid tabs in the help string.  The easiest way to provide the
22062proper leading whitespace is to format your @var{help-string} with the macro
22063@code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22064
22065The following example shows how to use the @code{AC_ARG_WITH} macro in
22066a common situation.  You want to let the user decide whether to enable
22067support for an external library (e.g., the readline library); if the user
22068specified neither @option{--with-readline} nor @option{--without-readline},
22069you want to enable support for readline only if the library is available
22070on the system.
22071
22072@c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22073@example
22074AC_ARG_WITH([readline],
22075  [AS_HELP_STRING([--with-readline],
22076    [support fancy command line editing @@<:@@default=check@@:>@@])],
22077  [],
22078  [with_readline=check])
22079
22080LIBREADLINE=
22081AS_IF([test "x$with_readline" != xno],
22082  [AC_CHECK_LIB([readline], [main],
22083    [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22084     AC_DEFINE([HAVE_LIBREADLINE], [1],
22085               [Define if you have libreadline])
22086    ],
22087    [if test "x$with_readline" != xcheck; then
22088       AC_MSG_FAILURE(
22089         [--with-readline was given, but test for readline failed])
22090     fi
22091    ], -lncurses)])
22092@end example
22093
22094The next example shows how to use @code{AC_ARG_WITH} to give the user the
22095possibility to enable support for the readline library, in case it is still
22096experimental and not well tested, and is therefore disabled by default.
22097
22098@c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22099@example
22100AC_ARG_WITH([readline],
22101  [AS_HELP_STRING([--with-readline],
22102    [enable experimental support for readline])],
22103  [],
22104  [with_readline=no])
22105
22106LIBREADLINE=
22107AS_IF([test "x$with_readline" != xno],
22108  [AC_CHECK_LIB([readline], [main],
22109    [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22110     AC_DEFINE([HAVE_LIBREADLINE], [1],
22111               [Define if you have libreadline])
22112    ],
22113    [AC_MSG_FAILURE(
22114       [--with-readline was given, but test for readline failed])],
22115    [-lncurses])])
22116@end example
22117
22118The last example shows how to use @code{AC_ARG_WITH} to give the user the
22119possibility to disable support for the readline library, given that it is
22120an important feature and that it should be enabled by default.
22121
22122@c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22123@example
22124AC_ARG_WITH([readline],
22125  [AS_HELP_STRING([--without-readline],
22126    [disable support for readline])],
22127  [],
22128  [with_readline=yes])
22129
22130LIBREADLINE=
22131AS_IF([test "x$with_readline" != xno],
22132  [AC_CHECK_LIB([readline], [main],
22133    [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22134     AC_DEFINE([HAVE_LIBREADLINE], [1],
22135               [Define if you have libreadline])
22136    ],
22137    [AC_MSG_FAILURE(
22138       [readline test failed (--without-readline to disable)])],
22139    [-lncurses])])
22140@end example
22141
22142These three examples can be easily adapted to the case where
22143@code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22144@ref{Package Options}).
22145@end defmac
22146
22147@node Package Options
22148@section Choosing Package Options
22149@cindex Package options
22150@cindex Options, package
22151
22152If a software package has optional compile-time features, the user can
22153give @command{configure} command line options to specify whether to
22154compile them.  The options have one of these forms:
22155
22156@c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22157@c awful.
22158@example
22159--enable-@var{feature}@r{[}=@var{arg}@r{]}
22160--disable-@var{feature}
22161@end example
22162
22163These options allow users to choose which optional features to build and
22164install.  @option{--enable-@var{feature}} options should never make a
22165feature behave differently or cause one feature to replace another.
22166They should only cause parts of the program to be built rather than left
22167out.
22168
22169The user can give an argument by following the feature name with
22170@samp{=} and the argument.  Giving an argument of @samp{no} requests
22171that the feature @emph{not} be made available.  A feature with an
22172argument looks like @option{--enable-debug=stabs}.  If no argument is
22173given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22174equivalent to @option{--enable-@var{feature}=no}.
22175
22176Normally @command{configure} scripts complain about
22177@option{--enable-@var{package}} options that they do not support.
22178@xref{Option Checking}, for details, and for how to override the
22179defaults.
22180
22181For each optional feature, @file{configure.ac} should call
22182@code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22183to include it.  Whether each feature is included or not by default, and
22184which arguments are valid, is up to you.
22185
22186@anchor{AC_ARG_ENABLE}
22187@defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22188  @ovar{action-if-given}, @ovar{action-if-not-given})
22189@acindex{ARG_ENABLE}
22190If the user gave @command{configure} the option
22191@option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22192shell commands @var{action-if-given}.  If neither option was given, run
22193shell commands @var{action-if-not-given}.  The name @var{feature}
22194indicates an optional user-level facility.  It should consist only of
22195alphanumeric characters, dashes, plus signs, and dots.
22196
22197The option's argument is available to the shell commands
22198@var{action-if-given} in the shell variable @code{enableval}, which is
22199actually just the value of the shell variable named
22200@code{enable_@var{feature}}, with any non-alphanumeric characters in
22201@var{feature} changed into @samp{_}.  You may use that variable instead,
22202if you wish.  The @var{help-string} argument is like that of
22203@code{AC_ARG_WITH} (@pxref{External Software}).
22204
22205You should format your @var{help-string} with the macro
22206@code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22207
22208See the examples suggested with the definition of @code{AC_ARG_WITH}
22209(@pxref{External Software}) to get an idea of possible applications of
22210@code{AC_ARG_ENABLE}.
22211@end defmac
22212
22213@node Pretty Help Strings
22214@section Making Your Help Strings Look Pretty
22215@cindex Help strings
22216
22217Properly formatting the @samp{help strings} which are used in
22218@code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22219(@pxref{Package Options}) can be challenging.  Specifically, you want
22220your own @samp{help strings} to line up in the appropriate columns of
22221@samp{configure --help} just like the standard Autoconf @samp{help
22222strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22223
22224@anchor{AS_HELP_STRING}
22225@defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22226  @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22227@asindex{HELP_STRING}
22228
22229Expands into a help string that looks pretty when the user executes
22230@samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22231(@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22232Options}).  The following example makes this clearer.
22233
22234@example
22235AC_ARG_WITH([foo],
22236  [AS_HELP_STRING([--with-foo],
22237     [use foo (default is no)])],
22238  [use_foo=$withval],
22239  [use_foo=no])
22240@end example
22241
22242Then the last few lines of @samp{configure --help} appear like
22243this:
22244
22245@example
22246--enable and --with options recognized:
22247  --with-foo              use foo (default is no)
22248@end example
22249
22250Macro expansion is performed on the first argument.  However, the second
22251argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22252list of text to be reformatted, and is not subject to macro expansion.
22253Since it is not expanded, it should not be double quoted.
22254@xref{Autoconf Language}, for a more detailed explanation.
22255
22256The @code{AS_HELP_STRING} macro is particularly helpful when the
22257@var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22258arguments, as shown in the following example.  Be aware that
22259@var{left-hand-side} may not expand to unbalanced quotes,
22260although quadrigraphs can be used.
22261
22262@example
22263AC_DEFUN([MY_ARG_WITH],
22264  [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22265     [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22266                     [use $1 (default is $2)])],
22267     [use_[]$1=$withval],
22268     [use_[]$1=$2])])
22269MY_ARG_WITH([a_b], [no])
22270@end example
22271@noindent
22272Here, the last few lines of @samp{configure --help} will include:
22273
22274@example
22275--enable and --with options recognized:
22276  --with-a-b              use a_b (default is no)
22277@end example
22278
22279The parameters @var{indent-column} and @var{wrap-column} were introduced
22280in Autoconf 2.62.  Generally, they should not be specified; they exist
22281for fine-tuning of the wrapping.
22282@example
22283AS_HELP_STRING([--option], [description of option])
22284@result{}  --option                description of option
22285AS_HELP_STRING([--option], [description of option], [15], [30])
22286@result{}  --option     description of
22287@result{}               option
22288@end example
22289@end defmac
22290
22291
22292@node Option Checking
22293@section Controlling Checking of @command{configure} Options
22294@cindex Options, Package
22295
22296The @command{configure} script checks its command-line options against a
22297list of known options, like @option{--help} or @option{--config-cache}.
22298An unknown option ordinarily indicates a mistake by the user and
22299@command{configure} halts with an error.  However, by default unknown
22300@option{--with-@var{package}} and @option{--enable-@var{feature}}
22301options elicit only a warning, to support configuring entire source
22302trees.
22303
22304Source trees often contain multiple packages with a top-level
22305@command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22306(@pxref{Subdirectories}).  Because the packages generally support
22307different @option{--with-@var{package}} and
22308@option{--enable-@var{feature}} options, the GNU Coding
22309Standards say they must accept unrecognized options without halting.
22310Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22311automatically disables the warnings.
22312
22313This default behavior may be modified in two ways.  First, the installer
22314can invoke @code{configure --disable-option-checking} to disable
22315these warnings, or invoke @code{configure --enable-option-checking=fatal}
22316options to turn them into fatal errors, respectively.  Second, the
22317maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22318
22319@defmac AC_DISABLE_OPTION_CHECKING
22320@acindex{DISABLE_OPTION_CHECKING}
22321
22322By default, disable warnings related to any unrecognized
22323@option{--with-@var{package}} or @option{--enable-@var{feature}}
22324options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22325
22326The installer can override this behavior by passing
22327@option{--enable-option-checking} (enable warnings) or
22328@option{--enable-option-checking=fatal} (enable errors) to
22329@command{configure}.
22330@end defmac
22331
22332
22333@node Site Details
22334@section Configuring Site Details
22335@cindex Site details
22336
22337Some software packages require complex site-specific information.  Some
22338examples are host names to use for certain services, company names, and
22339email addresses to contact.  Since some configuration scripts generated
22340by Metaconfig ask for such information interactively, people sometimes
22341wonder how to get that information in Autoconf-generated configuration
22342scripts, which aren't interactive.
22343
22344Such site configuration information should be put in a file that is
22345edited @emph{only by users}, not by programs.  The location of the file
22346can either be based on the @code{prefix} variable, or be a standard
22347location such as the user's home directory.  It could even be specified
22348by an environment variable.  The programs should examine that file at
22349runtime, rather than at compile time.  Runtime configuration is more
22350convenient for users and makes the configuration process simpler than
22351getting the information while configuring.  @xref{Directory Variables, ,
22352Variables for Installation Directories, standards, The GNU Coding
22353Standards}, for more information on where to put data files.
22354
22355@node Transforming Names
22356@section Transforming Program Names When Installing
22357@cindex Transforming program names
22358@cindex Program names, transforming
22359
22360Autoconf supports changing the names of programs when installing them.
22361In order to use these transformations, @file{configure.ac} must call the
22362macro @code{AC_ARG_PROGRAM}.
22363
22364@defmac AC_ARG_PROGRAM
22365@acindex{ARG_PROGRAM}
22366@ovindex program_transform_name
22367Place in output variable @code{program_transform_name} a sequence of
22368@code{sed} commands for changing the names of installed programs.
22369
22370If any of the options described below are given to @command{configure},
22371program names are transformed accordingly.  Otherwise, if
22372@code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22373is given, the target type followed by a dash is used as a prefix.
22374Otherwise, no program name transformation is done.
22375@end defmac
22376
22377@menu
22378* Transformation Options::      @command{configure} options to transform names
22379* Transformation Examples::     Sample uses of transforming names
22380* Transformation Rules::        Makefile uses of transforming names
22381@end menu
22382
22383@node Transformation Options
22384@subsection Transformation Options
22385
22386You can specify name transformations by giving @command{configure} these
22387command line options:
22388
22389@table @option
22390@item --program-prefix=@var{prefix}
22391prepend @var{prefix} to the names;
22392
22393@item --program-suffix=@var{suffix}
22394append @var{suffix} to the names;
22395
22396@item --program-transform-name=@var{expression}
22397perform @code{sed} substitution @var{expression} on the names.
22398@end table
22399
22400@node Transformation Examples
22401@subsection Transformation Examples
22402
22403These transformations are useful with programs that can be part of a
22404cross-compilation development environment.  For example, a
22405cross-assembler running on a Sun 4 configured with
22406@option{--target=i960-vxworks} is normally installed as
22407@file{i960-vxworks-as}, rather than @file{as}, which could be confused
22408with a native Sun 4 assembler.
22409
22410You can force a program name to begin with @file{g}, if you don't want
22411GNU programs installed on your system to shadow other programs with
22412the same name.  For example, if you configure GNU @code{diff} with
22413@option{--program-prefix=g}, then when you run @samp{make install} it is
22414installed as @file{/usr/local/bin/gdiff}.
22415
22416As a more sophisticated example, you could use
22417
22418@example
22419--program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22420@end example
22421@noindent
22422
22423to prepend @samp{g} to most of the program names in a source tree,
22424excepting those like @code{gdb} that already have one and those like
22425@code{less} and @code{lesskey} that aren't GNU programs.  (That is
22426assuming that you have a source tree containing those programs that is
22427set up to use this feature.)
22428
22429One way to install multiple versions of some programs simultaneously is
22430to append a version number to the name of one or both.  For example, if
22431you want to keep Autoconf version 1 around for awhile, you can configure
22432Autoconf version 2 using @option{--program-suffix=2} to install the
22433programs as @file{/usr/local/bin/autoconf2},
22434@file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22435that only the binaries are renamed, therefore you'd have problems with
22436the library files which might overlap.
22437
22438@node Transformation Rules
22439@subsection Transformation Rules
22440
22441Here is how to use the variable @code{program_transform_name} in a
22442@file{Makefile.in}:
22443
22444@example
22445PROGRAMS = cp ls rm
22446transform = @@program_transform_name@@
22447install:
22448        for p in $(PROGRAMS); do \
22449          $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22450                                              sed '$(transform)'`; \
22451        done
22452
22453uninstall:
22454        for p in $(PROGRAMS); do \
22455          rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22456@c $$ restore font-lock
22457        done
22458@end example
22459
22460It is guaranteed that @code{program_transform_name} is never empty, and
22461that there are no useless separators.  Therefore you may safely embed
22462@code{program_transform_name} within a sed program using @samp{;}:
22463
22464@example
22465transform = @@program_transform_name@@
22466transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22467@end example
22468
22469Whether to do the transformations on documentation files (Texinfo or
22470@code{man}) is a tricky question; there seems to be no perfect answer,
22471due to the several reasons for name transforming.  Documentation is not
22472usually particular to a specific architecture, and Texinfo files do not
22473conflict with system documentation.  But they might conflict with
22474earlier versions of the same files, and @code{man} pages sometimes do
22475conflict with system documentation.  As a compromise, it is probably
22476best to do name transformations on @code{man} pages but not on Texinfo
22477manuals.
22478
22479@node Site Defaults
22480@section Setting Site Defaults
22481@cindex Site defaults
22482@cindex config.site
22483
22484Autoconf-generated @command{configure} scripts allow your site to provide
22485default values for some configuration values.  You do this by creating
22486site- and system-wide initialization files.
22487
22488@evindex CONFIG_SITE
22489If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22490uses its value as the name of a shell script to read; it is recommended
22491that this be an absolute file name.  Otherwise, it
22492reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22493then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22494settings in machine-specific files override those in machine-independent
22495ones in case of conflict.
22496
22497Site files can be arbitrary shell scripts, but only certain kinds of
22498code are really appropriate to be in them.  Because @command{configure}
22499reads any cache file after it has read any site files, a site file can
22500define a default cache file to be shared between all Autoconf-generated
22501@command{configure} scripts run on that system (@pxref{Cache Files}).  If
22502you set a default cache file in a site file, it is a good idea to also
22503set the output variable @code{CC} in that site file, because the cache
22504file is only valid for a particular compiler, but many systems have
22505several available.
22506
22507You can examine or override the value set by a command line option to
22508@command{configure} in a site file; options set shell variables that have
22509the same names as the options, with any dashes turned into underscores.
22510The exceptions are that @option{--without-} and @option{--disable-} options
22511are like giving the corresponding @option{--with-} or @option{--enable-}
22512option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22513sets the variable @code{cache_file} to the value @samp{localcache};
22514@option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22515@code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22516variable @code{prefix} to the value @samp{/usr}; etc.
22517
22518Site files are also good places to set default values for other output
22519variables, such as @code{CFLAGS}, if you need to give them non-default
22520values: anything you would normally do, repetitively, on the command
22521line.  If you use non-default values for @var{prefix} or
22522@var{exec_prefix} (wherever you locate the site file), you can set them
22523in the site file if you specify it with the @code{CONFIG_SITE}
22524environment variable.
22525
22526You can set some cache values in the site file itself.  Doing this is
22527useful if you are cross-compiling, where it is impossible to check features
22528that require running a test program.  You could ``prime the cache'' by
22529setting those values correctly for that system in
22530@file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22531variables you need to set, see the documentation of the respective
22532Autoconf macro.  If the variables or their semantics are undocumented,
22533you may need to look for shell variables with @samp{_cv_} in their names
22534in the affected @command{configure} scripts, or in the Autoconf M4
22535source code for those macros; but in that case, their name or semantics
22536may change in a future Autoconf version.
22537
22538The cache file is careful to not override any variables set in the site
22539files.  Similarly, you should not override command-line options in the
22540site files.  Your code should check that variables such as @code{prefix}
22541and @code{cache_file} have their default values (as set near the top of
22542@command{configure}) before changing them.
22543
22544Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22545command @samp{configure --prefix=/usr/share/local/gnu} would read this
22546file (if @code{CONFIG_SITE} is not set to a different file).
22547
22548@example
22549# /usr/share/local/gnu/share/config.site for configure
22550#
22551# Change some defaults.
22552test "$prefix" = NONE && prefix=/usr/share/local/gnu
22553test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22554test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22555test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22556
22557# Give Autoconf 2.x generated configure scripts a shared default
22558# cache file for feature test results, architecture-specific.
22559if test "$cache_file" = /dev/null; then
22560  cache_file="$prefix/var/config.cache"
22561  # A cache file is only valid for one C compiler.
22562  CC=gcc
22563fi
22564@end example
22565
22566@c Leave this use of ``File system'' rendered as one word, but
22567@c slightly obfuscated so as not to trigger the syntax-check prohibition.
22568@cindex File@/system Hierarchy Standard
22569@cindex FHS
22570
22571Another use of @file{config.site} is for priming the directory variables
22572@c ``File system'', but slightly obfuscated, as above.
22573in a manner consistent with the File@/system Hierarchy Standard
22574(FHS).  Once the following file is installed at
22575@file{/usr/share/config.site}, a user can execute simply
22576@code{./configure --prefix=/usr} to get all the directories chosen in
22577the locations recommended by FHS.
22578
22579@example
22580# /usr/share/config.site for FHS defaults when installing below /usr,
22581# and the respective settings were not changed on the command line.
22582if test "$prefix" = /usr; then
22583  test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22584  test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22585  test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22586fi
22587@end example
22588
22589@cindex @file{lib64}
22590@cindex 64-bit libraries
22591Likewise, on platforms where 64-bit libraries are built by default, then
22592installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22593it is appropriate to install @file{/usr/local/@/share/config.site}:
22594
22595@example
22596# /usr/local/share/config.site for platforms that prefer
22597# the directory /usr/local/lib64 over /usr/local/lib.
22598test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22599@end example
22600
22601
22602@c ============================================== Running configure Scripts.
22603
22604@node Running configure Scripts
22605@chapter Running @command{configure} Scripts
22606@cindex @command{configure}
22607
22608Below are instructions on how to configure a package that uses a
22609@command{configure} script, suitable for inclusion as an @file{INSTALL}
22610file in the package.  A plain-text version of @file{INSTALL} which you
22611may use comes with Autoconf.
22612
22613@menu
22614* Basic Installation::          Instructions for typical cases
22615* Compilers and Options::       Selecting compilers and optimization
22616* Multiple Architectures::      Compiling for multiple architectures at once
22617* Installation Names::          Installing in different directories
22618* Optional Features::           Selecting optional features
22619* Particular Systems::          Particular systems
22620* System Type::                 Specifying the system type
22621* Sharing Defaults::            Setting site-wide defaults for @command{configure}
22622* Defining Variables::          Specifying the compiler etc.
22623* configure Invocation::        Changing how @command{configure} runs
22624@end menu
22625
22626@set autoconf
22627@include install.texi
22628
22629
22630@c ============================================== config.status Invocation
22631
22632@node config.status Invocation
22633@chapter config.status Invocation
22634@cindex @command{config.status}
22635
22636The @command{configure} script creates a file named @file{config.status},
22637which actually configures, @dfn{instantiates}, the template files.  It
22638also records the configuration options that were specified when the
22639package was last configured in case reconfiguring is needed.
22640
22641Synopsis:
22642@example
22643./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22644@end example
22645
22646It configures each @var{tag}; if none are specified, all the templates
22647are instantiated.  A @var{tag} refers to a file or other tag associated
22648with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22649macro (@pxref{Configuration Actions}).  The files must be specified
22650without their dependencies, as in
22651
22652@example
22653./config.status foobar
22654@end example
22655
22656@noindent
22657not
22658
22659@example
22660./config.status foobar:foo.in:bar.in
22661@end example
22662
22663The supported options are:
22664
22665@table @option
22666@item --help
22667@itemx -h
22668Print a summary of the command line options, the list of the template
22669files, and exit.
22670
22671@item --version
22672@itemx -V
22673Print the version number of Autoconf and the configuration settings,
22674and exit.
22675
22676@item --config
22677Print the configuration settings in reusable way, quoted for the shell,
22678and exit.  For example, for a debugging build that otherwise reuses the
22679configuration from a different build directory @var{build-dir} of a
22680package in @var{src-dir}, you could use the following:
22681
22682@example
22683args=`@var{build-dir}/config.status --config`
22684eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22685@end example
22686
22687@noindent
22688Note that it may be necessary to override a @option{--srcdir} setting
22689that was saved in the configuration, if the arguments are used in a
22690different build directory.
22691
22692@item --silent
22693@itemx --quiet
22694@itemx -q
22695Do not print progress messages.
22696
22697@item --debug
22698@itemx -d
22699Don't remove the temporary files.
22700
22701@item --file=@var{file}[:@var{template}]
22702Require that @var{file} be instantiated as if
22703@samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22704@var{file} and @var{template} may be @samp{-} in which case the standard
22705output and/or standard input, respectively, is used.  If a
22706@var{template} file name is relative, it is first looked for in the build
22707tree, and then in the source tree.  @xref{Configuration Actions}, for
22708more details.
22709
22710This option and the following ones provide one way for separately
22711distributed packages to share the values computed by @command{configure}.
22712Doing so can be useful if some of the packages need a superset of the
22713features that one of them, perhaps a common library, does.  These
22714options allow a @file{config.status} file to create files other than the
22715ones that its @file{configure.ac} specifies, so it can be used for a
22716different package, or for extracting a subset of values.  For example,
22717
22718@example
22719echo '@@CC@@' | ./config.status --file=-
22720@end example
22721
22722@noindent
22723provides the value of @code{@@CC@@} on standard output.
22724
22725@item --header=@var{file}[:@var{template}]
22726Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22727
22728@item --recheck
22729Ask @file{config.status} to update itself and exit (no instantiation).
22730This option is useful if you change @command{configure}, so that the
22731results of some tests might be different from the previous run.  The
22732@option{--recheck} option reruns @command{configure} with the same arguments
22733you used before, plus the @option{--no-create} option, which prevents
22734@command{configure} from running @file{config.status} and creating
22735@file{Makefile} and other files, and the @option{--no-recursion} option,
22736which prevents @command{configure} from running other @command{configure}
22737scripts in subdirectories.  (This is so other Make rules can
22738run @file{config.status} when it changes; @pxref{Automatic Remaking},
22739for an example).
22740@end table
22741
22742@file{config.status} checks several optional environment variables that
22743can alter its behavior:
22744
22745@anchor{CONFIG_SHELL}
22746@defvar CONFIG_SHELL
22747@evindex CONFIG_SHELL
22748The shell with which to run @command{configure}.  It must be
22749Bourne-compatible, and the absolute name of the shell should be passed.
22750The default is a shell that supports @code{LINENO} if available, and
22751@file{/bin/sh} otherwise.
22752@end defvar
22753
22754@defvar CONFIG_STATUS
22755@evindex CONFIG_STATUS
22756The file name to use for the shell script that records the
22757configuration.  The default is @file{./config.status}.  This variable is
22758useful when one package uses parts of another and the @command{configure}
22759scripts shouldn't be merged because they are maintained separately.
22760@end defvar
22761
22762You can use @file{./config.status} in your makefiles.  For example, in
22763the dependencies given above (@pxref{Automatic Remaking}),
22764@file{config.status} is run twice when @file{configure.ac} has changed.
22765If that bothers you, you can make each run only regenerate the files for
22766that rule:
22767@example
22768@group
22769config.h: stamp-h
22770stamp-h: config.h.in config.status
22771        ./config.status config.h
22772        echo > stamp-h
22773
22774Makefile: Makefile.in config.status
22775        ./config.status Makefile
22776@end group
22777@end example
22778
22779The calling convention of @file{config.status} has changed; see
22780@ref{Obsolete config.status Use}, for details.
22781
22782
22783@c =================================================== Obsolete Constructs
22784
22785@node Obsolete Constructs
22786@chapter Obsolete Constructs
22787@cindex Obsolete constructs
22788
22789Autoconf changes, and throughout the years some constructs have been
22790obsoleted.  Most of the changes involve the macros, but in some cases
22791the tools themselves, or even some concepts, are now considered
22792obsolete.
22793
22794You may completely skip this chapter if you are new to Autoconf.  Its
22795intention is mainly to help maintainers updating their packages by
22796understanding how to move to more modern constructs.
22797
22798@menu
22799* Obsolete config.status Use::  Obsolete convention for @command{config.status}
22800* acconfig Header::             Additional entries in @file{config.h.in}
22801* autoupdate Invocation::       Automatic update of @file{configure.ac}
22802* Obsolete Macros::             Backward compatibility macros
22803* Autoconf 1::                  Tips for upgrading your files
22804* Autoconf 2.13::               Some fresher tips
22805@end menu
22806
22807@node Obsolete config.status Use
22808@section Obsolete @file{config.status} Invocation
22809
22810@file{config.status} now supports arguments to specify the files to
22811instantiate; see @ref{config.status Invocation}, for more details.
22812Before, environment variables had to be used.
22813
22814@defvar CONFIG_COMMANDS
22815@evindex CONFIG_COMMANDS
22816The tags of the commands to execute.  The default is the arguments given
22817to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
22818@file{configure.ac}.
22819@end defvar
22820
22821@defvar CONFIG_FILES
22822@evindex CONFIG_FILES
22823The files in which to perform @samp{@@@var{variable}@@} substitutions.
22824The default is the arguments given to @code{AC_OUTPUT} and
22825@code{AC_CONFIG_FILES} in @file{configure.ac}.
22826@end defvar
22827
22828@defvar CONFIG_HEADERS
22829@evindex CONFIG_HEADERS
22830The files in which to substitute C @code{#define} statements.  The
22831default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
22832macro was not called, @file{config.status} ignores this variable.
22833@end defvar
22834
22835@defvar CONFIG_LINKS
22836@evindex CONFIG_LINKS
22837The symbolic links to establish.  The default is the arguments given to
22838@code{AC_CONFIG_LINKS}; if that macro was not called,
22839@file{config.status} ignores this variable.
22840@end defvar
22841
22842In @ref{config.status Invocation}, using this old interface, the example
22843would be:
22844
22845@example
22846@group
22847config.h: stamp-h
22848stamp-h: config.h.in config.status
22849        CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
22850          CONFIG_HEADERS=config.h ./config.status
22851        echo > stamp-h
22852
22853Makefile: Makefile.in config.status
22854        CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
22855          CONFIG_FILES=Makefile ./config.status
22856@end group
22857@end example
22858
22859@noindent
22860(If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
22861no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
22862for @code{CONFIG_COMMANDS}, etc.)
22863
22864
22865@node acconfig Header
22866@section @file{acconfig.h}
22867
22868@cindex @file{acconfig.h}
22869@cindex @file{config.h.top}
22870@cindex @file{config.h.bot}
22871
22872In order to produce @file{config.h.in}, @command{autoheader} needs to
22873build or to find templates for each symbol.  Modern releases of Autoconf
22874use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
22875Macros}), but in older releases a file, @file{acconfig.h}, contained the
22876list of needed templates.  @command{autoheader} copied comments and
22877@code{#define} and @code{#undef} statements from @file{acconfig.h} in
22878the current directory, if present.  This file used to be mandatory if
22879you @code{AC_DEFINE} any additional symbols.
22880
22881Modern releases of Autoconf also provide @code{AH_TOP} and
22882@code{AH_BOTTOM} if you need to prepend/append some information to
22883@file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
22884if @file{./acconfig.h} contains the string @samp{@@TOP@@},
22885@command{autoheader} copies the lines before the line containing
22886@samp{@@TOP@@} into the top of the file that it generates.  Similarly,
22887if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
22888@command{autoheader} copies the lines after that line to the end of the
22889file it generates.  Either or both of those strings may be omitted.  An
22890even older alternate way to produce the same effect in ancient versions
22891of Autoconf is to create the files @file{@var{file}.top} (typically
22892@file{config.h.top}) and/or @file{@var{file}.bot} in the current
22893directory.  If they exist, @command{autoheader} copies them to the
22894beginning and end, respectively, of its output.
22895
22896In former versions of Autoconf, the files used in preparing a software
22897package for distribution were:
22898@example
22899@group
22900configure.ac --.   .------> autoconf* -----> configure
22901               +---+
22902[aclocal.m4] --+   `---.
22903[acsite.m4] ---'       |
22904                       +--> [autoheader*] -> [config.h.in]
22905[acconfig.h] ----.     |
22906                 +-----'
22907[config.h.top] --+
22908[config.h.bot] --'
22909@end group
22910@end example
22911
22912Using only the @code{AH_} macros, @file{configure.ac} should be
22913self-contained, and should not depend upon @file{acconfig.h} etc.
22914
22915
22916@node autoupdate Invocation
22917@section Using @command{autoupdate} to Modernize @file{configure.ac}
22918@cindex @command{autoupdate}
22919
22920The @command{autoupdate} program updates a @file{configure.ac} file that
22921calls Autoconf macros by their old names to use the current macro names.
22922In version 2 of Autoconf, most of the macros were renamed to use a more
22923uniform and descriptive naming scheme.  @xref{Macro Names}, for a
22924description of the new scheme.  Although the old names still work
22925(@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
22926new names), you can make your @file{configure.ac} files more readable
22927and make it easier to use the current Autoconf documentation if you
22928update them to use the new macro names.
22929
22930@evindex SIMPLE_BACKUP_SUFFIX
22931If given no arguments, @command{autoupdate} updates @file{configure.ac},
22932backing up the original version with the suffix @file{~} (or the value
22933of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
22934set).  If you give @command{autoupdate} an argument, it reads that file
22935instead of @file{configure.ac} and writes the updated file to the
22936standard output.
22937
22938@noindent
22939@command{autoupdate} accepts the following options:
22940
22941@table @option
22942@item --help
22943@itemx -h
22944Print a summary of the command line options and exit.
22945
22946@item --version
22947@itemx -V
22948Print the version number of Autoconf and exit.
22949
22950@item --verbose
22951@itemx -v
22952Report processing steps.
22953
22954@item --debug
22955@itemx -d
22956Don't remove the temporary files.
22957
22958@item --force
22959@itemx -f
22960Force the update even if the file has not changed.  Disregard the cache.
22961
22962@item --include=@var{dir}
22963@itemx -I @var{dir}
22964Also look for input files in @var{dir}.  Multiple invocations accumulate.
22965Directories are browsed from last to first.
22966
22967@item --prepend-include=@var{dir}
22968@itemx -B @var{dir}
22969Prepend directory @var{dir} to the search path.  This is used to include
22970the language-specific files before any third-party macros.
22971@end table
22972
22973@node Obsolete Macros
22974@section Obsolete Macros
22975
22976Several macros are obsoleted in Autoconf, for various reasons (typically
22977they failed to quote properly, couldn't be extended for more recent
22978issues, etc.).  They are still supported, but deprecated: their use
22979should be avoided.
22980
22981During the jump from Autoconf version 1 to version 2, most of the
22982macros were renamed to use a more uniform and descriptive naming scheme,
22983but their signature did not change.  @xref{Macro Names}, for a
22984description of the new naming scheme.  Below, if there is just the mapping
22985from old names to new names for these macros, the reader is invited to
22986refer to the definition of the new macro for the signature and the
22987description.
22988
22989@defmac AC_AIX
22990@acindex{AIX}
22991@cvindex _ALL_SOURCE
22992This macro is a platform-specific subset of
22993@code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22994@end defmac
22995
22996@defmac AC_ALLOCA
22997@acindex{ALLOCA}
22998Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
22999@end defmac
23000
23001@defmac AC_ARG_ARRAY
23002@acindex{ARG_ARRAY}
23003Removed because of limited usefulness.
23004@end defmac
23005
23006@defmac AC_C_CROSS
23007@acindex{C_CROSS}
23008This macro is obsolete; it does nothing.
23009@end defmac
23010
23011@defmac AC_C_LONG_DOUBLE
23012@acindex{C_LONG_DOUBLE}
23013@cvindex HAVE_LONG_DOUBLE
23014If the C compiler supports a working @code{long double} type with more
23015range or precision than the @code{double} type, define
23016@code{HAVE_LONG_DOUBLE}.
23017
23018You should use @code{AC_TYPE_LONG_DOUBLE} or
23019@code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23020@end defmac
23021
23022@defmac AC_CANONICAL_SYSTEM
23023@acindex{CANONICAL_SYSTEM}
23024Determine the system type and set output variables to the names of the
23025canonical system types.  @xref{Canonicalizing}, for details about the
23026variables this macro sets.
23027
23028The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23029@code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23030the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23031other macros (@pxref{Canonicalizing}).
23032@end defmac
23033
23034@defmac AC_CHAR_UNSIGNED
23035@acindex{CHAR_UNSIGNED}
23036Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23037@end defmac
23038
23039@defmac AC_CHECK_TYPE (@var{type}, @var{default})
23040@acindex{CHECK_TYPE}
23041Autoconf, up to 2.13, used to provide this version of
23042@code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23043it is a member of the @code{CHECK} clan, it does
23044more than just checking.  Secondly, missing types are defined
23045using @code{#define}, not @code{typedef}, and this can lead to
23046problems in the case of pointer types.
23047
23048This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23049@ref{Generic Types}, for the description of the current macro.
23050
23051If the type @var{type} is not defined, define it to be the C (or C++)
23052builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23053
23054This macro is equivalent to:
23055
23056@example
23057AC_CHECK_TYPE([@var{type}], [],
23058  [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23059     [Define to `@var{default}'
23060      if <sys/types.h> does not define.])])
23061@end example
23062
23063In order to keep backward compatibility, the two versions of
23064@code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23065
23066@enumerate
23067@item
23068If there are three or four arguments, the modern version is used.
23069
23070@item
23071If the second argument appears to be a C or C++ type, then the
23072obsolete version is used.  This happens if the argument is a C or C++
23073@emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23074followed by one of @samp{[(* } and then by a string of zero or more
23075characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23076
23077@item
23078If the second argument is spelled with the alphabet of valid C and C++
23079types, the user is warned and the modern version is used.
23080
23081@item
23082Otherwise, the modern version is used.
23083@end enumerate
23084
23085@noindent
23086You are encouraged either to use a valid builtin type, or to use the
23087equivalent modern code (see above), or better yet, to use
23088@code{AC_CHECK_TYPES} together with
23089
23090@example
23091#ifndef HAVE_LOFF_T
23092typedef loff_t off_t;
23093#endif
23094@end example
23095@end defmac
23096@c end of AC_CHECK_TYPE
23097
23098@defmac AC_CHECKING (@var{feature-description})
23099@acindex{CHECKING}
23100Same as
23101
23102@example
23103AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23104@end example
23105
23106@noindent
23107@xref{AC_MSG_NOTICE}.
23108@end defmac
23109
23110@defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23111  @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23112@acindex{COMPILE_CHECK}
23113This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23114@code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23115addition that it prints @samp{checking for @var{echo-text}} to the
23116standard output first, if @var{echo-text} is non-empty.  Use
23117@code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23118messages (@pxref{Printing Messages}).
23119@end defmac
23120
23121@defmac AC_CONST
23122@acindex{CONST}
23123Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23124@end defmac
23125
23126@defmac AC_CROSS_CHECK
23127@acindex{CROSS_CHECK}
23128Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23129@code{:-)}.
23130@end defmac
23131
23132@defmac AC_CYGWIN
23133@acindex{CYGWIN}
23134@evindex CYGWIN
23135Check for the Cygwin environment in which case the shell variable
23136@code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23137means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23138(@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23139
23140@example
23141AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23142case $host_os in
23143  *cygwin* ) CYGWIN=yes;;
23144         * ) CYGWIN=no;;
23145esac
23146@end example
23147
23148Beware that the variable @env{CYGWIN} has a special meaning when
23149running Cygwin, and should not be changed.  That's yet another reason
23150not to use this macro.
23151@end defmac
23152
23153@defmac AC_DECL_SYS_SIGLIST
23154@acindex{DECL_SYS_SIGLIST}
23155@cvindex SYS_SIGLIST_DECLARED
23156Same as:
23157
23158@example
23159AC_CHECK_DECLS([sys_siglist], [], [],
23160[#include <signal.h>
23161/* NetBSD declares sys_siglist in unistd.h.  */
23162#ifdef HAVE_UNISTD_H
23163# include <unistd.h>
23164#endif
23165])
23166@end example
23167
23168@noindent
23169@xref{AC_CHECK_DECLS}.
23170@end defmac
23171
23172@defmac AC_DECL_YYTEXT
23173@acindex{DECL_YYTEXT}
23174Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23175@end defmac
23176
23177@defmac AC_DIR_HEADER
23178@acindex{DIR_HEADER}
23179@cvindex DIRENT
23180@cvindex SYSNDIR
23181@cvindex SYSDIR
23182@cvindex NDIR
23183Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23184(@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23185(@pxref{AC_HEADER_DIRENT}),
23186but defines a different set of C preprocessor macros to indicate which
23187header file is found:
23188
23189@multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23190@item Header            @tab Old Symbol     @tab New Symbol
23191@item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23192@item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23193@item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23194@item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23195@end multitable
23196@end defmac
23197
23198@defmac AC_DYNIX_SEQ
23199@acindex{DYNIX_SEQ}
23200If on DYNIX/ptx, add @option{-lseq} to output variable
23201@code{LIBS}.  This macro used to be defined as
23202
23203@example
23204AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23205@end example
23206
23207@noindent
23208now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23209@end defmac
23210
23211@defmac AC_EXEEXT
23212@acindex{EXEEXT}
23213@ovindex EXEEXT
23214Defined the output variable @code{EXEEXT} based on the output of the
23215compiler, which is now done automatically.  Typically set to empty
23216string if Posix and @samp{.exe} if a DOS variant.
23217@end defmac
23218
23219@defmac AC_EMXOS2
23220@acindex{EMXOS2}
23221Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23222and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23223check the nature of the host is using @code{AC_CANONICAL_HOST}
23224(@pxref{Canonicalizing}).
23225@end defmac
23226
23227@defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23228  @ovar{action-if-not-given})
23229@acindex{ENABLE}
23230This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23231support providing a help string (@pxref{AC_ARG_ENABLE}).
23232@end defmac
23233
23234@defmac AC_ERROR
23235@acindex{ERROR}
23236Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23237@end defmac
23238
23239@defmac AC_FIND_X
23240@acindex{FIND_X}
23241Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23242@end defmac
23243
23244@defmac AC_FIND_XTRA
23245@acindex{FIND_XTRA}
23246Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23247@end defmac
23248
23249@defmac AC_FOREACH
23250@acindex{FOREACH}
23251Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23252@end defmac
23253
23254@defmac AC_FUNC_CHECK
23255@acindex{FUNC_CHECK}
23256Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23257@end defmac
23258
23259@anchor{AC_FUNC_SETVBUF_REVERSED}
23260@defmac AC_FUNC_SETVBUF_REVERSED
23261@acindex{FUNC_SETVBUF_REVERSED}
23262@cvindex SETVBUF_REVERSED
23263@c @fuindex setvbuf
23264@prindex @code{setvbuf}
23265Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23266the buffering type as its second argument and the buffer pointer as the
23267third, instead of the other way around, and defined
23268@code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23269were those based on SVR2, which became obsolete in 1987, and the macro
23270is no longer needed.
23271@end defmac
23272
23273@defmac AC_FUNC_WAIT3
23274@acindex{FUNC_WAIT3}
23275@cvindex HAVE_WAIT3
23276@c @fuindex wait3
23277@prindex @code{wait3}
23278If @code{wait3} is found and fills in the contents of its third argument
23279(a @samp{struct rusage *}), which HP-UX does not do, define
23280@code{HAVE_WAIT3}.
23281
23282These days portable programs should use @code{waitpid}, not
23283@code{wait3}, as @code{wait3} has been removed from Posix.
23284@end defmac
23285
23286@defmac AC_GCC_TRADITIONAL
23287@acindex{GCC_TRADITIONAL}
23288Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23289@end defmac
23290
23291@defmac AC_GETGROUPS_T
23292@acindex{GETGROUPS_T}
23293Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23294@end defmac
23295
23296@defmac AC_GETLOADAVG
23297@acindex{GETLOADAVG}
23298Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23299@end defmac
23300
23301@defmac AC_GNU_SOURCE
23302@acindex{GNU_SOURCE}
23303@cvindex _GNU_SOURCE
23304This macro is a platform-specific subset of
23305@code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23306@end defmac
23307
23308@defmac AC_HAVE_FUNCS
23309@acindex{HAVE_FUNCS}
23310Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23311@end defmac
23312
23313@defmac AC_HAVE_HEADERS
23314@acindex{HAVE_HEADERS}
23315Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23316@end defmac
23317
23318@defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23319  @ovar{action-if-not-found}, @ovar{other-libraries})
23320@acindex{HAVE_LIBRARY}
23321This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23322@var{function} argument of @code{main}.  In addition, @var{library} can
23323be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23324all of those cases, the compiler is passed @option{-lfoo}.  However,
23325@var{library} cannot be a shell variable; it must be a literal name.
23326@xref{AC_CHECK_LIB}.
23327@end defmac
23328
23329@defmac AC_HAVE_POUNDBANG
23330@acindex{HAVE_POUNDBANG}
23331Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23332@end defmac
23333
23334@defmac AC_HEADER_CHECK
23335@acindex{HEADER_CHECK}
23336Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23337@end defmac
23338
23339@defmac AC_HEADER_EGREP
23340@acindex{HEADER_EGREP}
23341Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23342@end defmac
23343
23344@defmac AC_HELP_STRING
23345@acindex{HELP_STRING}
23346Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23347@end defmac
23348
23349@defmac AC_INIT (@var{unique-file-in-source-dir})
23350@acindex{INIT}
23351Formerly @code{AC_INIT} used to have a single argument, and was
23352equivalent to:
23353
23354@example
23355AC_INIT
23356AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23357@end example
23358See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23359@end defmac
23360
23361@defmac AC_INLINE
23362@acindex{INLINE}
23363Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23364@end defmac
23365
23366@defmac AC_INT_16_BITS
23367@acindex{INT_16_BITS}
23368@cvindex INT_16_BITS
23369If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23370Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23371@end defmac
23372
23373@defmac AC_IRIX_SUN
23374@acindex{IRIX_SUN}
23375If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23376@code{LIBS}.  If you were using it to get @code{getmntent}, use
23377@code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23378of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23379getpwnam)}.  Up to Autoconf 2.13, it used to be
23380
23381@example
23382AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23383@end example
23384
23385@noindent
23386now it is defined as
23387
23388@example
23389AC_FUNC_GETMNTENT
23390AC_CHECK_LIB([sun], [getpwnam])
23391@end example
23392
23393@noindent
23394See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23395@end defmac
23396
23397@defmac AC_ISC_POSIX
23398@acindex{ISC_POSIX}
23399@ovindex LIBS
23400This macro adds @option{-lcposix} to output variable @code{LIBS} if
23401necessary for Posix facilities.  Sun dropped support for the obsolete
23402INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23403need not use this macro.  It is implemented as
23404@code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23405@end defmac
23406
23407@defmac AC_LANG_C
23408@acindex{LANG_C}
23409Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23410@end defmac
23411
23412@defmac AC_LANG_CPLUSPLUS
23413@acindex{LANG_CPLUSPLUS}
23414Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23415@end defmac
23416
23417@defmac AC_LANG_FORTRAN77
23418@acindex{LANG_FORTRAN77}
23419Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23420@end defmac
23421
23422@defmac AC_LANG_RESTORE
23423@acindex{LANG_RESTORE}
23424Select the @var{language} that is saved on the top of the stack, as set
23425by @code{AC_LANG_SAVE}, remove it from the stack, and call
23426@code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23427preferred way to change languages.
23428@end defmac
23429
23430@defmac AC_LANG_SAVE
23431@acindex{LANG_SAVE}
23432Remember the current language (as set by @code{AC_LANG}) on a stack.
23433The current language does not change.  @code{AC_LANG_PUSH} is preferred
23434(@pxref{AC_LANG_PUSH}).
23435@end defmac
23436
23437@defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23438@acindex{LINK_FILES}
23439This is an obsolete version of @code{AC_CONFIG_LINKS}
23440(@pxref{AC_CONFIG_LINKS}.  An updated version of:
23441
23442@example
23443AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23444              host.h            object.h)
23445@end example
23446
23447@noindent
23448is:
23449
23450@example
23451AC_CONFIG_LINKS([host.h:config/$machine.h
23452                object.h:config/$obj_format.h])
23453@end example
23454@end defmac
23455
23456@defmac AC_LN_S
23457@acindex{LN_S}
23458Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23459@end defmac
23460
23461@defmac AC_LONG_64_BITS
23462@acindex{LONG_64_BITS}
23463@cvindex LONG_64_BITS
23464Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23465Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23466(@pxref{AC_CHECK_SIZEOF}).
23467@end defmac
23468
23469@defmac AC_LONG_DOUBLE
23470@acindex{LONG_DOUBLE}
23471If the C compiler supports a working @code{long double} type with more
23472range or precision than the @code{double} type, define
23473@code{HAVE_LONG_DOUBLE}.
23474
23475You should use @code{AC_TYPE_LONG_DOUBLE} or
23476@code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23477@end defmac
23478
23479@defmac AC_LONG_FILE_NAMES
23480@acindex{LONG_FILE_NAMES}
23481Replaced by
23482@example
23483AC_SYS_LONG_FILE_NAMES
23484@end example
23485@noindent
23486@xref{AC_SYS_LONG_FILE_NAMES}.
23487@end defmac
23488
23489@defmac AC_MAJOR_HEADER
23490@acindex{MAJOR_HEADER}
23491Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23492@end defmac
23493
23494@defmac AC_MEMORY_H
23495@acindex{MEMORY_H}
23496@cvindex NEED_MEMORY_H
23497Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23498defined in @file{memory.h}.  Today it is equivalent to
23499@samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23500your code to depend upon
23501@code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
23502Symbols}.
23503@end defmac
23504
23505@defmac AC_MINGW32
23506@acindex{MINGW32}
23507Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23508environment and sets @code{MINGW32}.  Don't use this macro, the
23509dignified means to check the nature of the host is using
23510@code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23511@end defmac
23512
23513@defmac AC_MINIX
23514@acindex{MINIX}
23515@cvindex _MINIX
23516@cvindex _POSIX_SOURCE
23517@cvindex _POSIX_1_SOURCE
23518This macro is a platform-specific subset of
23519@code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23520@end defmac
23521
23522@defmac AC_MINUS_C_MINUS_O
23523@acindex{MINUS_C_MINUS_O}
23524Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23525@end defmac
23526
23527@defmac AC_MMAP
23528@acindex{MMAP}
23529Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23530@end defmac
23531
23532@defmac AC_MODE_T
23533@acindex{MODE_T}
23534Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23535@end defmac
23536
23537@defmac AC_OBJEXT
23538@acindex{OBJEXT}
23539@ovindex OBJEXT
23540Defined the output variable @code{OBJEXT} based on the output of the
23541compiler, after .c files have been excluded.  Typically set to @samp{o}
23542if Posix, @samp{obj} if a DOS variant.
23543Now the compiler checking macros handle
23544this automatically.
23545@end defmac
23546
23547@defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23548@acindex{OBSOLETE}
23549Make M4 print a message to the standard error output warning that
23550@var{this-macro-name} is obsolete, and giving the file and line number
23551where it was called.  @var{this-macro-name} should be the name of the
23552macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23553it is printed at the end of the warning message; for example, it can be
23554a suggestion for what to use instead of @var{this-macro-name}.
23555
23556For instance
23557
23558@example
23559AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23560@end example
23561
23562@noindent
23563You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23564services to the user (@pxref{AU_DEFUN}).
23565@end defmac
23566
23567@defmac AC_OFF_T
23568@acindex{OFF_T}
23569Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23570@end defmac
23571
23572@defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23573@acindex{OUTPUT}
23574The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23575interface is equivalent to:
23576
23577@example
23578@group
23579AC_CONFIG_FILES(@var{file}@dots{})
23580AC_CONFIG_COMMANDS([default],
23581                   @var{extra-cmds}, @var{init-cmds})
23582AC_OUTPUT
23583@end group
23584@end example
23585
23586@noindent
23587See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23588@end defmac
23589
23590@defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23591@acindex{OUTPUT_COMMANDS}
23592Specify additional shell commands to run at the end of
23593@file{config.status}, and shell commands to initialize any variables
23594from @command{configure}.  This macro may be called multiple times.  It is
23595obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23596
23597Here is an unrealistic example:
23598
23599@example
23600fubar=27
23601AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23602                   [fubar=$fubar])
23603AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23604                   [echo init bit])
23605@end example
23606
23607Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23608additional key, an important difference is that
23609@code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23610@code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23611can safely be given macro calls as arguments:
23612
23613@example
23614AC_CONFIG_COMMANDS(foo, [my_FOO()])
23615@end example
23616
23617@noindent
23618Conversely, where one level of quoting was enough for literal strings
23619with @code{AC_OUTPUT_COMMANDS}, you need two with
23620@code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23621
23622@example
23623@group
23624AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23625AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23626@end group
23627@end example
23628@end defmac
23629
23630@defmac AC_PID_T
23631@acindex{PID_T}
23632Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23633@end defmac
23634
23635@defmac AC_PREFIX
23636@acindex{PREFIX}
23637Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23638@end defmac
23639
23640@defmac AC_PROGRAMS_CHECK
23641@acindex{PROGRAMS_CHECK}
23642Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23643@end defmac
23644
23645@defmac AC_PROGRAMS_PATH
23646@acindex{PROGRAMS_PATH}
23647Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23648@end defmac
23649
23650@defmac AC_PROGRAM_CHECK
23651@acindex{PROGRAM_CHECK}
23652Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23653@end defmac
23654
23655@defmac AC_PROGRAM_EGREP
23656@acindex{PROGRAM_EGREP}
23657Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23658@end defmac
23659
23660@defmac AC_PROGRAM_PATH
23661@acindex{PROGRAM_PATH}
23662Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23663@end defmac
23664
23665@defmac AC_REMOTE_TAPE
23666@acindex{REMOTE_TAPE}
23667Removed because of limited usefulness.
23668@end defmac
23669
23670@defmac AC_RESTARTABLE_SYSCALLS
23671@acindex{RESTARTABLE_SYSCALLS}
23672This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23673these days portable programs should use @code{sigaction} with
23674@code{SA_RESTART} if they want restartable system calls.  They should
23675not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23676system call is restartable is a dynamic issue, not a configuration-time
23677issue.
23678@end defmac
23679
23680@defmac AC_RETSIGTYPE
23681@acindex{RETSIGTYPE}
23682Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23683is obsolete when assuming C89 or better.
23684@end defmac
23685
23686@defmac AC_RSH
23687@acindex{RSH}
23688Removed because of limited usefulness.
23689@end defmac
23690
23691@defmac AC_SCO_INTL
23692@acindex{SCO_INTL}
23693@ovindex LIBS
23694If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23695macro used to do this:
23696
23697@example
23698AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23699@end example
23700
23701@noindent
23702Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23703@end defmac
23704
23705@defmac AC_SETVBUF_REVERSED
23706@acindex{SETVBUF_REVERSED}
23707Replaced by
23708@example
23709AC_FUNC_SETVBUF_REVERSED
23710@end example
23711@noindent
23712@xref{AC_FUNC_SETVBUF_REVERSED}.
23713@end defmac
23714
23715@defmac AC_SET_MAKE
23716@acindex{SET_MAKE}
23717Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23718@end defmac
23719
23720@defmac AC_SIZEOF_TYPE
23721@acindex{SIZEOF_TYPE}
23722Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23723@end defmac
23724
23725@defmac AC_SIZE_T
23726@acindex{SIZE_T}
23727Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23728@end defmac
23729
23730@defmac AC_STAT_MACROS_BROKEN
23731@acindex{STAT_MACROS_BROKEN}
23732Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23733@end defmac
23734
23735@defmac AC_STDC_HEADERS
23736@acindex{STDC_HEADERS}
23737Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
23738@end defmac
23739
23740@defmac AC_STRCOLL
23741@acindex{STRCOLL}
23742Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23743@end defmac
23744
23745@defmac AC_STRUCT_ST_BLKSIZE
23746@acindex{STRUCT_ST_BLKSIZE}
23747@cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23748@cvindex HAVE_ST_BLKSIZE
23749If @code{struct stat} contains an @code{st_blksize} member, define
23750@code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23751@code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23752the future.  This macro is obsoleted, and should be replaced by
23753
23754@example
23755AC_CHECK_MEMBERS([struct stat.st_blksize])
23756@end example
23757@noindent
23758@xref{AC_CHECK_MEMBERS}.
23759@end defmac
23760
23761@defmac AC_STRUCT_ST_RDEV
23762@acindex{STRUCT_ST_RDEV}
23763@cvindex HAVE_ST_RDEV
23764@cvindex HAVE_STRUCT_STAT_ST_RDEV
23765If @code{struct stat} contains an @code{st_rdev} member, define
23766@code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23767@code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23768in the future.  Actually, even the new macro is obsolete and should be
23769replaced by:
23770@example
23771AC_CHECK_MEMBERS([struct stat.st_rdev])
23772@end example
23773@noindent
23774@xref{AC_CHECK_MEMBERS}.
23775@end defmac
23776
23777@defmac AC_ST_BLKSIZE
23778@acindex{ST_BLKSIZE}
23779Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23780@end defmac
23781
23782@defmac AC_ST_BLOCKS
23783@acindex{ST_BLOCKS}
23784Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
23785@end defmac
23786
23787@defmac AC_ST_RDEV
23788@acindex{ST_RDEV}
23789Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23790@end defmac
23791
23792@defmac AC_SYS_RESTARTABLE_SYSCALLS
23793@acindex{SYS_RESTARTABLE_SYSCALLS}
23794@cvindex HAVE_RESTARTABLE_SYSCALLS
23795If the system automatically restarts a system call that is interrupted
23796by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
23797not check whether system calls are restarted in general---it checks whether a
23798signal handler installed with @code{signal} (but not @code{sigaction})
23799causes system calls to be restarted.  It does not check whether system calls
23800can be restarted when interrupted by signals that have no handler.
23801
23802These days portable programs should use @code{sigaction} with
23803@code{SA_RESTART} if they want restartable system calls.  They should
23804not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23805system call is restartable is a dynamic issue, not a configuration-time
23806issue.
23807@end defmac
23808
23809@defmac AC_SYS_SIGLIST_DECLARED
23810@acindex{SYS_SIGLIST_DECLARED}
23811This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
23812name is obsolete, as the same functionality is now achieved via
23813@code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
23814@end defmac
23815
23816@defmac AC_TEST_CPP
23817@acindex{TEST_CPP}
23818This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
23819@code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
23820@end defmac
23821
23822@defmac AC_TEST_PROGRAM
23823@acindex{TEST_PROGRAM}
23824This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
23825@code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
23826@end defmac
23827
23828@defmac AC_TIMEZONE
23829@acindex{TIMEZONE}
23830Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
23831@end defmac
23832
23833@defmac AC_TIME_WITH_SYS_TIME
23834@acindex{TIME_WITH_SYS_TIME}
23835Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
23836@end defmac
23837
23838@defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
23839  @ovar{action-if-true}, @ovar{action-if-false})
23840@acindex{TRY_COMPILE}
23841Same as:
23842
23843@example
23844AC_COMPILE_IFELSE(
23845  [AC_LANG_PROGRAM([[@var{includes}]],
23846     [[@var{function-body}]])],
23847  [@var{action-if-true}],
23848  [@var{action-if-false}])
23849@end example
23850
23851@noindent
23852@xref{Running the Compiler}.
23853
23854This macro double quotes both @var{includes} and @var{function-body}.
23855
23856For C and C++, @var{includes} is any @code{#include} statements needed
23857by the code in @var{function-body} (@var{includes} is ignored if
23858the currently selected language is Fortran or Fortran 77).  The compiler
23859and compilation flags are determined by the current language
23860(@pxref{Language Choice}).
23861@end defmac
23862
23863@defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
23864@acindex{TRY_CPP}
23865Same as:
23866
23867@example
23868AC_PREPROC_IFELSE(
23869  [AC_LANG_SOURCE([[@var{input}]])],
23870  [@var{action-if-true}],
23871  [@var{action-if-false}])
23872@end example
23873
23874@noindent
23875@xref{Running the Preprocessor}.
23876
23877This macro double quotes the @var{input}.
23878@end defmac
23879
23880@defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
23881  @ovar{action-if-true}, @ovar{action-if-false})
23882@acindex{TRY_LINK}
23883Same as:
23884
23885@example
23886AC_LINK_IFELSE(
23887  [AC_LANG_PROGRAM([[@var{includes}]],
23888     [[@var{function-body}]])],
23889  [@var{action-if-true}],
23890  [@var{action-if-false}])
23891@end example
23892
23893@noindent
23894@xref{Running the Compiler}.
23895
23896This macro double quotes both @var{includes} and @var{function-body}.
23897
23898Depending on the current language (@pxref{Language Choice}), create a
23899test program to see whether a function whose body consists of
23900@var{function-body} can be compiled and linked.  If the file compiles
23901and links successfully, run shell commands @var{action-if-found},
23902otherwise run @var{action-if-not-found}.
23903
23904This macro double quotes both @var{includes} and @var{function-body}.
23905
23906For C and C++, @var{includes} is any @code{#include} statements needed
23907by the code in @var{function-body} (@var{includes} is ignored if
23908the currently selected language is Fortran or Fortran 77).  The compiler
23909and compilation flags are determined by the current language
23910(@pxref{Language Choice}), and in addition @code{LDFLAGS} and
23911@code{LIBS} are used for linking.
23912@end defmac
23913
23914@defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
23915  @ovar{action-if-not-found})
23916@acindex{TRY_LINK_FUNC}
23917This macro is equivalent to
23918@example
23919AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
23920  [@var{action-if-found}], [@var{action-if-not-found}])
23921@end example
23922@noindent
23923@xref{AC_LINK_IFELSE}.
23924@end defmac
23925
23926@defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
23927  @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
23928@acindex{TRY_RUN}
23929Same as:
23930
23931@example
23932AC_RUN_IFELSE(
23933  [AC_LANG_SOURCE([[@var{program}]])],
23934  [@var{action-if-true}],
23935  [@var{action-if-false}],
23936  [@var{action-if-cross-compiling}])
23937@end example
23938
23939@noindent
23940@xref{Runtime}.
23941@end defmac
23942
23943@anchor{AC_TYPE_SIGNAL}
23944@defmac AC_TYPE_SIGNAL
23945@acindex{TYPE_SIGNAL}
23946@cvindex RETSIGTYPE
23947@hdrindex{signal.h}
23948If @file{signal.h} declares @code{signal} as returning a pointer to a
23949function returning @code{void}, define @code{RETSIGTYPE} to be
23950@code{void}; otherwise, define it to be @code{int}.  These days, it is
23951portable to assume C89, and that signal handlers return @code{void},
23952without needing to use this macro or @code{RETSIGTYPE}.
23953
23954When targeting older K&R C, it is possible to define signal handlers as
23955returning type @code{RETSIGTYPE}, and omit a return statement:
23956
23957@example
23958@group
23959RETSIGTYPE
23960hup_handler ()
23961@{
23962@dots{}
23963@}
23964@end group
23965@end example
23966@end defmac
23967
23968@defmac AC_UID_T
23969@acindex{UID_T}
23970Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23971@end defmac
23972
23973@defmac AC_UNISTD_H
23974@acindex{UNISTD_H}
23975Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
23976@end defmac
23977
23978@defmac AC_USG
23979@acindex{USG}
23980@cvindex USG
23981Define @code{USG} if the BSD string functions are defined in
23982@file{strings.h}.  You should no longer depend upon @code{USG}, but on
23983@code{HAVE_STRING_H}; see @ref{Standard Symbols}.
23984@end defmac
23985
23986@defmac AC_UTIME_NULL
23987@acindex{UTIME_NULL}
23988Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
23989@end defmac
23990
23991@defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
23992@acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
23993If the cache file is inconsistent with the current host, target and
23994build system types, it used to execute @var{cmd} or print a default
23995error message.  This is now handled by default.
23996@end defmac
23997
23998@defmac AC_VERBOSE (@var{result-description})
23999@acindex{VERBOSE}
24000Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24001@end defmac
24002
24003@defmac AC_VFORK
24004@acindex{VFORK}
24005Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24006@end defmac
24007
24008@defmac AC_VPRINTF
24009@acindex{VPRINTF}
24010Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24011@end defmac
24012
24013@defmac AC_WAIT3
24014@acindex{WAIT3}
24015This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24016portable programs should use @code{waitpid}, not @code{wait3}, as
24017@code{wait3} has been removed from Posix.
24018@end defmac
24019
24020@defmac AC_WARN
24021@acindex{WARN}
24022Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24023@end defmac
24024
24025@defmac AC_WITH (@var{package}, @var{action-if-given}, @
24026  @ovar{action-if-not-given})
24027@acindex{WITH}
24028This is an obsolete version of @code{AC_ARG_WITH} that does not
24029support providing a help string (@pxref{AC_ARG_WITH}).
24030@end defmac
24031
24032@defmac AC_WORDS_BIGENDIAN
24033@acindex{WORDS_BIGENDIAN}
24034Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24035@end defmac
24036
24037@defmac AC_XENIX_DIR
24038@acindex{XENIX_DIR}
24039@ovindex LIBS
24040This macro used to add @option{-lx} to output variable @code{LIBS} if on
24041Xenix.  Also, if @file{dirent.h} is being checked for, added
24042@option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24043@code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24044running XENIX on which you should not depend:
24045
24046@example
24047AC_MSG_CHECKING([for Xenix])
24048AC_EGREP_CPP([yes],
24049[#if defined M_XENIX && !defined M_UNIX
24050  yes
24051#endif],
24052             [AC_MSG_RESULT([yes]); XENIX=yes],
24053             [AC_MSG_RESULT([no]); XENIX=])
24054@end example
24055@noindent
24056Don't use this macro, the dignified means to check the nature of the
24057host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24058@end defmac
24059
24060@defmac AC_YYTEXT_POINTER
24061@acindex{YYTEXT_POINTER}
24062This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24063integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24064@end defmac
24065
24066@node Autoconf 1
24067@section Upgrading From Version 1
24068@cindex Upgrading autoconf
24069@cindex Autoconf upgrading
24070
24071Autoconf version 2 is mostly backward compatible with version 1.
24072However, it introduces better ways to do some things, and doesn't
24073support some of the ugly things in version 1.  So, depending on how
24074sophisticated your @file{configure.ac} files are, you might have to do
24075some manual work in order to upgrade to version 2.  This chapter points
24076out some problems to watch for when upgrading.  Also, perhaps your
24077@command{configure} scripts could benefit from some of the new features in
24078version 2; the changes are summarized in the file @file{NEWS} in the
24079Autoconf distribution.
24080
24081@menu
24082* Changed File Names::          Files you might rename
24083* Changed Makefiles::           New things to put in @file{Makefile.in}
24084* Changed Macros::              Macro calls you might replace
24085* Changed Results::             Changes in how to check test results
24086* Changed Macro Writing::       Better ways to write your own macros
24087@end menu
24088
24089@node Changed File Names
24090@subsection Changed File Names
24091
24092If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24093in a particular package's source directory), you must rename it to
24094@file{acsite.m4}.  @xref{autoconf Invocation}.
24095
24096If you distribute @file{install.sh} with your package, rename it to
24097@file{install-sh} so @command{make} builtin rules don't inadvertently
24098create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24099looks for the script under both names, but it is best to use the new name.
24100
24101If you were using @file{config.h.top}, @file{config.h.bot}, or
24102@file{acconfig.h}, you still can, but you have less clutter if you
24103use the @code{AH_} macros.  @xref{Autoheader Macros}.
24104
24105@node Changed Makefiles
24106@subsection Changed Makefiles
24107
24108Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24109your @file{Makefile.in} files, so they can take advantage of the values
24110of those variables in the environment when @command{configure} is run.
24111Doing this isn't necessary, but it's a convenience for users.
24112
24113Also add @samp{@@configure_input@@} in a comment to each input file for
24114@code{AC_OUTPUT}, so that the output files contain a comment saying
24115they were produced by @command{configure}.  Automatically selecting the
24116right comment syntax for all the kinds of files that people call
24117@code{AC_OUTPUT} on became too much work.
24118
24119Add @file{config.log} and @file{config.cache} to the list of files you
24120remove in @code{distclean} targets.
24121
24122If you have the following in @file{Makefile.in}:
24123
24124@example
24125prefix = /usr/local
24126exec_prefix = $(prefix)
24127@end example
24128
24129@noindent
24130you must change it to:
24131
24132@example
24133prefix = @@prefix@@
24134exec_prefix = @@exec_prefix@@
24135@end example
24136
24137@noindent
24138The old behavior of replacing those variables without @samp{@@}
24139characters around them has been removed.
24140
24141@node Changed Macros
24142@subsection Changed Macros
24143
24144Many of the macros were renamed in Autoconf version 2.  You can still
24145use the old names, but the new ones are clearer, and it's easier to find
24146the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24147new names for the old macros.  Use the @command{autoupdate} program to
24148convert your @file{configure.ac} to using the new macro names.
24149@xref{autoupdate Invocation}.
24150
24151Some macros have been superseded by similar ones that do the job better,
24152but are not call-compatible.  If you get warnings about calling obsolete
24153macros while running @command{autoconf}, you may safely ignore them, but
24154your @command{configure} script generally works better if you follow
24155the advice that is printed about what to replace the obsolete macros with.  In
24156particular, the mechanism for reporting the results of tests has
24157changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24158via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24159looks better if you switch to @code{AC_MSG_CHECKING} and
24160@code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24161in conjunction with cache variables.  @xref{Caching Results}.
24162
24163
24164
24165@node Changed Results
24166@subsection Changed Results
24167
24168If you were checking the results of previous tests by examining the
24169shell variable @code{DEFS}, you need to switch to checking the values of
24170the cache variables for those tests.  @code{DEFS} no longer exists while
24171@command{configure} is running; it is only created when generating output
24172files.  This difference from version 1 is because properly quoting the
24173contents of that variable turned out to be too cumbersome and
24174inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24175Variable Names}.
24176
24177For example, here is a @file{configure.ac} fragment written for Autoconf
24178version 1:
24179
24180@example
24181AC_HAVE_FUNCS(syslog)
24182case "$DEFS" in
24183*-DHAVE_SYSLOG*) ;;
24184*) # syslog is not in the default libraries.  See if it's in some other.
24185  saved_LIBS="$LIBS"
24186  for lib in bsd socket inet; do
24187    AC_CHECKING(for syslog in -l$lib)
24188    LIBS="-l$lib $saved_LIBS"
24189    AC_HAVE_FUNCS(syslog)
24190    case "$DEFS" in
24191    *-DHAVE_SYSLOG*) break ;;
24192    *) ;;
24193    esac
24194    LIBS="$saved_LIBS"
24195  done ;;
24196esac
24197@end example
24198
24199Here is a way to write it for version 2:
24200
24201@example
24202AC_CHECK_FUNCS([syslog])
24203if test "x$ac_cv_func_syslog" = xno; then
24204  # syslog is not in the default libraries.  See if it's in some other.
24205  for lib in bsd socket inet; do
24206    AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24207      LIBS="-l$lib $LIBS"; break])
24208  done
24209fi
24210@end example
24211
24212If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24213backslashes before quotes, you need to remove them.  It now works
24214predictably, and does not treat quotes (except back quotes) specially.
24215@xref{Setting Output Variables}.
24216
24217All of the Boolean shell variables set by Autoconf macros now use
24218@samp{yes} for the true value.  Most of them use @samp{no} for false,
24219though for backward compatibility some use the empty string instead.  If
24220you were relying on a shell variable being set to something like 1 or
24221@samp{t} for true, you need to change your tests.
24222
24223@node Changed Macro Writing
24224@subsection Changed Macro Writing
24225
24226When defining your own macros, you should now use @code{AC_DEFUN}
24227instead of @code{define}.  @code{AC_DEFUN} automatically calls
24228@code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24229do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24230messages on the screen.  There's no actual harm in continuing to use the
24231older way, but it's less convenient and attractive.  @xref{Macro
24232Definitions}.
24233
24234You probably looked at the macros that came with Autoconf as a guide for
24235how to do things.  It would be a good idea to take a look at the new
24236versions of them, as the style is somewhat improved and they take
24237advantage of some new features.
24238
24239If you were doing tricky things with undocumented Autoconf internals
24240(macros, variables, diversions), check whether you need to change
24241anything to account for changes that have been made.  Perhaps you can
24242even use an officially supported technique in version 2 instead of
24243kludging.  Or perhaps not.
24244
24245To speed up your locally written feature tests, add caching to them.
24246See whether any of your tests are of general enough usefulness to
24247encapsulate them into macros that you can share.
24248
24249
24250@node Autoconf 2.13
24251@section Upgrading From Version 2.13
24252@cindex Upgrading autoconf
24253@cindex Autoconf upgrading
24254
24255The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24256suits this section@enddots{}
24257
24258@quotation
24259Autoconf version 2.50 is mostly backward compatible with version 2.13.
24260However, it introduces better ways to do some things, and doesn't
24261support some of the ugly things in version 2.13.  So, depending on how
24262sophisticated your @file{configure.ac} files are, you might have to do
24263some manual work in order to upgrade to version 2.50.  This chapter
24264points out some problems to watch for when upgrading.  Also, perhaps
24265your @command{configure} scripts could benefit from some of the new
24266features in version 2.50; the changes are summarized in the file
24267@file{NEWS} in the Autoconf distribution.
24268@end quotation
24269
24270@menu
24271* Changed Quotation::           Broken code which used to work
24272* New Macros::                  Interaction with foreign macros
24273* Hosts and Cross-Compilation::  Bugward compatibility kludges
24274* AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24275* AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24276@end menu
24277
24278@node Changed Quotation
24279@subsection Changed Quotation
24280
24281The most important changes are invisible to you: the implementation of
24282most macros have completely changed.  This allowed more factorization of
24283the code, better error messages, a higher uniformity of the user's
24284interface etc.  Unfortunately, as a side effect, some construct which
24285used to (miraculously) work might break starting with Autoconf 2.50.
24286The most common culprit is bad quotation.
24287
24288For instance, in the following example, the message is not properly
24289quoted:
24290
24291@example
24292AC_INIT
24293AC_CHECK_HEADERS(foo.h, ,
24294  AC_MSG_ERROR(cannot find foo.h, bailing out))
24295AC_OUTPUT
24296@end example
24297
24298@noindent
24299Autoconf 2.13 simply ignores it:
24300
24301@example
24302$ @kbd{autoconf-2.13; ./configure --silent}
24303creating cache ./config.cache
24304configure: error: cannot find foo.h
24305$
24306@end example
24307
24308@noindent
24309while Autoconf 2.50 produces a broken @file{configure}:
24310
24311@example
24312$ @kbd{autoconf-2.50; ./configure --silent}
24313configure: error: cannot find foo.h
24314./configure: exit: bad non-numeric arg `bailing'
24315./configure: exit: bad non-numeric arg `bailing'
24316$
24317@end example
24318
24319The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24320too!
24321
24322@example
24323AC_INIT([Example], [1.0], [bug-example@@example.org])
24324AC_CHECK_HEADERS([foo.h], [],
24325  [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24326AC_OUTPUT
24327@end example
24328
24329Many many (and many more) Autoconf macros were lacking proper quotation,
24330including no less than@dots{} @code{AC_DEFUN} itself!
24331
24332@example
24333$ @kbd{cat configure.in}
24334AC_DEFUN([AC_PROG_INSTALL],
24335[# My own much better version
24336])
24337AC_INIT
24338AC_PROG_INSTALL
24339AC_OUTPUT
24340$ @kbd{autoconf-2.13}
24341autoconf: Undefined macros:
24342***BUG in Autoconf--please report*** AC_FD_MSG
24343***BUG in Autoconf--please report*** AC_EPI
24344configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24345configure.in:5:AC_PROG_INSTALL
24346$ @kbd{autoconf-2.50}
24347$
24348@end example
24349
24350
24351@node New Macros
24352@subsection New Macros
24353
24354@cindex undefined macro
24355@cindex @code{_m4_divert_diversion}
24356
24357While Autoconf was relatively dormant in the late 1990s, Automake
24358provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24359in 2001, Autoconf provided
24360versions of these macros, integrated in the @code{AC_} namespace,
24361instead of @code{AM_}.  But in order to ease the upgrading via
24362@command{autoupdate}, bindings to such @code{AM_} macros are provided.
24363
24364Unfortunately older versions of Automake (e.g., Automake 1.4)
24365did not quote the names of these macros.
24366Therefore, when @command{m4} finds something like
24367@samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24368@code{AM_TYPE_PTRDIFF_T} is
24369expanded, replaced with its Autoconf definition.
24370
24371Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24372complains, in its own words:
24373
24374@example
24375$ @kbd{cat configure.ac}
24376AC_INIT([Example], [1.0], [bug-example@@example.org])
24377AM_TYPE_PTRDIFF_T
24378$ @kbd{aclocal-1.4}
24379$ @kbd{autoconf}
24380aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24381aclocal.m4:17: the top level
24382autom4te: m4 failed with exit status: 1
24383$
24384@end example
24385
24386Modern versions of Automake no longer define most of these
24387macros, and properly quote the names of the remaining macros.
24388If you must use an old Automake, do not depend upon macros from Automake
24389as it is simply not its job
24390to provide macros (but the one it requires itself):
24391
24392@example
24393$ @kbd{cat configure.ac}
24394AC_INIT([Example], [1.0], [bug-example@@example.org])
24395AM_TYPE_PTRDIFF_T
24396$ @kbd{rm aclocal.m4}
24397$ @kbd{autoupdate}
24398autoupdate: `configure.ac' is updated
24399$ @kbd{cat configure.ac}
24400AC_INIT([Example], [1.0], [bug-example@@example.org])
24401AC_CHECK_TYPES([ptrdiff_t])
24402$ @kbd{aclocal-1.4}
24403$ @kbd{autoconf}
24404$
24405@end example
24406
24407
24408@node Hosts and Cross-Compilation
24409@subsection Hosts and Cross-Compilation
24410@cindex Cross compilation
24411
24412Based on the experience of compiler writers, and after long public
24413debates, many aspects of the cross-compilation chain have changed:
24414
24415@itemize @minus
24416@item
24417the relationship between the build, host, and target architecture types,
24418
24419@item
24420the command line interface for specifying them to @command{configure},
24421
24422@item
24423the variables defined in @command{configure},
24424
24425@item
24426the enabling of cross-compilation mode.
24427@end itemize
24428
24429@sp 1
24430
24431The relationship between build, host, and target have been cleaned up:
24432the chain of default is now simply: target defaults to host, host to
24433build, and build to the result of @command{config.guess}.  Nevertheless,
24434in order to ease the transition from 2.13 to 2.50, the following
24435transition scheme is implemented.  @emph{Do not rely on it}, as it will
24436be completely disabled in a couple of releases (we cannot keep it, as it
24437proves to cause more problems than it cures).
24438
24439They all default to the result of running @command{config.guess}, unless
24440you specify either @option{--build} or @option{--host}.  In this case,
24441the default becomes the system type you specified.  If you specify both,
24442and they're different, @command{configure} enters cross compilation
24443mode, so it doesn't run any tests that require execution.
24444
24445Hint: if you mean to override the result of @command{config.guess},
24446prefer @option{--build} over @option{--host}.
24447
24448@sp 1
24449
24450For backward compatibility, @command{configure} accepts a system
24451type as an option by itself.  Such an option overrides the
24452defaults for build, host, and target system types.  The following
24453configure statement configures a cross toolchain that runs on
24454NetBSD/alpha but generates code for GNU Hurd/sparc,
24455which is also the build platform.
24456
24457@example
24458./configure --host=alpha-netbsd sparc-gnu
24459@end example
24460
24461@sp 1
24462
24463In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24464and @code{target} had a different semantics before and after the
24465invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24466@option{--build} is strictly copied into @code{build_alias}, and is left
24467empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24468set to the canonicalized build type.  To ease the transition, before,
24469its contents is the same as that of @code{build_alias}.  Do @emph{not}
24470rely on this broken feature.
24471
24472For consistency with the backward compatibility scheme exposed above,
24473when @option{--host} is specified but @option{--build} isn't, the build
24474system is assumed to be the same as @option{--host}, and
24475@samp{build_alias} is set to that value.  Eventually, this
24476historically incorrect behavior will go away.
24477
24478@sp 1
24479
24480The former scheme to enable cross-compilation proved to cause more harm
24481than good, in particular, it used to be triggered too easily, leaving
24482regular end users puzzled in front of cryptic error messages.
24483@command{configure} could even enter cross-compilation mode only
24484because the compiler was not functional.  This is mainly because
24485@command{configure} used to try to detect cross-compilation, instead of
24486waiting for an explicit flag from the user.
24487
24488Now, @command{configure} enters cross-compilation mode if and only if
24489@option{--host} is passed.
24490
24491That's the short documentation.  To ease the transition between 2.13 and
24492its successors, a more complicated scheme is implemented.  @emph{Do not
24493rely on the following}, as it will be removed in the near future.
24494
24495If you specify @option{--host}, but not @option{--build}, when
24496@command{configure} performs the first compiler test it tries to run
24497an executable produced by the compiler.  If the execution fails, it
24498enters cross-compilation mode.  This is fragile.  Moreover, by the time
24499the compiler test is performed, it may be too late to modify the
24500build-system type: other tests may have already been performed.
24501Therefore, whenever you specify @option{--host}, be sure to specify
24502@option{--build} too.
24503
24504@example
24505./configure --build=i686-pc-linux-gnu --host=m68k-coff
24506@end example
24507
24508@noindent
24509enters cross-compilation mode.  The former interface, which
24510consisted in setting the compiler to a cross-compiler without informing
24511@command{configure} is obsolete.  For instance, @command{configure}
24512fails if it can't run the code generated by the specified compiler if you
24513configure as follows:
24514
24515@example
24516./configure CC=m68k-coff-gcc
24517@end example
24518
24519
24520@node AC_LIBOBJ vs LIBOBJS
24521@subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24522
24523Up to Autoconf 2.13, the replacement of functions was triggered via the
24524variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24525@code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24526Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24527
24528This change is mandated by the unification of the GNU Build System
24529components.  In particular, the various fragile techniques used to parse
24530a @file{configure.ac} are all replaced with the use of traces.  As a
24531consequence, any action must be traceable, which obsoletes critical
24532variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24533and it can even be handled gracefully (read, ``without your having to
24534change something'').
24535
24536There were two typical uses of @code{LIBOBJS}: asking for a replacement
24537function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24538
24539@sp 1
24540
24541As for function replacement, the fix is immediate: use
24542@code{AC_LIBOBJ}.  For instance:
24543
24544@example
24545LIBOBJS="$LIBOBJS fnmatch.o"
24546LIBOBJS="$LIBOBJS malloc.$ac_objext"
24547@end example
24548
24549@noindent
24550should be replaced with:
24551
24552@example
24553AC_LIBOBJ([fnmatch])
24554AC_LIBOBJ([malloc])
24555@end example
24556
24557@sp 1
24558
24559@ovindex LIBOBJDIR
24560When used with Automake 1.10 or newer, a suitable value for
24561@code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24562can be referenced from any @file{Makefile.am}.  Even without Automake,
24563arranging for @code{LIBOBJDIR} to be set correctly enables
24564referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24565The @code{LIBOBJDIR} feature is experimental.
24566
24567
24568@node AC_ACT_IFELSE vs AC_TRY_ACT
24569@subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24570@c the anchor keeps the old node name, to try to avoid breaking links
24571@anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24572
24573@acindex{@var{ACT}_IFELSE}
24574@acindex{TRY_@var{ACT}}
24575Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24576@code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24577@code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24578and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24579@code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24580@code{AC_TRY_RUN}.  The motivations where:
24581@itemize @minus
24582@item
24583a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24584quoting their arguments;
24585
24586@item
24587the combinatoric explosion is solved by decomposing on the one hand the
24588generation of sources, and on the other hand executing the program;
24589
24590@item
24591this scheme helps supporting more languages than plain C and C++.
24592@end itemize
24593
24594In addition to the change of syntax, the philosophy has changed too:
24595while emphasis was put on speed at the expense of accuracy, today's
24596Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24597expense of speed.
24598
24599
24600As a perfect example of what is @emph{not} to be done, here is how to
24601find out whether a header file contains a particular declaration, such
24602as a typedef, a structure, a structure member, or a function.  Use
24603@code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24604header file; on some systems the symbol might be defined in another
24605header file that the file you are checking includes.
24606
24607As a (bad) example, here is how you should not check for C preprocessor
24608symbols, either defined by header files or predefined by the C
24609preprocessor: using @code{AC_EGREP_CPP}:
24610
24611@example
24612@group
24613AC_EGREP_CPP(yes,
24614[#ifdef _AIX
24615  yes
24616#endif
24617], is_aix=yes, is_aix=no)
24618@end group
24619@end example
24620
24621The above example, properly written would (i) use
24622@code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24623
24624@example
24625@group
24626AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24627[[#ifndef _AIX
24628 error: This isn't AIX!
24629#endif
24630]])],
24631                   [is_aix=yes],
24632                   [is_aix=no])
24633@end group
24634@end example
24635
24636
24637@c ============================= Generating Test Suites with Autotest
24638
24639@node Using Autotest
24640@chapter Generating Test Suites with Autotest
24641
24642@cindex Autotest
24643
24644@display
24645@strong{N.B.: This section describes a feature which is still
24646stabilizing.  Although we believe that Autotest is useful as-is, this
24647documentation describes an interface which might change in the future:
24648do not depend upon Autotest without subscribing to the Autoconf mailing
24649lists.}
24650@end display
24651
24652It is paradoxical that portable projects depend on nonportable tools
24653to run their test suite.  Autoconf by itself is the paragon of this
24654problem: although it aims at perfectly portability, up to 2.13 its
24655test suite was using DejaGNU, a rich and complex testing
24656framework, but which is far from being standard on Posix systems.
24657Worse yet, it was likely to be missing on the most fragile platforms,
24658the very platforms that are most likely to torture Autoconf and
24659exhibit deficiencies.
24660
24661To circumvent this problem, many package maintainers have developed their
24662own testing framework, based on simple shell scripts whose sole outputs
24663are exit status values describing whether the test succeeded.  Most of
24664these tests share common patterns, and this can result in lots of
24665duplicated code and tedious maintenance.
24666
24667Following exactly the same reasoning that yielded to the inception of
24668Autoconf, Autotest provides a test suite generation framework, based on
24669M4 macros building a portable shell script.  The suite itself is
24670equipped with automatic logging and tracing facilities which greatly
24671diminish the interaction with bug reporters, and simple timing reports.
24672
24673Autoconf itself has been using Autotest for years, and we do attest that
24674it has considerably improved the strength of the test suite and the
24675quality of bug reports.  Other projects are known to use some generation
24676of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
24677them with different needs, and this usage has validated Autotest as a general
24678testing framework.
24679
24680Nonetheless, compared to DejaGNU, Autotest is inadequate for
24681interactive tool testing, which is probably its main limitation.
24682
24683@menu
24684* Using an Autotest Test Suite::  Autotest and the user
24685* Writing Testsuites::          Autotest macros
24686* testsuite Invocation::        Running @command{testsuite} scripts
24687* Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24688@end menu
24689
24690@node Using an Autotest Test Suite
24691@section Using an Autotest Test Suite
24692
24693@menu
24694* testsuite Scripts::           The concepts of Autotest
24695* Autotest Logs::               Their contents
24696@end menu
24697
24698@node testsuite Scripts
24699@subsection @command{testsuite} Scripts
24700
24701@cindex @command{testsuite}
24702
24703Generating testing or validation suites using Autotest is rather easy.
24704The whole validation suite is held in a file to be processed through
24705@command{autom4te}, itself using GNU M4 under the hood, to
24706produce a stand-alone Bourne shell script which then gets distributed.
24707Neither @command{autom4te} nor GNU M4 are needed at
24708the installer's end.
24709
24710@cindex test group
24711Each test of the validation suite should be part of some test group.  A
24712@dfn{test group} is a sequence of interwoven tests that ought to be
24713executed together, usually because one test in the group creates data
24714files that a later test in the same group needs to read.  Complex test
24715groups make later debugging more tedious.  It is much better to
24716keep only a few tests per test group.  Ideally there is only one test
24717per test group.
24718
24719For all but the simplest packages, some file such as @file{testsuite.at}
24720does not fully hold all test sources, as these are often easier to
24721maintain in separate files.  Each of these separate files holds a single
24722test group, or a sequence of test groups all addressing some common
24723functionality in the package.  In such cases, @file{testsuite.at}
24724merely initializes the validation suite, and sometimes does elementary
24725health checking, before listing include statements for all other test
24726files.  The special file @file{package.m4}, containing the
24727identification of the package, is automatically included if found.
24728
24729A convenient alternative consists in moving all the global issues
24730(local Autotest macros, elementary health checking, and @code{AT_INIT}
24731invocation) into the file @code{local.at}, and making
24732@file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24733suites.  In such case, generating the whole test suite or pieces of it
24734is only a matter of choosing the @command{autom4te} command line
24735arguments.
24736
24737The validation scripts that Autotest produces are by convention called
24738@command{testsuite}.  When run, @command{testsuite} executes each test
24739group in turn, producing only one summary line per test to say if that
24740particular test succeeded or failed.  At end of all tests, summarizing
24741counters get printed.  One debugging directory is left for each test
24742group which failed, if any: such directories are named
24743@file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24744the test group, and they include:
24745
24746@itemize @bullet
24747@item a debugging script named @file{run} which reruns the test in
24748@dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24749of debugging scripts has the purpose of easing the chase for bugs.
24750
24751@item all the files created with @code{AT_DATA}
24752
24753@item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24754
24755@item a log of the run, named @file{testsuite.log}
24756@end itemize
24757
24758In the ideal situation, none of the tests fail, and consequently no
24759debugging directory is left behind for validation.
24760
24761It often happens in practice that individual tests in the validation
24762suite need to get information coming out of the configuration process.
24763Some of this information, common for all validation suites, is provided
24764through the file @file{atconfig}, automatically created by
24765@code{AC_CONFIG_TESTDIR}.  For configuration information which your
24766testing environment specifically needs, you might prepare an optional
24767file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24768The configuration process produces @file{atconfig} and @file{atlocal}
24769out of these two input files, and these two produced files are
24770automatically read by the @file{testsuite} script.
24771
24772Here is a diagram showing the relationship between files.
24773
24774@noindent
24775Files used in preparing a software package for distribution:
24776
24777@example
24778                [package.m4] -->.
24779                                 \
24780subfile-1.at ->.  [local.at] ---->+
24781    ...         \                  \
24782subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
24783    ...         /
24784subfile-n.at ->'
24785@end example
24786
24787@noindent
24788Files used in configuring a software package:
24789
24790@example
24791                                     .--> atconfig
24792                                    /
24793[atlocal.in] -->  config.status* --<
24794                                    \
24795                                     `--> [atlocal]
24796@end example
24797
24798@noindent
24799Files created during test suite execution:
24800
24801@example
24802atconfig -->.                    .--> testsuite.log
24803             \                  /
24804              >-- testsuite* --<
24805             /                  \
24806[atlocal] ->'                    `--> [testsuite.dir]
24807@end example
24808
24809
24810@node Autotest Logs
24811@subsection Autotest Logs
24812
24813When run, the test suite creates a log file named after itself, e.g., a
24814test suite named @command{testsuite} creates @file{testsuite.log}.  It
24815contains a lot of information, usually more than maintainers actually
24816need, but therefore most of the time it contains all that is needed:
24817
24818@table @asis
24819@item command line arguments
24820A bad but unfortunately widespread habit consists of
24821setting environment variables before the command, such as in
24822@samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
24823know this change, hence (i) it cannot report it to you, and (ii)
24824it cannot preserve the value of @code{CC} for subsequent runs.
24825Autoconf faced exactly the same problem, and solved it by asking
24826users to pass the variable definitions as command line arguments.
24827Autotest requires this rule, too, but has no means to enforce it; the log
24828then contains a trace of the variables that were changed by the user.
24829
24830@item @file{ChangeLog} excerpts
24831The topmost lines of all the @file{ChangeLog} files found in the source
24832hierarchy.  This is especially useful when bugs are reported against
24833development versions of the package, since the version string does not
24834provide sufficient information to know the exact state of the sources
24835the user compiled.  Of course, this relies on the use of a
24836@file{ChangeLog}.
24837
24838@item build machine
24839Running a test suite in a cross-compile environment is not an easy task,
24840since it would mean having the test suite run on a machine @var{build},
24841while running programs on a machine @var{host}.  It is much simpler to
24842run both the test suite and the programs on @var{host}, but then, from
24843the point of view of the test suite, there remains a single environment,
24844@var{host} = @var{build}.  The log contains relevant information on the
24845state of the @var{build} machine, including some important environment
24846variables.
24847@c FIXME: How about having an M4sh macro to say `hey, log the value
24848@c of `@dots{}'?  This would help both Autoconf and Autotest.
24849
24850@item tested programs
24851The absolute file name and answers to @option{--version} of the tested
24852programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
24853
24854@item configuration log
24855The contents of @file{config.log}, as created by @command{configure},
24856are appended.  It contains the configuration flags and a detailed report
24857on the configuration itself.
24858@end table
24859
24860
24861@node Writing Testsuites
24862@section Writing @file{testsuite.at}
24863
24864The @file{testsuite.at} is a Bourne shell script making use of special
24865Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
24866its beginning followed by one call to @code{m4_include} per source file
24867for tests.  Each such included file, or the remainder of
24868@file{testsuite.at} if include files are not used, contain a sequence of
24869test groups.  Each test group begins with a call to @code{AT_SETUP},
24870then an arbitrary number of shell commands or calls to @code{AT_CHECK},
24871and then completes with a call to @code{AT_CLEANUP}.  Multiple test
24872groups can be categorized by a call to @code{AT_BANNER}.
24873
24874All of the public Autotest macros have all-uppercase names in the
24875namespace @samp{^AT_} to prevent them from accidentally conflicting with
24876other text; Autoconf also reserves the namespace @samp{^_AT_} for
24877internal macros.  All shell variables used in the testsuite for internal
24878purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
24879also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
24880makes use of the file system namespace @samp{^at-}.
24881
24882Since Autoconf is built on top of M4sugar (@pxref{Programming in
24883M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
24884of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
24885@emph{should not use} the namespace of a package that does not own the
24886macro or shell code you are writing.
24887
24888@defmac AT_INIT (@ovar{name})
24889@atindex{INIT}
24890@c FIXME: Not clear, plus duplication of the information.
24891Initialize Autotest.  Giving a @var{name} to the test suite is
24892encouraged if your package includes several test suites.  Before this
24893macro is called, @code{AT_PACKAGE_STRING} and
24894@code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
24895information about the testsuite to the user.  Typically, these macros
24896are provided by a file @file{package.m4} built by @command{make}
24897(@pxref{Making testsuite Scripts}), in order to inherit the package
24898name, version, and bug reporting address from @file{configure.ac}.
24899@end defmac
24900
24901@defmac AT_COPYRIGHT (@var{copyright-notice})
24902@atindex{COPYRIGHT}
24903@cindex Copyright Notice
24904State that, in addition to the Free Software Foundation's copyright on
24905the Autotest macros, parts of your test suite are covered by
24906@var{copyright-notice}.
24907
24908The @var{copyright-notice} shows up in both the head of
24909@command{testsuite} and in @samp{testsuite --version}.
24910@end defmac
24911
24912@defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
24913  @ovar{action-if-given}, @ovar{action-if-not-given})
24914@atindex{ARG_OPTION}
24915@vrindex at_arg_@var{option}
24916Accept options from the space-separated list @var{options}, a list that
24917has leading dashes removed from the options.  Long options will be
24918prefixed with @samp{--}, single-character options with @samp{-}.  The
24919first word in this list is the primary @var{option}, any others are
24920assumed to be short-hand aliases.  The variable associated with it
24921is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
24922with underscores.
24923
24924If the user passes @option{--@var{option}} to the @command{testsuite},
24925the variable will be set to @samp{:}.  If the user does not pass the
24926option, or passes @option{--no-@var{option}}, then the variable will be
24927set to @samp{false}.
24928
24929@vrindex at_optarg
24930@vrindex at_optarg_@var{option}
24931@var{action-if-given} is run each time the option is encountered; here,
24932the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
24933appropriate.  @code{at_optarg} is actually just a copy of
24934@code{at_arg_@var{option}}.
24935
24936@var{action-if-not-given} will be run once after option parsing is
24937complete and if no option from @var{options} was used.
24938
24939@var{help-text} is added to the end of the list of options shown in
24940@command{testsuite --help} (@pxref{AS_HELP_STRING}).
24941
24942It is recommended that you use a package-specific prefix to @var{options}
24943names in order to avoid clashes with future Autotest built-in options.
24944@end defmac
24945
24946@defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
24947  @ovar{action-if-given}, @ovar{action-if-not-given})
24948@atindex{ARG_OPTION_ARG}
24949@vrindex at_arg_@var{option}
24950Accept options with arguments from the space-separated list
24951@var{options}, a list that has leading dashes removed from the options.
24952Long options will be prefixed with @samp{--}, single-character options
24953with @samp{-}.  The first word in this list is the primary @var{option},
24954any others are assumed to be short-hand aliases.  The variable associated
24955with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24956replaced with underscores.
24957
24958If the user passes @option{--@var{option}=@var{arg}} or
24959@option{--@var{option} @var{arg}} to the @command{testsuite}, the
24960variable will be set to @samp{@var{arg}}.
24961
24962@vrindex at_optarg
24963@var{action-if-given} is run each time the option is encountered; here,
24964the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24965@code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24966
24967@var{action-if-not-given} will be run once after option parsing is
24968complete and if no option from @var{options} was used.
24969
24970@var{help-text} is added to the end of the list of options shown in
24971@command{testsuite --help} (@pxref{AS_HELP_STRING}).
24972
24973It is recommended that you use a package-specific prefix to @var{options}
24974names in order to avoid clashes with future Autotest built-in options.
24975@end defmac
24976
24977@defmac AT_COLOR_TESTS
24978@atindex{COLOR_TESTS}
24979Enable colored test results by default when the output is connected to
24980a terminal.
24981@end defmac
24982
24983@defmac AT_TESTED (@var{executables})
24984@atindex{TESTED}
24985Log the file name and answer to @option{--version} of each program in
24986space-separated list @var{executables}.  Several invocations register
24987new executables, in other words, don't fear registering one program
24988several times.
24989
24990Autotest test suites rely on @env{PATH} to find the tested program.
24991This avoids the need to generate absolute names of the various tools, and
24992makes it possible to test installed programs.  Therefore, knowing which
24993programs are being exercised is crucial to understanding problems in
24994the test suite itself, or its occasional misuses.  It is a good idea to
24995also subscribe foreign programs you depend upon, to avoid incompatible
24996diagnostics.
24997@end defmac
24998
24999@sp 1
25000
25001@defmac AT_BANNER (@var{test-category-name})
25002@atindex{BANNER}
25003This macro identifies the start of a category of related test groups.
25004When the resulting @file{testsuite} is invoked with more than one test
25005group to run, its output will include a banner containing
25006@var{test-category-name} prior to any tests run from that category.  The
25007banner should be no more than about 40 or 50 characters.  A blank banner
25008indicates uncategorized tests; an empty line will be inserted after
25009tests from an earlier category, effectively ending that category.
25010@end defmac
25011
25012@defmac AT_SETUP (@var{test-group-name})
25013@atindex{SETUP}
25014This macro starts a group of related tests, all to be executed in the
25015same subshell.  It accepts a single argument, which holds a few words
25016(no more than about 30 or 40 characters) quickly describing the purpose
25017of the test group being started.  @var{test-group-name} must not expand
25018to unbalanced quotes, although quadrigraphs can be used.
25019@end defmac
25020
25021@defmac AT_KEYWORDS (@var{keywords})
25022@atindex{KEYWORDS}
25023Associate the space-separated list of @var{keywords} to the enclosing
25024test group.  This makes it possible to run ``slices'' of the test suite.
25025For instance, if some of your test groups exercise some @samp{foo}
25026feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25027@samp{./testsuite -k foo} to run exclusively these test groups.  The
25028@var{test-group-name} of the test group is automatically recorded to
25029@code{AT_KEYWORDS}.
25030
25031Several invocations within a test group accumulate new keywords.  In
25032other words, don't fear registering the same keyword several times in a
25033test group.
25034@end defmac
25035
25036@defmac AT_CAPTURE_FILE (@var{file})
25037@atindex{CAPTURE_FILE}
25038If the current test group fails, log the contents of @var{file}.
25039Several identical calls within one test group have no additional effect.
25040@end defmac
25041
25042@defmac AT_FAIL_IF (@var{shell-condition})
25043@atindex{FAIL_IF}
25044Make the test group fail and skip the rest of its execution, if
25045@var{shell-condition} is true.  @var{shell-condition} is a shell expression
25046such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25047will be executed and may still cause the test group to be skipped.
25048You can instantiate this macro many times from within the same test group.
25049
25050You should use this macro only for very simple failure conditions.  If the
25051@var{shell-condition} could emit any kind of output you should instead
25052use @command{AT_CHECK} like
25053@example
25054AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25055@end example
25056@noindent
25057so that such output is properly recorded in the @file{testsuite.log}
25058file.
25059@end defmac
25060
25061@defmac AT_SKIP_IF (@var{shell-condition})
25062@atindex{SKIP_IF}
25063Determine whether the test should be skipped because it requires
25064features that are unsupported on the machine under test.
25065@var{shell-condition} is a shell expression such as a @code{test}
25066command.  Tests before @command{AT_SKIP_IF} will be executed
25067and may still cause the test group to fail.  You can instantiate this
25068macro many times from within the same test group.
25069
25070You should use this macro only for very simple skip conditions.  If the
25071@var{shell-condition} could emit any kind of output you should instead
25072use @command{AT_CHECK} like
25073@example
25074AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25075@end example
25076@noindent
25077so that such output is properly recorded in the @file{testsuite.log}
25078file.
25079@end defmac
25080
25081@defmac AT_XFAIL_IF (@var{shell-condition})
25082@atindex{XFAIL_IF}
25083Determine whether the test is expected to fail because it is a known
25084bug (for unsupported features, you should skip the test).
25085@var{shell-condition} is a shell expression such as a @code{test}
25086command; you can instantiate this macro many times from within the
25087same test group, and one of the conditions is enough to turn
25088the test into an expected failure.
25089@end defmac
25090
25091@defmac AT_CLEANUP
25092@atindex{CLEANUP}
25093End the current test group.
25094@end defmac
25095
25096@sp 1
25097
25098@defmac AT_DATA (@var{file}, @var{contents})
25099@atindex{DATA}
25100Initialize an input data @var{file} with given @var{contents}.  Of
25101course, the @var{contents} have to be properly quoted between square
25102brackets to protect against included commas or spurious M4
25103expansion.  @var{contents} must be empty or end with a newline.
25104@var{file} must
25105be a single shell word that expands into a single file name.
25106@end defmac
25107
25108@defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25109  @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25110@defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25111  @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25112@atindex{CHECK}
25113@atindex{CHECK_UNQUOTED}
25114@vrindex at_status
25115Execute a test by performing given shell @var{commands} in a subshell.
25116@var{commands} is output as-is, so shell expansions are honored.  These
25117commands should normally exit with @var{status}, while producing expected
25118@var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25119unexpected status 77, then the rest of the test group is skipped.  If
25120@var{commands} exit with unexpected status 99, then the test group is
25121immediately failed.  Otherwise, if this test fails, run shell commands
25122@var{run-if-fail} or, if this test passes, run shell commands
25123@var{run-if-pass}, both inside the current shell execution environment.
25124At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25125@var{commands} is available in the @code{at_status} shell variable.
25126
25127This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25128
25129If @var{status} is the literal @samp{ignore}, then the corresponding
25130exit status is not checked, except for the special cases of 77 (skip)
25131and 99 (hard failure).  The existence of hard failures allows one to
25132mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25133feature has not yet been implemented, but to still distinguish between
25134gracefully handling the missing feature and dumping core.  A hard
25135failure also inhibits post-test actions in @var{run-if-fail}.
25136
25137If the value of the @var{stdout} or @var{stderr} parameter is one of the
25138literals in the following table, then the test treats the output
25139according to the rules of that literal.  Otherwise, the value of the
25140parameter is treated as text that must exactly match the output given by
25141@var{commands} on standard output and standard error (including an empty
25142parameter for no output); any differences are captured in the testsuite
25143log and the test is failed (unless an unexpected exit status of 77
25144skipped the test instead).  The difference between @code{AT_CHECK} and
25145@code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25146expansion (@samp{$}), command substitution (@samp{`}), and backslash
25147escaping (@samp{\}) on comparison text given in the @var{stdout} and
25148@var{stderr} arguments; if the text includes a trailing newline, this
25149would be the same as if it were specified via an unquoted
25150here-document.  (However, there is no difference in the interpretation
25151of @var{commands}).
25152
25153@table @samp
25154@item ignore
25155The content of the output is ignored, but still captured in the test
25156group log (if the testsuite is run with option @option{-v}, the test
25157group log is displayed as the test is run; if the test group later
25158fails, the test group log is also copied into the overall testsuite
25159log).  This action is valid for both @var{stdout} and @var{stderr}.
25160
25161@item ignore-nolog
25162The content of the output is ignored, and nothing is captured in the log
25163files.  If @var{commands} are likely to produce binary output (including
25164long lines) or large amounts of output, then logging the output can make
25165it harder to locate details related to subsequent tests within the
25166group, and could potentially corrupt terminal display of a user running
25167@command{testsuite -v}.
25168
25169@item stdout
25170For the @var{stdout} parameter, capture the content of standard output
25171to both the file @file{stdout} and the test group log.  Subsequent
25172commands in the test group can then post-process the file.  This action
25173is often used when it is desired to use @command{grep} to look for a
25174substring in the output, or when the output must be post-processed to
25175normalize error messages into a common form.
25176
25177@item stderr
25178Like @samp{stdout}, except that it only works for the @var{stderr}
25179parameter, and the standard error capture file will be named
25180@file{stderr}.
25181
25182@item stdout-nolog
25183@itemx stderr-nolog
25184Like @samp{stdout} or @samp{stderr}, except that the captured output is
25185not duplicated into the test group log.  This action is particularly
25186useful for an intermediate check that produces large amounts of data,
25187which will be followed by another check that filters down to the
25188relevant data, as it makes it easier to locate details in the log.
25189
25190@item expout
25191For the @var{stdout} parameter, compare standard output contents with
25192the previously created file @file{expout}, and list any differences in
25193the testsuite log.
25194
25195@item experr
25196Like @samp{expout}, except that it only works for the @var{stderr}
25197parameter, and the standard error contents are compared with
25198@file{experr}.
25199@end table
25200@end defmac
25201
25202@defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25203  @ovar{run-if-fail}, @ovar{run-if-pass})
25204@atindex{CHECK_EUNIT}
25205Initialize and execute an Erlang module named @var{module} that performs
25206tests following the @var{test-spec} EUnit test specification.
25207@var{test-spec} must be a valid EUnit test specification, as defined in
25208the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25209Reference Manual}.  @var{erlflags} are optional command-line options
25210passed to the Erlang interpreter to execute the test Erlang module.
25211Typically, @var{erlflags} defines at least the paths to directories
25212containing the compiled Erlang modules under test, as @samp{-pa path1
25213path2 ...}.
25214
25215For example, the unit tests associated with Erlang module @samp{testme},
25216which compiled code is in subdirectory @file{src}, can be performed
25217with:
25218
25219@example
25220AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25221               [-pa "$@{abs_top_builddir@}/src"])
25222@end example
25223
25224This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25225
25226Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25227must be defined as the path of the Erlang interpreter, the path of the
25228Erlang compiler, and the command-line flags to pass to the compiler,
25229respectively.  Those variables should be configured in
25230@file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25231@command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25232variables are automatically defined in the testsuite.  If @code{ERL} or
25233@code{ERLC} is not defined, the test group is skipped.
25234
25235If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25236be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25237an invalid EUnit test specification, the test group fails.  Otherwise,
25238if the EUnit test passes, shell commands @var{run-if-pass} are executed
25239or, if the EUnit test fails, shell commands @var{run-if-fail} are
25240executed and the test group fails.
25241
25242Only the generated test Erlang module is automatically compiled and
25243executed.  If @var{test-spec} involves testing other Erlang modules,
25244e.g. module @samp{testme} in the example above, those modules must be
25245already compiled.
25246
25247If the testsuite is run in verbose mode, with option @option{--verbose},
25248EUnit is also run in verbose mode to output more details about
25249individual unit tests.
25250@end defmac
25251
25252
25253@node testsuite Invocation
25254@section Running @command{testsuite} Scripts
25255@cindex @command{testsuite}
25256
25257Autotest test suites support the following options:
25258
25259@table @option
25260@item --help
25261@itemx -h
25262Display the list of options and exit successfully.
25263
25264@item --version
25265@itemx -V
25266Display the version of the test suite and exit successfully.
25267
25268@item --directory=@var{dir}
25269@itemx -C @var{dir}
25270Change the current directory to @var{dir} before creating any files.
25271Useful for running the testsuite in a subdirectory from a top-level
25272Makefile.
25273
25274@item --jobs@r{[}=@var{n}@r{]}
25275@itemx -j@ovar{n}
25276Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25277run all given tests in parallel.  Note that there should be no space
25278before the argument to @option{-j}, as @option{-j @var{number}} denotes
25279the separate arguments @option{-j} and @option{@var{number}}, see below.
25280
25281In parallel mode, the standard input device of the testsuite script is
25282not available to commands inside a test group.  Furthermore, banner
25283lines are not printed, and the summary line for each test group is
25284output after the test group completes.  Summary lines may appear
25285unordered.  If verbose and trace output are enabled (see below), they
25286may appear intermixed from concurrently running tests.
25287
25288Parallel mode requires the @command{mkfifo} command to work, and will be
25289silently disabled otherwise.
25290
25291@item --clean
25292@itemx -c
25293Remove all the files the test suite might have created and exit.  Meant
25294for @code{clean} Make targets.
25295
25296@item --list
25297@itemx -l
25298List all the tests (or only the selection), including their possible
25299keywords.
25300@end table
25301
25302@sp 1
25303
25304By default all tests are performed (or described with @option{--list})
25305silently in the default environment, but the environment, set of tests,
25306and verbosity level can be tuned:
25307
25308@table @samp
25309@item @var{variable}=@var{value}
25310Set the environment @var{variable} to @var{value}.  Use this rather
25311than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25312different environment.
25313
25314@cindex @code{AUTOTEST_PATH}
25315The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25316to @env{PATH}.  Relative directory names (not starting with
25317@samp{/}) are considered to be relative to the top level of the
25318package being built.  All directories are made absolute, first
25319starting from the top level @emph{build} tree, then from the
25320@emph{source} tree.  For instance @samp{./testsuite
25321AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25322in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25323then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25324@env{PATH}.
25325
25326@item @var{number}
25327@itemx @var{number}-@var{number}
25328@itemx @var{number}-
25329@itemx -@var{number}
25330Add the corresponding test groups, with obvious semantics, to the
25331selection.
25332
25333@item --keywords=@var{keywords}
25334@itemx -k @var{keywords}
25335Add to the selection the test groups with title or keywords (arguments
25336to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25337of the comma separated list @var{keywords}, case-insensitively.  Use
25338@samp{!} immediately before the keyword to invert the selection for this
25339keyword.  By default, the keywords match whole words; enclose them in
25340@samp{.*} to also match parts of words.
25341
25342For example, running
25343
25344@example
25345@kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25346@end example
25347
25348@noindent
25349selects all tests tagged @samp{autoupdate} @emph{and} with tags
25350containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25351etc.), while
25352
25353@example
25354@kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25355@end example
25356
25357@noindent
25358selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25359containing @samp{FUNC}.
25360
25361@item --errexit
25362@itemx -e
25363If any test fails, immediately abort testing.  This implies
25364@option{--debug}: post test group clean up, and top-level logging
25365are inhibited.  This option is meant for the full test
25366suite, it is not really useful for generated debugging scripts.
25367If the testsuite is run in parallel mode using @option{--jobs},
25368then concurrently running tests will finish before exiting.
25369
25370@item --verbose
25371@itemx -v
25372Force more verbosity in the detailed output of what is being done.  This
25373is the default for debugging scripts.
25374
25375@item --color
25376@itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25377Enable colored test results.  Without an argument, or with @samp{always},
25378test results will be colored.  With @samp{never}, color mode is turned
25379off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25380the testsuite author, or the argument @samp{auto} is given, then test
25381results are colored if standard output is connected to a terminal.
25382
25383@item --debug
25384@itemx -d
25385Do not remove the files after a test group was performed---but they are
25386still removed @emph{before}, therefore using this option is sane when
25387running several test groups.  Create debugging scripts.  Do not
25388overwrite the top-level
25389log (in order to preserve a supposedly existing full log file).  This is
25390the default for debugging scripts, but it can also be useful to debug
25391the testsuite itself.
25392
25393@item --recheck
25394Add to the selection all test groups that failed or passed unexpectedly
25395during the last non-debugging test run.
25396
25397@item --trace
25398@itemx -x
25399Trigger shell tracing of the test groups.
25400@end table
25401
25402Besides these options accepted by every Autotest testsuite, the
25403testsuite author might have added package-specific options
25404via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25405(@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25406the package documentation for details.
25407
25408
25409@node Making testsuite Scripts
25410@section Making @command{testsuite} Scripts
25411
25412For putting Autotest into movement, you need some configuration and
25413makefile machinery.  We recommend, at least if your package uses deep or
25414shallow hierarchies, that you use @file{tests/} as the name of the
25415directory holding all your tests and their makefile.  Here is a
25416check list of things to do.
25417
25418@itemize @minus
25419
25420@item
25421@cindex @file{package.m4}
25422@atindex{PACKAGE_STRING}
25423@atindex{PACKAGE_BUGREPORT}
25424@atindex{PACKAGE_NAME}
25425@atindex{PACKAGE_TARNAME}
25426@atindex{PACKAGE_VERSION}
25427@atindex{PACKAGE_URL}
25428Make sure to create the file @file{package.m4}, which defines the
25429identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25430full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25431address to which bug reports should be sent.  For sake of completeness,
25432we suggest that you also define @code{AT_PACKAGE_NAME},
25433@code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25434@code{AT_PACKAGE_URL}.
25435@xref{Initializing configure}, for a description of these variables.
25436Be sure to distribute @file{package.m4} and to put it into the source
25437hierarchy: the test suite ought to be shipped!  See below for an example
25438@file{Makefile} excerpt.
25439
25440@item
25441Invoke @code{AC_CONFIG_TESTDIR}.
25442
25443@defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
25444@acindex{CONFIG_TESTDIR}
25445An Autotest test suite is to be configured in @var{directory}.  This
25446macro causes @file{@var{directory}/atconfig} to be created by
25447@command{config.status} and sets the default @code{AUTOTEST_PATH} to
25448@var{test-path} (@pxref{testsuite Invocation}).
25449@end defmac
25450
25451@item
25452Still within @file{configure.ac}, as appropriate, ensure that some
25453@code{AC_CONFIG_FILES} command includes substitution for
25454@file{tests/atlocal}.
25455
25456@item
25457The appropriate @file{Makefile} should be modified so the validation in
25458your package is triggered by @samp{make check}.  An example is provided
25459below.
25460@end itemize
25461
25462With Automake, here is a minimal example for inclusion in
25463@file{tests/Makefile.am}, in order to link @samp{make check} with a
25464validation suite.
25465
25466@example
25467# The `:;' works around a Bash 3.2 bug when the output is not writable.
25468$(srcdir)/package.m4: $(top_srcdir)/configure.ac
25469        :;@{ \
25470          echo '# Signature of the current package.' && \
25471          echo 'm4_define([AT_PACKAGE_NAME],' && \
25472          echo '  [$(PACKAGE_NAME)])' && \
25473          echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25474          echo '  [$(PACKAGE_TARNAME)])' && \
25475          echo 'm4_define([AT_PACKAGE_VERSION],' && \
25476          echo '  [$(PACKAGE_VERSION)])' && \
25477          echo 'm4_define([AT_PACKAGE_STRING],' && \
25478          echo '  [$(PACKAGE_STRING)])' && \
25479          echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25480          echo '  [$(PACKAGE_BUGREPORT)])'; \
25481          echo 'm4_define([AT_PACKAGE_URL],' && \
25482          echo '  [$(PACKAGE_URL)])'; \
25483        @} >'$(srcdir)/package.m4'
25484
25485EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25486TESTSUITE = $(srcdir)/testsuite
25487
25488check-local: atconfig atlocal $(TESTSUITE)
25489        $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25490
25491installcheck-local: atconfig atlocal $(TESTSUITE)
25492        $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25493          $(TESTSUITEFLAGS)
25494
25495clean-local:
25496        test ! -f '$(TESTSUITE)' || \
25497         $(SHELL) '$(TESTSUITE)' --clean
25498
25499AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
25500AUTOTEST = $(AUTOM4TE) --language=autotest
25501$(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25502        $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25503        mv $@@.tmp $@@
25504@end example
25505
25506Note that the built testsuite is distributed; this is necessary because
25507users might not have Autoconf installed, and thus would not be able to
25508rebuild it.  Likewise, the use of @file{missing} provides the user with
25509a nicer error message if they modify a source file to the testsuite, and
25510accidentally trigger the rebuild rules.
25511
25512You might want to list explicitly the dependencies, i.e., the list of
25513the files @file{testsuite.at} includes.
25514
25515If you don't use Automake, you should include the above example in
25516@file{tests/@/Makefile.in}, along with additional lines inspired from
25517the following:
25518
25519@example
25520subdir = tests
25521PACKAGE_NAME = @@PACKAGE_NAME@@
25522PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25523PACKAGE_VERSION = @@PACKAGE_VERSION@@
25524PACKAGE_STRING = @@PACKAGE_STRING@@
25525PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25526PACKAGE_URL = @@PACKAGE_URL@@
25527
25528atconfig: $(top_builddir)/config.status
25529        cd $(top_builddir) && \
25530           $(SHELL) ./config.status $(subdir)/$@@
25531
25532atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25533        cd $(top_builddir) && \
25534           $(SHELL) ./config.status $(subdir)/$@@
25535@end example
25536
25537@noindent
25538and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
25539to distribute the file @file{build-aux/@/missing} from the Automake
25540project; a copy of this file resides in the Autoconf source tree.
25541
25542With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
25543within your makefile, you can fine-tune test suite execution with this
25544variable, for example:
25545
25546@example
25547make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25548@end example
25549
25550
25551
25552@c =============================== Frequent Autoconf Questions, with answers
25553
25554@node FAQ
25555@chapter Frequent Autoconf Questions, with answers
25556
25557Several questions about Autoconf come up occasionally.  Here some of them
25558are addressed.
25559
25560@menu
25561* Distributing::                Distributing @command{configure} scripts
25562* Why GNU M4::                  Why not use the standard M4?
25563* Bootstrapping::               Autoconf and GNU M4 require each other?
25564* Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25565* Defining Directories::        Passing @code{datadir} to program
25566* Autom4te Cache::              What is it?  Can I remove it?
25567* Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25568* Expanded Before Required::    Expanded Before Required
25569* Debugging::                   Debugging @command{configure} scripts
25570@end menu
25571
25572@node Distributing
25573@section Distributing @command{configure} Scripts
25574@cindex License
25575
25576@display
25577What are the restrictions on distributing @command{configure}
25578scripts that Autoconf generates?  How does that affect my
25579programs that use them?
25580@end display
25581
25582There are no restrictions on how the configuration scripts that Autoconf
25583produces may be distributed or used.  In Autoconf version 1, they were
25584covered by the GNU General Public License.  We still encourage
25585software authors to distribute their work under terms like those of the
25586GPL, but doing so is not required to use Autoconf.
25587
25588Of the other files that might be used with @command{configure},
25589@file{config.h.in} is under whatever copyright you use for your
25590@file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25591exception to the GPL when they are used with an Autoconf-generated
25592@command{configure} script, which permits you to distribute them under the
25593same terms as the rest of your package.  @file{install-sh} is from the X
25594Consortium and is not copyrighted.
25595
25596@node Why GNU M4
25597@section Why Require GNU M4?
25598
25599@display
25600Why does Autoconf require GNU M4?
25601@end display
25602
25603Many M4 implementations have hard-coded limitations on the size and
25604number of macros that Autoconf exceeds.  They also lack several
25605builtin macros that it would be difficult to get along without in a
25606sophisticated application like Autoconf, including:
25607
25608@example
25609m4_builtin
25610m4_indir
25611m4_bpatsubst
25612__file__
25613__line__
25614@end example
25615
25616Autoconf requires version 1.4.6 or later of GNU M4.
25617
25618Since only software maintainers need to use Autoconf, and since GNU
25619M4 is simple to configure and install, it seems reasonable to require
25620GNU M4 to be installed also.  Many maintainers of GNU and
25621other free software already have most of the GNU utilities
25622installed, since they prefer them.
25623
25624@node Bootstrapping
25625@section How Can I Bootstrap?
25626@cindex Bootstrap
25627
25628@display
25629If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25630@command{configure} script, how do I bootstrap?  It seems like a chicken
25631and egg problem!
25632@end display
25633
25634This is a misunderstanding.  Although GNU M4 does come with a
25635@command{configure} script produced by Autoconf, Autoconf is not required
25636in order to run the script and install GNU M4.  Autoconf is only
25637required if you want to change the M4 @command{configure} script, which few
25638people have to do (mainly its maintainer).
25639
25640@node Why Not Imake
25641@section Why Not Imake?
25642@cindex Imake
25643
25644@display
25645Why not use Imake instead of @command{configure} scripts?
25646@end display
25647
25648Several people have written addressing this question, so
25649adaptations of their explanations are included here.
25650
25651The following answer is based on one written by Richard Pixley:
25652
25653@quotation
25654Autoconf generated scripts frequently work on machines that it has
25655never been set up to handle before.  That is, it does a good job of
25656inferring a configuration for a new system.  Imake cannot do this.
25657
25658Imake uses a common database of host specific data.  For X11, this makes
25659sense because the distribution is made as a collection of tools, by one
25660central authority who has control over the database.
25661
25662GNU tools are not released this way.  Each GNU tool has a
25663maintainer; these maintainers are scattered across the world.  Using a
25664common database would be a maintenance nightmare.  Autoconf may appear
25665to be this kind of database, but in fact it is not.  Instead of listing
25666host dependencies, it lists program requirements.
25667
25668If you view the GNU suite as a collection of native tools, then the
25669problems are similar.  But the GNU development tools can be
25670configured as cross tools in almost any host+target permutation.  All of
25671these configurations can be installed concurrently.  They can even be
25672configured to share host independent files across hosts.  Imake doesn't
25673address these issues.
25674
25675Imake templates are a form of standardization.  The GNU coding
25676standards address the same issues without necessarily imposing the same
25677restrictions.
25678@end quotation
25679
25680
25681Here is some further explanation, written by Per Bothner:
25682
25683@quotation
25684One of the advantages of Imake is that it is easy to generate large
25685makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25686However, @code{cpp} is not programmable: it has limited conditional
25687facilities, and no looping.  And @code{cpp} cannot inspect its
25688environment.
25689
25690All of these problems are solved by using @code{sh} instead of
25691@code{cpp}.  The shell is fully programmable, has macro substitution,
25692can execute (or source) other shell scripts, and can inspect its
25693environment.
25694@end quotation
25695
25696
25697Paul Eggert elaborates more:
25698
25699@quotation
25700With Autoconf, installers need not assume that Imake itself is already
25701installed and working well.  This may not seem like much of an advantage
25702to people who are accustomed to Imake.  But on many hosts Imake is not
25703installed or the default installation is not working well, and requiring
25704Imake to install a package hinders the acceptance of that package on
25705those hosts.  For example, the Imake template and configuration files
25706might not be installed properly on a host, or the Imake build procedure
25707might wrongly assume that all source files are in one big directory
25708tree, or the Imake configuration might assume one compiler whereas the
25709package or the installer needs to use another, or there might be a
25710version mismatch between the Imake expected by the package and the Imake
25711supported by the host.  These problems are much rarer with Autoconf,
25712where each package comes with its own independent configuration
25713processor.
25714
25715Also, Imake often suffers from unexpected interactions between
25716@command{make} and the installer's C preprocessor.  The fundamental problem
25717here is that the C preprocessor was designed to preprocess C programs,
25718not makefiles.  This is much less of a problem with Autoconf,
25719which uses the general-purpose preprocessor M4, and where the
25720package's author (rather than the installer) does the preprocessing in a
25721standard way.
25722@end quotation
25723
25724
25725Finally, Mark Eichin notes:
25726
25727@quotation
25728Imake isn't all that extensible, either.  In order to add new features to
25729Imake, you need to provide your own project template, and duplicate most
25730of the features of the existing one.  This means that for a sophisticated
25731project, using the vendor-provided Imake templates fails to provide any
25732leverage---since they don't cover anything that your own project needs
25733(unless it is an X11 program).
25734
25735On the other side, though:
25736
25737The one advantage that Imake has over @command{configure}:
25738@file{Imakefile} files tend to be much shorter (likewise, less redundant)
25739than @file{Makefile.in} files.  There is a fix to this, however---at least
25740for the Kerberos V5 tree, we've modified things to call in common
25741@file{post.in} and @file{pre.in} makefile fragments for the
25742entire tree.  This means that a lot of common things don't have to be
25743duplicated, even though they normally are in @command{configure} setups.
25744@end quotation
25745
25746
25747@node Defining Directories
25748@section How Do I @code{#define} Installation Directories?
25749
25750@display
25751My program needs library files, installed in @code{datadir} and
25752similar.  If I use
25753
25754@example
25755AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
25756  [Define to the read-only architecture-independent
25757   data directory.])
25758@end example
25759
25760@noindent
25761I get
25762
25763@example
25764#define DATADIR "$@{prefix@}/share"
25765@end example
25766@end display
25767
25768As already explained, this behavior is on purpose, mandated by the
25769GNU Coding Standards, see @ref{Installation Directory
25770Variables}.  There are several means to achieve a similar goal:
25771
25772@itemize @minus
25773@item
25774Do not use @code{AC_DEFINE} but use your makefile to pass the
25775actual value of @code{datadir} via compilation flags.
25776@xref{Installation Directory Variables}, for the details.
25777
25778@item
25779This solution can be simplified when compiling a program: you may either
25780extend the @code{CPPFLAGS}:
25781
25782@example
25783CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
25784@end example
25785
25786@noindent
25787If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
25788
25789@example
25790AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
25791@end example
25792
25793@noindent
25794Alternatively, create a dedicated header file:
25795
25796@example
25797DISTCLEANFILES = myprog-paths.h
25798myprog-paths.h: Makefile
25799        echo '#define DATADIR "$(datadir)"' >$@@
25800@end example
25801
25802@noindent
25803The gnulib module @samp{configmake} provides such a header with all the
25804standard directory variables defined, @pxref{configmake,,, gnulib, GNU
25805Gnulib}.
25806
25807@item
25808Use @code{AC_DEFINE} but have @command{configure} compute the literal
25809value of @code{datadir} and others.  Many people have wrapped macros to
25810automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
25811the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
25812Archive}.
25813
25814This solution does not conform to the GNU Coding Standards.
25815
25816@item
25817Note that all the previous solutions hard wire the absolute name of
25818these directories in the executables, which is not a good property.  You
25819may try to compute the names relative to @code{prefix}, and try to
25820find @code{prefix} at runtime, this way your package is relocatable.
25821@end itemize
25822
25823
25824@node Autom4te Cache
25825@section What is @file{autom4te.cache}?
25826
25827@display
25828What is this directory @file{autom4te.cache}?  Can I safely remove it?
25829@end display
25830
25831In the GNU Build System, @file{configure.ac} plays a central
25832role and is read by many tools: @command{autoconf} to create
25833@file{configure}, @command{autoheader} to create @file{config.h.in},
25834@command{automake} to create @file{Makefile.in}, @command{autoscan} to
25835check the completeness of @file{configure.ac}, @command{autoreconf} to
25836check the GNU Build System components that are used.  To
25837``read @file{configure.ac}'' actually means to compile it with M4,
25838which can be a long process for complex @file{configure.ac}.
25839
25840This is why all these tools, instead of running directly M4, invoke
25841@command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
25842a specific demand, stores additional information in
25843@file{autom4te.cache} for future runs.  For instance, if you run
25844@command{autoconf}, behind the scenes, @command{autom4te} also
25845stores information for the other tools, so that when you invoke
25846@command{autoheader} or @command{automake} etc., reprocessing
25847@file{configure.ac} is not needed.  The speed up is frequently 30%,
25848and is increasing with the size of @file{configure.ac}.
25849
25850But it is and remains being simply a cache: you can safely remove it.
25851
25852@sp 1
25853
25854@display
25855Can I permanently get rid of it?
25856@end display
25857
25858The creation of this cache can be disabled from
25859@file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
25860details.  You should be aware that disabling the cache slows down the
25861Autoconf test suite by 40%.  The more GNU Build System
25862components are used, the more the cache is useful; for instance
25863running @samp{autoreconf -f} on the Core Utilities is twice slower without
25864the cache @emph{although @option{--force} implies that the cache is
25865not fully exploited}, and eight times slower than without
25866@option{--force}.
25867
25868
25869@node Present But Cannot Be Compiled
25870@section Header Present But Cannot Be Compiled
25871
25872The most important guideline to bear in mind when checking for
25873features is to mimic as much as possible the intended use.
25874Unfortunately, old versions of @code{AC_CHECK_HEADER} and
25875@code{AC_CHECK_HEADERS} failed to follow this idea, and called
25876the preprocessor, instead of the compiler, to check for headers.  As a
25877result, incompatibilities between headers went unnoticed during
25878configuration, and maintainers finally had to deal with this issue
25879elsewhere.
25880
25881The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
25882checks are performed, and @command{configure} complains loudly if the
25883compiler and the preprocessor do not agree.  However, only the compiler
25884result is considered.
25885
25886Consider the following example:
25887
25888@smallexample
25889$ @kbd{cat number.h}
25890typedef int number;
25891$ @kbd{cat pi.h}
25892const number pi = 3;
25893$ @kbd{cat configure.ac}
25894AC_INIT([Example], [1.0], [bug-example@@example.org])
25895AC_CHECK_HEADERS([pi.h])
25896$ @kbd{autoconf -Wall}
25897$ @kbd{./configure}
25898checking for gcc... gcc
25899checking for C compiler default output file name... a.out
25900checking whether the C compiler works... yes
25901checking whether we are cross compiling... no
25902checking for suffix of executables...
25903checking for suffix of object files... o
25904checking whether we are using the GNU C compiler... yes
25905checking whether gcc accepts -g... yes
25906checking for gcc option to accept ISO C89... none needed
25907checking how to run the C preprocessor... gcc -E
25908checking for grep that handles long lines and -e... grep
25909checking for egrep... grep -E
25910checking for ANSI C header files... yes
25911checking for sys/types.h... yes
25912checking for sys/stat.h... yes
25913checking for stdlib.h... yes
25914checking for string.h... yes
25915checking for memory.h... yes
25916checking for strings.h... yes
25917checking for inttypes.h... yes
25918checking for stdint.h... yes
25919checking for unistd.h... yes
25920checking pi.h usability... no
25921checking pi.h presence... yes
25922configure: WARNING: pi.h: present but cannot be compiled
25923configure: WARNING: pi.h:     check for missing prerequisite headers?
25924configure: WARNING: pi.h: see the Autoconf documentation
25925configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
25926configure: WARNING: pi.h: proceeding with the compiler's result
25927configure: WARNING:     ## -------------------------------------- ##
25928configure: WARNING:     ## Report this to bug-example@@example.org ##
25929configure: WARNING:     ## -------------------------------------- ##
25930checking for pi.h... yes
25931@end smallexample
25932
25933@noindent
25934The proper way the handle this case is using the fourth argument
25935(@pxref{Generic Headers}):
25936
25937@example
25938$ @kbd{cat configure.ac}
25939AC_INIT([Example], [1.0], [bug-example@@example.org])
25940AC_CHECK_HEADERS([number.h pi.h], [], [],
25941[[#ifdef HAVE_NUMBER_H
25942# include <number.h>
25943#endif
25944]])
25945$ @kbd{autoconf -Wall}
25946$ @kbd{./configure}
25947checking for gcc... gcc
25948checking for C compiler default output... a.out
25949checking whether the C compiler works... yes
25950checking whether we are cross compiling... no
25951checking for suffix of executables...
25952checking for suffix of object files... o
25953checking whether we are using the GNU C compiler... yes
25954checking whether gcc accepts -g... yes
25955checking for gcc option to accept ANSI C... none needed
25956checking for number.h... yes
25957checking for pi.h... yes
25958@end example
25959
25960See @ref{Particular Headers}, for a list of headers with their
25961prerequisites.
25962
25963@node Expanded Before Required
25964@section Expanded Before Required
25965
25966@cindex expanded before required
25967Older versions of Autoconf silently built files with incorrect ordering
25968between dependent macros if an outer macro first expanded, then later
25969indirectly required, an inner macro.  Starting with Autoconf 2.64, this
25970situation no longer generates out-of-order code, but results in
25971duplicate output and a syntax warning:
25972
25973@example
25974$ @kbd{cat configure.ac}
25975@result{}AC_DEFUN([TESTA], [[echo in A
25976@result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
25977@result{}SEEN_A=:]])
25978@result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
25979@result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
25980@result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
25981@result{}AC_DEFUN([OUTER], [[echo in OUTER]
25982@result{}TESTA
25983@result{}TESTC])
25984@result{}AC_INIT
25985@result{}OUTER
25986@result{}AC_OUTPUT
25987$ @kbd{autoconf}
25988@result{}configure.ac:11: warning: AC_REQUIRE:
25989@result{} `TESTA' was expanded before it was required
25990@result{}configure.ac:4: TESTB is expanded from...
25991@result{}configure.ac:6: TESTC is expanded from...
25992@result{}configure.ac:7: OUTER is expanded from...
25993@result{}configure.ac:11: the top level
25994@end example
25995
25996@noindent
25997To avoid this warning, decide what purpose the macro in question serves.
25998If it only needs to be expanded once (for example, if it provides
25999initialization text used by later macros), then the simplest fix is to
26000change the macro to be declared with @code{AC_DEFUN_ONCE}
26001(@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26002newer.  A more portable fix is to change all
26003instances of direct calls to instead go through @code{AC_REQUIRE}
26004(@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26005by arguments or by the current definition of other macros in the m4
26006environment, then the macro should always be directly expanded instead
26007of required.
26008
26009For another case study, consider this example trimmed down from an
26010actual package.  Originally, the package contained shell code and
26011multiple macro invocations at the top level of @file{configure.ac}:
26012
26013@example
26014AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26015foobar=
26016AC_PROG_CC
26017FOO
26018@end example
26019
26020@noindent
26021but that was getting complex, so the author wanted to offload some of
26022the text into a new macro in another file included via
26023@file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26024macro:
26025
26026@example
26027AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26028AC_DEFUN([BAR], [
26029foobar=
26030AC_PROG_CC
26031FOO
26032])
26033BAR
26034@end example
26035
26036@noindent
26037With older versions of Autoconf, the setting of @samp{foobar=} occurs
26038before the single compiler check, as the author intended.  But with
26039Autoconf 2.64, this issues the ``expanded before it was required''
26040warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26041check, one before @samp{foobar=}, and one after.  To understand why this
26042is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26043a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26044the documented semantics of @code{AC_REQUIRE}, this means that
26045@code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26046@code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26047use of @samp{foobar=}.  The older versions of Autoconf were broken with
26048regards to the rules of @code{AC_REQUIRE}, which explains why the code
26049changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26050autoconf.  In other words, the author was unknowingly relying on a bug
26051exploit to get the desired results, and that exploit broke once the bug
26052was fixed.
26053
26054So, what recourse does the author have, to restore their intended
26055semantics of setting @samp{foobar=} prior to a single compiler check,
26056regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26057remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26058there is always the possibility of using the lower-level
26059@code{m4_define}:
26060
26061@example
26062AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26063m4_define([BAR], [
26064foobar=
26065AC_PROG_CC
26066FOO
26067])
26068BAR
26069@end example
26070
26071@noindent
26072This works great if everything is in the same file.  However, it does
26073not help in the case where the author wants to have @command{aclocal}
26074find the definition of @code{BAR} from its own file, since
26075@command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26076better fix is to recognize that if @code{BAR} also uses
26077@code{AC_REQUIRE}, then there will no longer be direct expansion prior
26078to a subsequent require.  Then, by creating yet another helper macro,
26079the author can once again guarantee a single invocation of
26080@code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26081author can also use @code{AC_BEFORE} to make sure no other macro
26082appearing before @code{BAR} has triggered an unwanted expansion of
26083@code{AC_PROG_CC}.
26084
26085@example
26086AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26087AC_DEFUN([BEFORE_CC], [
26088foobar=
26089])
26090AC_DEFUN([BAR], [
26091AC_BEFORE([$0], [AC_PROG_CC])dnl
26092AC_REQUIRE([BEFORE_CC])dnl
26093AC_REQUIRE([AC_PROG_CC])dnl
26094FOO
26095])
26096BAR
26097@end example
26098
26099
26100@node Debugging
26101@section Debugging @command{configure} scripts
26102
26103While in general, @command{configure} scripts generated by Autoconf
26104strive to be fairly portable to various systems, compilers, shells, and
26105other tools, it may still be necessary to debug a failing test, broken
26106script or makefile, or fix or override an incomplete, faulty, or erroneous
26107test, especially during macro development.  Failures can occur at all levels,
26108in M4 syntax or semantics, shell script issues, or due to bugs in the
26109test or the tools invoked by @command{configure}.  Together with the
26110rather arcane error message that @command{m4} and @command{make} may
26111produce when their input contains syntax errors, this can make debugging
26112rather painful.
26113
26114Nevertheless, here is a list of hints and strategies that may help:
26115
26116@itemize
26117@item
26118When @command{autoconf} fails, common causes for error include:
26119
26120@itemize
26121@item
26122mismatched or unbalanced parentheses or braces (@pxref{Balancing
26123Parentheses}),
26124
26125@item under- or overquoted macro arguments (@pxref{Autoconf
26126Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26127Macros}),
26128
26129@item spaces between macro name and opening parenthesis (@pxref{Autoconf
26130Language}).
26131@end itemize
26132
26133Typically, it helps to go back to the last working version of the input
26134and compare the differences for each of these errors.  Another
26135possibility is to sprinkle pairs of @code{m4_traceon} and
26136@code{m4_traceoff} judiciously in the code, either without a parameter
26137or listing some macro names and watch @command{m4} expand its input
26138verbosely (@pxref{Debugging via autom4te}).
26139
26140@item
26141Sometimes @command{autoconf} succeeds but the generated
26142@command{configure} script has invalid shell syntax.  You can detect this
26143case by running @samp{bash -n configure} or @samp{sh -n configure}.
26144If this command fails, the same tips apply, as if @command{autoconf} had
26145failed.
26146
26147@item
26148Debugging @command{configure} script execution may be done by sprinkling
26149pairs of @code{set -x} and @code{set +x} into the shell script before
26150and after the region that contains a bug.  Running the whole script with
26151@samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26152@var{shell} may work, but produces lots of output.  Here, it can help to
26153search for markers like @samp{checking for} a particular test in the
26154@var{log-file}.
26155
26156@item
26157Alternatively, you might use a shell with debugging capabilities like
26158@uref{http://bashdb.sourceforge.net/, bashdb}.
26159
26160@item
26161When @command{configure} tests produce invalid results for your system,
26162it may be necessary to override them:
26163
26164@itemize
26165@item
26166For programs, tools or libraries variables, preprocessor, compiler, or
26167linker flags, it is often sufficient to override them at @command{make}
26168run time with some care (@pxref{Macros and Submakes}).  Since this
26169normally won't cause @command{configure} to be run again with these
26170changed settings, it may fail if the changed variable would have caused
26171different test results from @command{configure}, so this may work only
26172for simple differences.
26173
26174@item
26175Most tests which produce their result in a substituted variable allow to
26176override the test by setting the variable on the @command{configure}
26177command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26178@pxref{Particular Systems}).
26179
26180@item
26181Many tests store their result in a cache variable (@pxref{Caching
26182Results}).  This lets you override them either on the
26183@command{configure} command line as above, or through a primed cache or
26184site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26185cache variable is documented with a test macro or may be inferred from
26186@ref{Cache Variable Names}; the precise semantics of undocumented
26187variables are often internal details, subject to change.
26188@end itemize
26189
26190@item
26191Alternatively, @command{configure} may produce invalid results because
26192of uncaught programming errors, in your package or in an upstream
26193library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26194library with a specified function, always check @file{config.log}.  This
26195will reveal the exact error that produced the failing result: the
26196library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26197@end itemize
26198
26199Conversely, as macro author, you can make it easier for users of your
26200macro:
26201
26202@itemize
26203@item
26204by minimizing dependencies between tests and between test results as far
26205as possible,
26206
26207@item
26208by using @command{make} variables to factorize and allow
26209override of settings at @command{make} run time,
26210
26211@item
26212by honoring the GNU Coding Standards and not overriding flags
26213reserved for the user except temporarily during @command{configure}
26214tests,
26215
26216@item
26217by not requiring users of your macro to use the cache variables.
26218Instead, expose the result of the test via @var{run-if-true} and
26219@var{run-if-false} parameters.  If the result is not a boolean,
26220then provide it through documented shell variables.
26221@end itemize
26222
26223
26224@c ===================================================== History of Autoconf.
26225
26226@node History
26227@chapter History of Autoconf
26228@cindex History of autoconf
26229
26230@emph{This chapter was written by the original author, David MacKenzie.}
26231
26232You may be wondering, Why was Autoconf originally written?  How did it
26233get into its present form?  (Why does it look like gorilla spit?)  If
26234you're not wondering, then this chapter contains no information useful
26235to you, and you might as well skip it.  If you @emph{are} wondering,
26236then let there be light@enddots{}
26237
26238@menu
26239* Genesis::                     Prehistory and naming of @command{configure}
26240* Exodus::                      The plagues of M4 and Perl
26241* Leviticus::                   The priestly code of portability arrives
26242* Numbers::                     Growth and contributors
26243* Deuteronomy::                 Approaching the promises of easy configuration
26244@end menu
26245
26246@node Genesis
26247@section Genesis
26248
26249In June 1991 I was maintaining many of the GNU utilities for the
26250Free Software Foundation.  As they were ported to more platforms and
26251more programs were added, the number of @option{-D} options that users
26252had to select in the makefile (around 20) became burdensome.
26253Especially for me---I had to test each new release on a bunch of
26254different systems.  So I wrote a little shell script to guess some of
26255the correct settings for the fileutils package, and released it as part
26256of fileutils 2.0.  That @command{configure} script worked well enough that
26257the next month I adapted it (by hand) to create similar @command{configure}
26258scripts for several other GNU utilities packages.  Brian Berliner
26259also adapted one of my scripts for his CVS revision control system.
26260
26261Later that summer, I learned that Richard Stallman and Richard Pixley
26262were developing similar scripts to use in the GNU compiler tools;
26263so I adapted my @command{configure} scripts to support their evolving
26264interface: using the file name @file{Makefile.in} as the templates;
26265adding @samp{+srcdir}, the first option (of many); and creating
26266@file{config.status} files.
26267
26268@node Exodus
26269@section Exodus
26270
26271As I got feedback from users, I incorporated many improvements, using
26272Emacs to search and replace, cut and paste, similar changes in each of
26273the scripts.  As I adapted more GNU utilities packages to use
26274@command{configure} scripts, updating them all by hand became impractical.
26275Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26276mail saying that the @command{configure} scripts were great, and asking if
26277I had a tool for generating them that I could send him.  No, I thought,
26278but I should!  So I started to work out how to generate them.  And the
26279journey from the slavery of hand-written @command{configure} scripts to the
26280abundance and ease of Autoconf began.
26281
26282Cygnus @command{configure}, which was being developed at around that time,
26283is table driven; it is meant to deal mainly with a discrete number of
26284system types with a small number of mainly unguessable features (such as
26285details of the object file format).  The automatic configuration system
26286that Brian Fox had developed for Bash takes a similar approach.  For
26287general use, it seems to me a hopeless cause to try to maintain an
26288up-to-date database of which features each variant of each operating
26289system has.  It's easier and more reliable to check for most features on
26290the fly---especially on hybrid systems that people have hacked on
26291locally or that have patches from vendors installed.
26292
26293I considered using an architecture similar to that of Cygnus
26294@command{configure}, where there is a single @command{configure} script that
26295reads pieces of @file{configure.in} when run.  But I didn't want to have
26296to distribute all of the feature tests with every package, so I settled
26297on having a different @command{configure} made from each
26298@file{configure.in} by a preprocessor.  That approach also offered more
26299control and flexibility.
26300
26301I looked briefly into using the Metaconfig package, by Larry Wall,
26302Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26303reasons.  The @command{Configure} scripts it produces are interactive,
26304which I find quite inconvenient; I didn't like the ways it checked for
26305some features (such as library functions); I didn't know that it was
26306still being maintained, and the @command{Configure} scripts I had
26307seen didn't work on many modern systems (such as System V R4 and NeXT);
26308it wasn't flexible in what it could do in response to a feature's
26309presence or absence; I found it confusing to learn; and it was too big
26310and complex for my needs (I didn't realize then how much Autoconf would
26311eventually have to grow).
26312
26313I considered using Perl to generate my style of @command{configure}
26314scripts, but decided that M4 was better suited to the job of simple
26315textual substitutions: it gets in the way less, because output is
26316implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26317the GNU extensions to M4.)  Also, some of my friends at the
26318University of Maryland had recently been putting M4 front ends on
26319several programs, including @code{tvtwm}, and I was interested in trying
26320out a new language.
26321
26322@node Leviticus
26323@section Leviticus
26324
26325Since my @command{configure} scripts determine the system's capabilities
26326automatically, with no interactive user intervention, I decided to call
26327the program that generates them Autoconfig.  But with a version number
26328tacked on, that name would be too long for old Unix file systems,
26329so I shortened it to Autoconf.
26330
26331In the fall of 1991 I called together a group of fellow questers after
26332the Holy Grail of portability (er, that is, alpha testers) to give me
26333feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26334and continued to add features and improve the techniques used in the
26335checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26336with the idea of making an Autoconf shell script to run M4
26337and check for unresolved macro calls; Richard Pixley, who suggested
26338running the compiler instead of searching the file system to find
26339include files and symbols, for more accurate results; Karl Berry, who
26340got Autoconf to configure @TeX{} and added the macro index to the
26341documentation; and Ian Lance Taylor, who added support for creating a C
26342header file as an alternative to putting @option{-D} options in a
26343makefile, so he could use Autoconf for his UUCP package.
26344The alpha testers cheerfully adjusted their files again and again as the
26345names and calling conventions of the Autoconf macros changed from
26346release to release.  They all contributed many specific checks, great
26347ideas, and bug fixes.
26348
26349@node Numbers
26350@section Numbers
26351
26352In July 1992, after months of alpha testing, I released Autoconf 1.0,
26353and converted many GNU packages to use it.  I was surprised by how
26354positive the reaction to it was.  More people started using it than I
26355could keep track of, including people working on software that wasn't
26356part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26357Autoconf continued to improve rapidly, as many people using the
26358@command{configure} scripts reported problems they encountered.
26359
26360Autoconf turned out to be a good torture test for M4 implementations.
26361Unix M4 started to dump core because of the length of the
26362macros that Autoconf defined, and several bugs showed up in GNU
26363M4 as well.  Eventually, we realized that we needed to use some
26364features that only GNU M4 has.  4.3BSD M4, in
26365particular, has an impoverished set of builtin macros; the System V
26366version is better, but still doesn't provide everything we need.
26367
26368More development occurred as people put Autoconf under more stresses
26369(and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26370david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26371invalid arguments.  Jim Blandy bravely coerced it into configuring
26372GNU Emacs, laying the groundwork for several later improvements.
26373Roland McGrath got it to configure the GNU C Library, wrote the
26374@command{autoheader} script to automate the creation of C header file
26375templates, and added a @option{--verbose} option to @command{configure}.
26376Noah Friedman added the @option{--autoconf-dir} option and
26377@code{AC_MACRODIR} environment variable.  (He also coined the term
26378@dfn{autoconfiscate} to mean ``adapt a software package to use
26379Autoconf''.)  Roland and Noah improved the quoting protection in
26380@code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26381dealing with portability problems from February through June, 1993.
26382
26383@node Deuteronomy
26384@section Deuteronomy
26385
26386A long wish list for major features had accumulated, and the effect of
26387several years of patching by various people had left some residual
26388cruft.  In April 1994, while working for Cygnus Support, I began a major
26389revision of Autoconf.  I added most of the features of the Cygnus
26390@command{configure} that Autoconf had lacked, largely by adapting the
26391relevant parts of Cygnus @command{configure} with the help of david zuhn
26392and Ken Raeburn.  These features include support for using
26393@file{config.sub}, @file{config.guess}, @option{--host}, and
26394@option{--target}; making links to files; and running @command{configure}
26395scripts in subdirectories.  Adding these features enabled Ken to convert
26396GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26397Autoconf.
26398
26399I added more features in response to other peoples' requests.  Many
26400people had asked for @command{configure} scripts to share the results of
26401the checks between runs, because (particularly when configuring a large
26402source tree, like Cygnus does) they were frustratingly slow.  Mike
26403Haertel suggested adding site-specific initialization scripts.  People
26404distributing software that had to unpack on MS-DOS asked for a way to
26405override the @file{.in} extension on the file names, which produced file
26406names like @file{config.h.in} containing two dots.  Jim Avera did an
26407extensive examination of the problems with quoting in @code{AC_DEFINE}
26408and @code{AC_SUBST}; his insights led to significant improvements.
26409Richard Stallman asked that compiler output be sent to @file{config.log}
26410instead of @file{/dev/null}, to help people debug the Emacs
26411@command{configure} script.
26412
26413I made some other changes because of my dissatisfaction with the quality
26414of the program.  I made the messages showing results of the checks less
26415ambiguous, always printing a result.  I regularized the names of the
26416macros and cleaned up coding style inconsistencies.  I added some
26417auxiliary utilities that I had developed to help convert source code
26418packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26419the macros not interrupt each others' messages.  (That feature revealed
26420some performance bottlenecks in GNU M4, which he hastily
26421corrected!)  I reorganized the documentation around problems people want
26422to solve.  And I began a test suite, because experience had shown that
26423Autoconf has a pronounced tendency to regress when we change it.
26424
26425Again, several alpha testers gave invaluable feedback, especially
26426Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26427and Mark Eichin.
26428
26429Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26430have free time again.  I think.  Yeah, right.)
26431
26432
26433@c ========================================================== Appendices
26434
26435
26436@node GNU Free Documentation License
26437@appendix GNU Free Documentation License
26438
26439@include fdl.texi
26440
26441@node Indices
26442@appendix Indices
26443
26444@menu
26445* Environment Variable Index::  Index of environment variables used
26446* Output Variable Index::       Index of variables set in output files
26447* Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26448* Cache Variable Index::        Index of documented cache variables
26449* Autoconf Macro Index::        Index of Autoconf macros
26450* M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26451* Autotest Macro Index::        Index of Autotest macros
26452* Program & Function Index::    Index of those with portability problems
26453* Concept Index::               General index
26454@end menu
26455
26456@node Environment Variable Index
26457@appendixsec Environment Variable Index
26458
26459This is an alphabetical list of the environment variables that might
26460influence Autoconf checks.
26461
26462@printindex ev
26463
26464@node Output Variable Index
26465@appendixsec Output Variable Index
26466
26467This is an alphabetical list of the variables that Autoconf can
26468substitute into files that it creates, typically one or more
26469makefiles.  @xref{Setting Output Variables}, for more information
26470on how this is done.
26471
26472@printindex ov
26473
26474@node Preprocessor Symbol Index
26475@appendixsec Preprocessor Symbol Index
26476
26477This is an alphabetical list of the C preprocessor symbols that the
26478Autoconf macros define.  To work with Autoconf, C source code needs to
26479use these names in @code{#if} or @code{#ifdef} directives.
26480
26481@printindex cv
26482
26483@node Cache Variable Index
26484@appendixsec Cache Variable Index
26485
26486This is an alphabetical list of documented cache variables used
26487by macros defined in Autoconf.  Autoconf macros may use additional cache
26488variables internally.
26489@ifset shortindexflag
26490To make the list easier to use, the variables are listed without their
26491preceding @samp{ac_cv_}.
26492@end ifset
26493
26494@printindex CA
26495
26496@node Autoconf Macro Index
26497@appendixsec Autoconf Macro Index
26498
26499This is an alphabetical list of the Autoconf macros.
26500@ifset shortindexflag
26501To make the list easier to use, the macros are listed without their
26502preceding @samp{AC_}.
26503@end ifset
26504
26505@printindex AC
26506
26507@node M4 Macro Index
26508@appendixsec M4 Macro Index
26509
26510This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26511@ifset shortindexflag
26512To make the list easier to use, the macros are listed without their
26513preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26514all-lowercase macro names and @samp{AS_} for all-uppercase macro
26515names.
26516@end ifset
26517
26518@printindex MS
26519
26520@node Autotest Macro Index
26521@appendixsec Autotest Macro Index
26522
26523This is an alphabetical list of the Autotest macros.
26524@ifset shortindexflag
26525To make the list easier to use, the macros are listed without their
26526preceding @samp{AT_}.
26527@end ifset
26528
26529@printindex AT
26530
26531@node Program & Function Index
26532@appendixsec Program and Function Index
26533
26534This is an alphabetical list of the programs and functions whose
26535portability is discussed in this document.
26536
26537@printindex pr
26538
26539@node Concept Index
26540@appendixsec Concept Index
26541
26542This is an alphabetical list of the files, tools, and concepts
26543introduced in this document.
26544
26545@printindex cp
26546
26547@bye
26548
26549@c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26550@c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26551@c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26552@c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26553@c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26554@c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26555@c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26556@c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26557@c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26558@c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26559@c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26560@c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26561@c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26562@c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26563@c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26564@c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26565@c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26566@c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26567@c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26568@c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26569@c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26570@c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26571@c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26572@c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26573@c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26574@c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26575@c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26576@c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26577@c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26578@c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26579@c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26580@c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26581@c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26582@c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26583@c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26584@c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26585@c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26586@c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26587@c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26588@c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26589@c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26590@c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26591@c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26592@c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26593@c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26594@c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm
26595@c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26596@c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26597@c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26598@c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26599@c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26600@c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26601@c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26602@c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26603@c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26604@c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26605@c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26606@c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26607@c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26608@c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26609@c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26610@c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26611@c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26612@c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26613@c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26614@c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26615@c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26616@c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26617@c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26618@c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26619@c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26620@c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26621@c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26622@c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26623@c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26624@c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26625@c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26626@c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26627@c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26628@c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26629@c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26630@c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26631@c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26632@c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26633@c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26634@c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26635@c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26636@c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26637@c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26638@c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26639@c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck
26640@c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26641
26642@c Local Variables:
26643@c fill-column: 72
26644@c ispell-local-dictionary: "american"
26645@c indent-tabs-mode: nil
26646@c whitespace-check-buffer-indent: nil
26647@c End:
26648