1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
9 @setcontentsaftertitlepage
15 @c The ARG is an optional argument. To be used for macro arguments in
16 @c their documentation (@defmac).
18 @r{[}@var{\varname\}@r{]}@c
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT. To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc. That's why we first define indexes such as
34 @c acx meant to become the macro @acindex. First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''. Then you finish with a printed
37 @c index saying ``index is not existent''. Of course: you ought to use
38 @c two letters :( So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten. But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself. So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi. But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index.
51 @c Define an output variable index.
53 @c Define a CPP variable index.
55 @c Define a cache variable index.
57 @c Define an Autoconf macro index that @defmac doesn't write to.
59 @c Define an Autotest macro index that @defmac doesn't write to.
61 @c Define an M4sugar macro index that @defmac doesn't write to.
63 @c Define an index for *foreign* programs: `mv' etc. Used for the
64 @c portability sections and so on.
69 @c Shall we factor AC_ out of the Autoconf macro index etc.?
76 @c Registering an AC_\MACRO\.
83 @ifclear shortindexflag
91 @c Registering an AH_\MACRO\.
99 @c Registering an AS_\MACRO\.
100 @ifset shortindexflag
101 @macro asindex{macro}
106 @ifclear shortindexflag
107 @macro asindex{macro}
114 @c Registering an AT_\MACRO\.
115 @ifset shortindexflag
116 @macro atindex{macro}
121 @ifclear shortindexflag
122 @macro atindex{macro}
129 @c Registering an AU_\MACRO\.
130 @macro auindex{macro}
137 @c Indexing a header.
138 @macro hdrindex{macro}
139 @prindex @file{\macro\}
145 @c Registering an m4_\MACRO\.
146 @ifset shortindexflag
147 @macro msindex{macro}
152 @ifclear shortindexflag
153 @macro msindex{macro}
159 @c @caindex{VARIABLE}
160 @c ------------------
161 @c Registering an ac_cv_\VARIABLE\ cache variable.
162 @ifset shortindexflag
163 @macro caindex{macro}
167 @ifclear shortindexflag
168 @macro caindex{macro}
169 @CAindex ac_cv_\macro\
173 @c Define an index for functions: `alloca' etc. Used for the
174 @c portability sections and so on. We can't use `fn' (aka `fnindex),
175 @c since `@defmac' goes into it => we'd get all the macros too.
177 @c FIXME: Aaarg! It seems there are too many indices for TeX :(
179 @c ! No room for a new @write .
180 @c l.112 @defcodeindex fu
182 @c so don't define yet another one :( Just put some tags before each
183 @c @prindex which is actually a @funindex.
188 @c @c Put the programs and functions into their own index.
189 @c @syncodeindex fu pr
191 @comment %**end of header
192 @comment ========================================================
196 This manual (@value{UPDATED}) is for GNU Autoconf
197 (version @value{VERSION}),
198 a package for creating scripts to configure source code packages using
199 templates and an M4 macro package.
201 Copyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
202 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
206 Permission is granted to copy, distribute and/or modify this document
207 under the terms of the GNU Free Documentation License,
208 Version 1.3 or any later version published by the Free Software
209 Foundation; with no Invariant Sections, with the Front-Cover texts
210 being ``A GNU Manual,'' and with the Back-Cover Texts as in
211 (a) below. A copy of the license is included in the section entitled
212 ``GNU Free Documentation License.''
214 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
215 modify this GNU manual. Buying copies from the FSF
216 supports it in developing GNU and promoting software
223 @dircategory Software development
225 * Autoconf: (autoconf). Create source code configuration scripts.
228 @dircategory Individual utilities
230 * autoscan: (autoconf)autoscan Invocation.
231 Semi-automatic @file{configure.ac} writing
232 * ifnames: (autoconf)ifnames Invocation. Listing conditionals in source.
233 * autoconf-invocation: (autoconf)autoconf Invocation.
234 How to create configuration scripts
235 * autoreconf: (autoconf)autoreconf Invocation.
236 Remaking multiple @command{configure} scripts
237 * autoheader: (autoconf)autoheader Invocation.
238 How to create configuration templates
239 * autom4te: (autoconf)autom4te Invocation.
240 The Autoconf executables backbone
241 * configure: (autoconf)configure Invocation. Configuring a package.
242 * autoupdate: (autoconf)autoupdate Invocation.
243 Automatic update of @file{configure.ac}
244 * config.status: (autoconf)config.status Invocation. Recreating configurations.
245 * testsuite: (autoconf)testsuite Invocation. Running an Autotest test suite.
250 @subtitle Creating Automatic Configuration Scripts
251 @subtitle for version @value{VERSION}, @value{UPDATED}
252 @author David MacKenzie
254 @author Akim Demaille
256 @vskip 0pt plus 1filll
269 @c The master menu, created with texinfo-master-menu, goes here.
272 * Introduction:: Autoconf's purpose, strengths, and weaknesses
273 * The GNU Build System:: A set of tools for portable software packages
274 * Making configure Scripts:: How to organize and produce Autoconf scripts
275 * Setup:: Initialization and output
276 * Existing Tests:: Macros that check for particular features
277 * Writing Tests:: How to write new feature checks
278 * Results:: What to do with results from feature checks
279 * Programming in M4:: Layers on top of which Autoconf is written
280 * Programming in M4sh:: Shell portability layer
281 * Writing Autoconf Macros:: Adding new macros to Autoconf
282 * Portable Shell:: Shell script portability pitfalls
283 * Portable Make:: Makefile portability pitfalls
284 * Portable C and C++:: C and C++ portability pitfalls
285 * Manual Configuration:: Selecting features that can't be guessed
286 * Site Configuration:: Local defaults for @command{configure}
287 * Running configure Scripts:: How to use the Autoconf output
288 * config.status Invocation:: Recreating a configuration
289 * Obsolete Constructs:: Kept for backward compatibility
290 * Using Autotest:: Creating portable test suites
291 * FAQ:: Frequent Autoconf Questions, with answers
292 * History:: History of Autoconf
293 * GNU Free Documentation License:: License for copying this manual
294 * Indices:: Indices of symbols, concepts, etc.
297 --- The Detailed Node Listing ---
301 * Automake:: Escaping makefile hell
302 * Gnulib:: The GNU portability library
303 * Libtool:: Building libraries portably
304 * Pointers:: More info on the GNU build system
306 Making @command{configure} Scripts
308 * Writing Autoconf Input:: What to put in an Autoconf input file
309 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
310 * ifnames Invocation:: Listing the conditionals in source code
311 * autoconf Invocation:: How to create configuration scripts
312 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
314 Writing @file{configure.ac}
316 * Shell Script Compiler:: Autoconf as solution of a problem
317 * Autoconf Language:: Programming in Autoconf
318 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
320 Initialization and Output Files
322 * Initializing configure:: Option processing etc.
323 * Versioning:: Dealing with Autoconf versions
324 * Notices:: Copyright, version numbers in @command{configure}
325 * Input:: Where Autoconf should find files
326 * Output:: Outputting results from the configuration
327 * Configuration Actions:: Preparing the output based on results
328 * Configuration Files:: Creating output files
329 * Makefile Substitutions:: Using output variables in makefiles
330 * Configuration Headers:: Creating a configuration header file
331 * Configuration Commands:: Running arbitrary instantiation commands
332 * Configuration Links:: Links depending on the configuration
333 * Subdirectories:: Configuring independent packages together
334 * Default Prefix:: Changing the default installation prefix
336 Substitutions in Makefiles
338 * Preset Output Variables:: Output variables that are always set
339 * Installation Directory Variables:: Other preset output variables
340 * Changed Directory Variables:: Warnings about @file{datarootdir}
341 * Build Directories:: Supporting multiple concurrent compiles
342 * Automatic Remaking:: Makefile rules for configuring
344 Configuration Header Files
346 * Header Templates:: Input for the configuration headers
347 * autoheader Invocation:: How to create configuration templates
348 * Autoheader Macros:: How to specify CPP templates
352 * Common Behavior:: Macros' standard schemes
353 * Alternative Programs:: Selecting between alternative programs
354 * Files:: Checking for the existence of files
355 * Libraries:: Library archives that might be missing
356 * Library Functions:: C library functions that might be missing
357 * Header Files:: Header files that might be missing
358 * Declarations:: Declarations that may be missing
359 * Structures:: Structures or members that might be missing
360 * Types:: Types that might be missing
361 * Compilers and Preprocessors:: Checking for compiling programs
362 * System Services:: Operating system services
363 * Posix Variants:: Special kludges for specific Posix variants
364 * Erlang Libraries:: Checking for the existence of Erlang libraries
368 * Standard Symbols:: Symbols defined by the macros
369 * Default Includes:: Includes used by the generic macros
373 * Particular Programs:: Special handling to find certain programs
374 * Generic Programs:: How to find other programs
378 * Function Portability:: Pitfalls with usual functions
379 * Particular Functions:: Special handling to find certain functions
380 * Generic Functions:: How to find other functions
384 * Header Portability:: Collected knowledge on common headers
385 * Particular Headers:: Special handling to find certain headers
386 * Generic Headers:: How to find other headers
390 * Particular Declarations:: Macros to check for certain declarations
391 * Generic Declarations:: How to find other declarations
395 * Particular Structures:: Macros to check for certain structure members
396 * Generic Structures:: How to find other structure members
400 * Particular Types:: Special handling to find certain types
401 * Generic Types:: How to find other types
403 Compilers and Preprocessors
405 * Specific Compiler Characteristics:: Some portability issues
406 * Generic Compiler Characteristics:: Language independent tests and features
407 * C Compiler:: Checking its characteristics
408 * C++ Compiler:: Likewise
409 * Objective C Compiler:: Likewise
410 * Objective C++ Compiler:: Likewise
411 * Erlang Compiler and Interpreter:: Likewise
412 * Fortran Compiler:: Likewise
416 * Language Choice:: Selecting which language to use for testing
417 * Writing Test Programs:: Forging source files for compilers
418 * Running the Preprocessor:: Detecting preprocessor symbols
419 * Running the Compiler:: Detecting language or header features
420 * Running the Linker:: Detecting library features
421 * Runtime:: Testing for runtime features
422 * Systemology:: A zoology of operating systems
423 * Multiple Cases:: Tests for several possible values
425 Writing Test Programs
427 * Guidelines:: General rules for writing test programs
428 * Test Functions:: Avoiding pitfalls in test programs
429 * Generating Sources:: Source program boilerplate
433 * Defining Symbols:: Defining C preprocessor symbols
434 * Setting Output Variables:: Replacing variables in output files
435 * Special Chars in Variables:: Characters to beware of in variables
436 * Caching Results:: Speeding up subsequent @command{configure} runs
437 * Printing Messages:: Notifying @command{configure} users
441 * Cache Variable Names:: Shell variables used in caches
442 * Cache Files:: Files @command{configure} uses for caching
443 * Cache Checkpointing:: Loading and saving the cache file
447 * M4 Quotation:: Protecting macros from unwanted expansion
448 * Using autom4te:: The Autoconf executables backbone
449 * Programming in M4sugar:: Convenient pure M4 macros
450 * Debugging via autom4te:: Figuring out what M4 was doing
454 * Common Shell Constructs:: Portability layer for common shell constructs
455 * Polymorphic Variables:: Support for indirect variable names
456 * Initialization Macros:: Macros to establish a sane shell environment
457 * File Descriptor Macros:: File descriptor macros for input and output
461 * Active Characters:: Characters that change the behavior of M4
462 * One Macro Call:: Quotation and one macro call
463 * Quoting and Parameters:: M4 vs. shell parameters
464 * Quotation and Nested Macros:: Macros calling macros
465 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
466 * Quadrigraphs:: Another way to escape special characters
467 * Balancing Parentheses:: Dealing with unbalanced parentheses
468 * Quotation Rule Of Thumb:: One parenthesis, one quote
470 Using @command{autom4te}
472 * autom4te Invocation:: A GNU M4 wrapper
473 * Customizing autom4te:: Customizing the Autoconf package
475 Programming in M4sugar
477 * Redefined M4 Macros:: M4 builtins changed in M4sugar
478 * Diagnostic Macros:: Diagnostic messages from M4sugar
479 * Diversion support:: Diversions in M4sugar
480 * Conditional constructs:: Conditions in M4
481 * Looping constructs:: Iteration in M4
482 * Evaluation Macros:: More quotation and evaluation control
483 * Text processing Macros:: String manipulation in M4
484 * Number processing Macros:: Arithmetic computation in M4
485 * Set manipulation Macros:: Set manipulation in M4
486 * Forbidden Patterns:: Catching unexpanded macros
488 Writing Autoconf Macros
490 * Macro Definitions:: Basic format of an Autoconf macro
491 * Macro Names:: What to call your new macros
492 * Reporting Messages:: Notifying @command{autoconf} users
493 * Dependencies Between Macros:: What to do when macros depend on other macros
494 * Obsoleting Macros:: Warning about old ways of doing things
495 * Coding Style:: Writing Autoconf macros @`a la Autoconf
497 Dependencies Between Macros
499 * Prerequisite Macros:: Ensuring required information
500 * Suggested Ordering:: Warning about possible ordering problems
501 * One-Shot Macros:: Ensuring a macro is called only once
503 Portable Shell Programming
505 * Shellology:: A zoology of shells
506 * Here-Documents:: Quirks and tricks
507 * File Descriptors:: FDs and redirections
508 * File System Conventions:: File names
509 * Shell Pattern Matching:: Pattern matching
510 * Shell Substitutions:: Variable and command expansions
511 * Assignments:: Varying side effects of assignments
512 * Parentheses:: Parentheses in shell scripts
513 * Slashes:: Slashes in shell scripts
514 * Special Shell Variables:: Variables you should not change
515 * Shell Functions:: What to look out for if you use them
516 * Limitations of Builtins:: Portable use of not so portable /bin/sh
517 * Limitations of Usual Tools:: Portable use of portable tools
519 Portable Make Programming
521 * $< in Ordinary Make Rules:: $< in ordinary rules
522 * Failure in Make Rules:: Failing portably in rules
523 * Special Chars in Names:: Special Characters in Macro Names
524 * Backslash-Newline-Newline:: Empty last lines in macro definitions
525 * Backslash-Newline Comments:: Spanning comments across line boundaries
526 * Long Lines in Makefiles:: Line length limitations
527 * Macros and Submakes:: @code{make macro=value} and submakes
528 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
529 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
530 * Parallel Make:: Parallel @command{make} quirks
531 * Comments in Make Rules:: Other problems with Make comments
532 * obj/ and Make:: Don't name a subdirectory @file{obj}
533 * make -k Status:: Exit status of @samp{make -k}
534 * VPATH and Make:: @code{VPATH} woes
535 * Single Suffix Rules:: Single suffix rules and separated dependencies
536 * Timestamps and Make:: Subsecond timestamp resolution
538 @code{VPATH} and Make
540 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
541 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
542 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
543 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
544 * Tru64 Directory Magic:: @command{mkdir} goes wild on Tru64
545 * Make Target Lookup:: More details about @code{VPATH} lookup
547 Portable C and C++ Programming
549 * Varieties of Unportability:: How to make your programs unportable
550 * Integer Overflow:: When integers get too large
551 * Preprocessor Arithmetic:: @code{#if} expression problems
552 * Null Pointers:: Properties of null pointers
553 * Buffer Overruns:: Subscript errors and the like
554 * Volatile Objects:: @code{volatile} and signals
555 * Floating Point Portability:: Portable floating-point arithmetic
556 * Exiting Portably:: Exiting and the exit status
560 * Specifying Target Triplets:: Specifying target triplets
561 * Canonicalizing:: Getting the canonical system type
562 * Using System Type:: What to do with the system type
566 * Help Formatting:: Customizing @samp{configure --help}
567 * External Software:: Working with other optional software
568 * Package Options:: Selecting optional features
569 * Pretty Help Strings:: Formatting help string
570 * Option Checking:: Controlling checking of @command{configure} options
571 * Site Details:: Configuring site details
572 * Transforming Names:: Changing program names when installing
573 * Site Defaults:: Giving @command{configure} local defaults
575 Transforming Program Names When Installing
577 * Transformation Options:: @command{configure} options to transform names
578 * Transformation Examples:: Sample uses of transforming names
579 * Transformation Rules:: Makefile uses of transforming names
581 Running @command{configure} Scripts
583 * Basic Installation:: Instructions for typical cases
584 * Compilers and Options:: Selecting compilers and optimization
585 * Multiple Architectures:: Compiling for multiple architectures at once
586 * Installation Names:: Installing in different directories
587 * Optional Features:: Selecting optional features
588 * Particular Systems:: Particular systems
589 * System Type:: Specifying the system type
590 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
591 * Defining Variables:: Specifying the compiler etc.
592 * configure Invocation:: Changing how @command{configure} runs
596 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
597 * acconfig Header:: Additional entries in @file{config.h.in}
598 * autoupdate Invocation:: Automatic update of @file{configure.ac}
599 * Obsolete Macros:: Backward compatibility macros
600 * Autoconf 1:: Tips for upgrading your files
601 * Autoconf 2.13:: Some fresher tips
603 Upgrading From Version 1
605 * Changed File Names:: Files you might rename
606 * Changed Makefiles:: New things to put in @file{Makefile.in}
607 * Changed Macros:: Macro calls you might replace
608 * Changed Results:: Changes in how to check test results
609 * Changed Macro Writing:: Better ways to write your own macros
611 Upgrading From Version 2.13
613 * Changed Quotation:: Broken code which used to work
614 * New Macros:: Interaction with foreign macros
615 * Hosts and Cross-Compilation:: Bugward compatibility kludges
616 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
617 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
619 Generating Test Suites with Autotest
621 * Using an Autotest Test Suite:: Autotest and the user
622 * Writing Testsuites:: Autotest macros
623 * testsuite Invocation:: Running @command{testsuite} scripts
624 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
626 Using an Autotest Test Suite
628 * testsuite Scripts:: The concepts of Autotest
629 * Autotest Logs:: Their contents
631 Frequent Autoconf Questions, with answers
633 * Distributing:: Distributing @command{configure} scripts
634 * Why GNU M4:: Why not use the standard M4?
635 * Bootstrapping:: Autoconf and GNU M4 require each other?
636 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
637 * Defining Directories:: Passing @code{datadir} to program
638 * Autom4te Cache:: What is it? Can I remove it?
639 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
640 * Expanded Before Required:: Expanded Before Required
641 * Debugging:: Debugging @command{configure} scripts
645 * Genesis:: Prehistory and naming of @command{configure}
646 * Exodus:: The plagues of M4 and Perl
647 * Leviticus:: The priestly code of portability arrives
648 * Numbers:: Growth and contributors
649 * Deuteronomy:: Approaching the promises of easy configuration
653 * Environment Variable Index:: Index of environment variables used
654 * Output Variable Index:: Index of variables set in output files
655 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
656 * Cache Variable Index:: Index of documented cache variables
657 * Autoconf Macro Index:: Index of Autoconf macros
658 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
659 * Autotest Macro Index:: Index of Autotest macros
660 * Program & Function Index:: Index of those with portability problems
661 * Concept Index:: General index
666 @c ============================================================= Introduction.
669 @chapter Introduction
673 A physicist, an engineer, and a computer scientist were discussing the
674 nature of God. ``Surely a Physicist,'' said the physicist, ``because
675 early in the Creation, God made Light; and you know, Maxwell's
676 equations, the dual nature of electromagnetic waves, the relativistic
677 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
678 before making Light, God split the Chaos into Land and Water; it takes a
679 hell of an engineer to handle that big amount of mud, and orderly
680 separation of solids from liquids@enddots{}'' The computer scientist
681 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
685 @c (via Franc,ois Pinard)
687 Autoconf is a tool for producing shell scripts that automatically
688 configure software source code packages to adapt to many kinds of
689 Posix-like systems. The configuration scripts produced by Autoconf
690 are independent of Autoconf when they are run, so their users do not
691 need to have Autoconf.
693 The configuration scripts produced by Autoconf require no manual user
694 intervention when run; they do not normally even need an argument
695 specifying the system type. Instead, they individually test for the
696 presence of each feature that the software package they are for might need.
697 (Before each check, they print a one-line message stating what they are
698 checking for, so the user doesn't get too bored while waiting for the
699 script to finish.) As a result, they deal well with systems that are
700 hybrids or customized from the more common Posix variants. There is
701 no need to maintain files that list the features supported by each
702 release of each variant of Posix.
704 For each software package that Autoconf is used with, it creates a
705 configuration script from a template file that lists the system features
706 that the package needs or can use. After the shell code to recognize
707 and respond to a system feature has been written, Autoconf allows it to
708 be shared by many software packages that can use (or need) that feature.
709 If it later turns out that the shell code needs adjustment for some
710 reason, it needs to be changed in only one place; all of the
711 configuration scripts can be regenerated automatically to take advantage
714 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
715 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
716 Those who do not understand Autoconf are condemned to reinvent it, poorly.
717 The primary goal of Autoconf is making the @emph{user's} life easier;
718 making the @emph{maintainer's} life easier is only a secondary goal.
719 Put another way, the primary goal is not to make the generation of
720 @file{configure} automatic for package maintainers (although patches
721 along that front are welcome, since package maintainers form the user
722 base of Autoconf); rather, the goal is to make @file{configure}
723 painless, portable, and predictable for the end user of each
724 @dfn{autoconfiscated} package. And to this degree, Autoconf is highly
725 successful at its goal --- most complaints to the Autoconf list are
726 about difficulties in writing Autoconf input, and not in the behavior of
727 the resulting @file{configure}. Even packages that don't use Autoconf
728 will generally provide a @file{configure} script, and the most common
729 complaint about these alternative home-grown scripts is that they fail
730 to meet one or more of the GNU Coding Standards that users
731 have come to expect from Autoconf-generated @file{configure} scripts.
733 The Metaconfig package is similar in purpose to Autoconf, but the
734 scripts it produces require manual user intervention, which is quite
735 inconvenient when configuring large source trees. Unlike Metaconfig
736 scripts, Autoconf scripts can support cross-compiling, if some care is
737 taken in writing them.
739 Autoconf does not solve all problems related to making portable
740 software packages---for a more complete solution, it should be used in
741 concert with other GNU build tools like Automake and
742 Libtool. These other tools take on jobs like the creation of a
743 portable, recursive makefile with all of the standard targets,
744 linking of shared libraries, and so on. @xref{The GNU Build System},
745 for more information.
747 Autoconf imposes some restrictions on the names of macros used with
748 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
750 Autoconf requires GNU M4 version 1.4.6 or later in order to
751 generate the scripts. It uses features that some versions of M4,
752 including GNU M4 1.3, do not have. Autoconf works better
753 with GNU M4 version 1.4.14 or later, though this is not
756 @xref{Autoconf 1}, for information about upgrading from version 1.
757 @xref{History}, for the story of Autoconf's development. @xref{FAQ},
758 for answers to some common questions about Autoconf.
760 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
761 Autoconf web page} for up-to-date information, details on the mailing
762 lists, pointers to a list of known bugs, etc.
764 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
765 list}. Past suggestions are
766 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
768 Mail bug reports to @email{bug-autoconf@@gnu.org, the
769 Autoconf Bugs mailing list}. Past bug reports are
770 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
772 If possible, first check that your bug is
773 not already solved in current development versions, and that it has not
774 been reported yet. Be sure to include all the needed information and a
775 short @file{configure.ac} that demonstrates the problem.
777 Autoconf's development tree is accessible via @command{git}; see the
778 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
779 Summary} for details, or view
780 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
781 repository}. Anonymous CVS access is also available, see
782 @file{README} for more details. Patches relative to the
783 current @command{git} version can be sent for review to the
784 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
785 discussion on prior patches
786 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
787 archived}; and all commits are posted in the read-only
788 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
789 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
792 Because of its mission, the Autoconf package itself
793 includes only a set of often-used
794 macros that have already demonstrated their usefulness. Nevertheless,
795 if you wish to share your macros, or find existing ones, see the
796 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
797 Archive}, which is kindly run by @email{simons@@cryp.to,
801 @c ================================================= The GNU Build System
803 @node The GNU Build System
804 @chapter The GNU Build System
805 @cindex GNU build system
807 Autoconf solves an important problem---reliable discovery of
808 system-specific build and runtime information---but this is only one
809 piece of the puzzle for the development of portable software. To this
810 end, the GNU project has developed a suite of integrated
811 utilities to finish the job Autoconf started: the GNU build
812 system, whose most important components are Autoconf, Automake, and
813 Libtool. In this chapter, we introduce you to those tools, point you
814 to sources of more information, and try to convince you to use the
815 entire GNU build system for your software.
818 * Automake:: Escaping makefile hell
819 * Gnulib:: The GNU portability library
820 * Libtool:: Building libraries portably
821 * Pointers:: More info on the GNU build system
827 The ubiquity of @command{make} means that a makefile is almost the
828 only viable way to distribute automatic build rules for software, but
829 one quickly runs into its numerous limitations. Its lack of
830 support for automatic dependency tracking, recursive builds in
831 subdirectories, reliable timestamps (e.g., for network file systems), and
832 so on, mean that developers must painfully (and often incorrectly)
833 reinvent the wheel for each project. Portability is non-trivial, thanks
834 to the quirks of @command{make} on many systems. On top of all this is the
835 manual labor required to implement the many standard targets that users
836 have come to expect (@code{make install}, @code{make distclean},
837 @code{make uninstall}, etc.). Since you are, of course, using Autoconf,
838 you also have to insert repetitive code in your @file{Makefile.in} to
839 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
840 provided by @command{configure}. Into this mess steps @dfn{Automake}.
843 Automake allows you to specify your build needs in a @file{Makefile.am}
844 file with a vastly simpler and more powerful syntax than that of a plain
845 makefile, and then generates a portable @file{Makefile.in} for
846 use with Autoconf. For example, the @file{Makefile.am} to build and
847 install a simple ``Hello world'' program might look like:
851 hello_SOURCES = hello.c
855 The resulting @file{Makefile.in} (~400 lines) automatically supports all
856 the standard targets, the substitutions provided by Autoconf, automatic
857 dependency tracking, @code{VPATH} building, and so on. @command{make}
858 builds the @code{hello} program, and @code{make install} installs it
859 in @file{/usr/local/bin} (or whatever prefix was given to
860 @command{configure}, if not @file{/usr/local}).
862 The benefits of Automake increase for larger packages (especially ones
863 with subdirectories), but even for small programs the added convenience
864 and portability can be substantial. And that's not all@enddots{}
869 GNU software has a well-deserved reputation for running on
870 many different types of systems. While our primary goal is to write
871 software for the GNU system, many users and developers have
872 been introduced to us through the systems that they were already using.
875 Gnulib is a central location for common GNU code, intended to
876 be shared among free software packages. Its components are typically
877 shared at the source level, rather than being a library that gets built,
878 installed, and linked against. The idea is to copy files from Gnulib
879 into your own source tree. There is no distribution tarball; developers
880 should just grab source modules from the repository. The source files
881 are available online, under various licenses, mostly GNU
884 Gnulib modules typically contain C source code along with Autoconf
885 macros used to configure the source code. For example, the Gnulib
886 @code{stdbool} module implements a @file{stdbool.h} header that nearly
887 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
888 This module contains a source file for the replacement header, along
889 with an Autoconf macro that arranges to use the replacement header on
890 old-fashioned systems.
895 Often, one wants to build not only programs, but libraries, so that
896 other programs can benefit from the fruits of your labor. Ideally, one
897 would like to produce @emph{shared} (dynamically linked) libraries,
898 which can be used by multiple programs without duplication on disk or in
899 memory and can be updated independently of the linked programs.
900 Producing shared libraries portably, however, is the stuff of
901 nightmares---each system has its own incompatible tools, compiler flags,
902 and magic incantations. Fortunately, GNU provides a solution:
906 Libtool handles all the requirements of building shared libraries for
907 you, and at this time seems to be the @emph{only} way to do so with any
908 portability. It also handles many other headaches, such as: the
909 interaction of Make rules with the variable suffixes of
910 shared libraries, linking reliably with shared libraries before they are
911 installed by the superuser, and supplying a consistent versioning system
912 (so that different versions of a library can be installed or upgraded
913 without breaking binary compatibility). Although Libtool, like
914 Autoconf, can be used without Automake, it is most simply utilized in
915 conjunction with Automake---there, Libtool is used automatically
916 whenever shared libraries are needed, and you need not know its syntax.
921 Developers who are used to the simplicity of @command{make} for small
922 projects on a single system might be daunted at the prospect of
923 learning to use Automake and Autoconf. As your software is
924 distributed to more and more users, however, you otherwise
925 quickly find yourself putting lots of effort into reinventing the
926 services that the GNU build tools provide, and making the
927 same mistakes that they once made and overcame. (Besides, since
928 you're already learning Autoconf, Automake is a piece of cake.)
930 There are a number of places that you can go to for more information on
937 The project home pages for
938 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
939 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
940 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
941 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
943 @item Automake Manual
945 @xref{Top, , Automake, automake, GNU Automake}, for more
946 information on Automake.
950 The book @cite{GNU Autoconf, Automake and
951 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
952 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor. SAMS (originally
953 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
954 build environment. You can also find
955 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
959 @c ================================================= Making configure Scripts.
961 @node Making configure Scripts
962 @chapter Making @command{configure} Scripts
963 @cindex @file{aclocal.m4}
964 @cindex @command{configure}
966 The configuration scripts that Autoconf produces are by convention
967 called @command{configure}. When run, @command{configure} creates several
968 files, replacing configuration parameters in them with appropriate
969 values. The files that @command{configure} creates are:
973 one or more @file{Makefile} files, usually one in each subdirectory of the
974 package (@pxref{Makefile Substitutions});
977 optionally, a C header file, the name of which is configurable,
978 containing @code{#define} directives (@pxref{Configuration Headers});
981 a shell script called @file{config.status} that, when run, recreates
982 the files listed above (@pxref{config.status Invocation});
985 an optional shell script normally called @file{config.cache}
986 (created when using @samp{configure --config-cache}) that
987 saves the results of running many of the tests (@pxref{Cache Files});
990 a file called @file{config.log} containing any messages produced by
991 compilers, to help debugging if @command{configure} makes a mistake.
994 @cindex @file{configure.in}
995 @cindex @file{configure.ac}
996 To create a @command{configure} script with Autoconf, you need to write an
997 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
998 @command{autoconf} on it. If you write your own feature tests to
999 supplement those that come with Autoconf, you might also write files
1000 called @file{aclocal.m4} and @file{acsite.m4}. If you use a C header
1001 file to contain @code{#define} directives, you might also run
1002 @command{autoheader}, and you can distribute the generated file
1003 @file{config.h.in} with the package.
1005 Here is a diagram showing how the files that can be used in
1006 configuration are produced. Programs that are executed are suffixed by
1007 @samp{*}. Optional files are enclosed in square brackets (@samp{[]}).
1008 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1009 macro files (by reading @file{autoconf.m4}).
1012 Files used in preparing a software package for distribution, when using
1015 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1019 | .------> autoconf* -----> configure
1020 [aclocal.m4] --+---+
1021 | `-----> [autoheader*] --> [config.h.in]
1029 Additionally, if you use Automake, the following additional productions
1036 [local macros] --+--> aclocal* --> aclocal.m4
1043 +--> automake* --> Makefile.in
1049 Files used in configuring a software package:
1052 .-------------> [config.cache]
1053 configure* ------------+-------------> config.log
1055 [config.h.in] -. v .-> [config.h] -.
1056 +--> config.status* -+ +--> make*
1057 Makefile.in ---' `-> Makefile ---'
1062 * Writing Autoconf Input:: What to put in an Autoconf input file
1063 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
1064 * ifnames Invocation:: Listing the conditionals in source code
1065 * autoconf Invocation:: How to create configuration scripts
1066 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
1069 @node Writing Autoconf Input
1070 @section Writing @file{configure.ac}
1072 To produce a @command{configure} script for a software package, create a
1073 file called @file{configure.ac} that contains invocations of the
1074 Autoconf macros that test the system features your package needs or can
1075 use. Autoconf macros already exist to check for many features; see
1076 @ref{Existing Tests}, for their descriptions. For most other features,
1077 you can use Autoconf template macros to produce custom checks; see
1078 @ref{Writing Tests}, for information about them. For especially tricky
1079 or specialized features, @file{configure.ac} might need to contain some
1080 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1081 Programming}. The @command{autoscan} program can give you a good start
1082 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1085 Previous versions of Autoconf promoted the name @file{configure.in},
1086 which is somewhat ambiguous (the tool needed to process this file is not
1087 described by its extension), and introduces a slight confusion with
1088 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1089 processed by @command{configure}''). Using @file{configure.ac} is now
1093 * Shell Script Compiler:: Autoconf as solution of a problem
1094 * Autoconf Language:: Programming in Autoconf
1095 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
1098 @node Shell Script Compiler
1099 @subsection A Shell Script Compiler
1101 Just as for any other computer language, in order to properly program
1102 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1103 the language tries to address and @emph{how} it does so.
1105 The problem Autoconf addresses is that the world is a mess. After all,
1106 you are using Autoconf in order to have your package compile easily on
1107 all sorts of different systems, some of them being extremely hostile.
1108 Autoconf itself bears the price for these differences: @command{configure}
1109 must run on all those systems, and thus @command{configure} must limit itself
1110 to their lowest common denominator of features.
1112 Naturally, you might then think of shell scripts; who needs
1113 @command{autoconf}? A set of properly written shell functions is enough to
1114 make it easy to write @command{configure} scripts by hand. Sigh!
1115 Unfortunately, even in 2008, where shells without any function support are
1116 far and few between, there are pitfalls to avoid when making use of them.
1117 Also, finding a Bourne shell that accepts shell functions is not trivial,
1118 even though there is almost always one on interesting porting targets.
1120 So, what is really needed is some kind of compiler, @command{autoconf},
1121 that takes an Autoconf program, @file{configure.ac}, and transforms it
1122 into a portable shell script, @command{configure}.
1124 How does @command{autoconf} perform this task?
1126 There are two obvious possibilities: creating a brand new language or
1127 extending an existing one. The former option is attractive: all
1128 sorts of optimizations could easily be implemented in the compiler and
1129 many rigorous checks could be performed on the Autoconf program
1130 (e.g., rejecting any non-portable construct). Alternatively, you can
1131 extend an existing language, such as the @code{sh} (Bourne shell)
1134 Autoconf does the latter: it is a layer on top of @code{sh}. It was
1135 therefore most convenient to implement @command{autoconf} as a macro
1136 expander: a program that repeatedly performs @dfn{macro expansions} on
1137 text input, replacing macro calls with macro bodies and producing a pure
1138 @code{sh} script in the end. Instead of implementing a dedicated
1139 Autoconf macro expander, it is natural to use an existing
1140 general-purpose macro language, such as M4, and implement the extensions
1141 as a set of M4 macros.
1144 @node Autoconf Language
1145 @subsection The Autoconf Language
1148 The Autoconf language differs from many other computer
1149 languages because it treats actual code the same as plain text. Whereas
1150 in C, for instance, data and instructions have different syntactic
1151 status, in Autoconf their status is rigorously the same. Therefore, we
1152 need a means to distinguish literal strings from text to be expanded:
1155 When calling macros that take arguments, there must not be any white
1156 space between the macro name and the open parenthesis.
1159 AC_INIT ([oops], [1.0]) # incorrect
1160 AC_INIT([hello], [1.0]) # good
1164 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1165 separated by commas. Any leading blanks or newlines in arguments are ignored,
1166 unless they are quoted. You should always quote an argument that
1167 might contain a macro name, comma, parenthesis, or a leading blank or
1168 newline. This rule applies recursively for every macro
1169 call, including macros called from other macros. For more details on
1170 quoting rules, see @ref{Programming in M4}.
1175 AC_CHECK_HEADER([stdio.h],
1176 [AC_DEFINE([HAVE_STDIO_H], [1],
1177 [Define to 1 if you have <stdio.h>.])],
1178 [AC_MSG_ERROR([sorry, can't do anything for you])])
1182 is quoted properly. You may safely simplify its quotation to:
1185 AC_CHECK_HEADER([stdio.h],
1186 [AC_DEFINE([HAVE_STDIO_H], 1,
1187 [Define to 1 if you have <stdio.h>.])],
1188 [AC_MSG_ERROR([sorry, can't do anything for you])])
1192 because @samp{1} cannot contain a macro call. Here, the argument of
1193 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1194 interpreted as an argument separator. Also, the second and third arguments
1195 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1196 macro calls. The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1197 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1198 if you unwisely defined a macro with a name like @samp{Define} or
1199 @samp{stdio} then they would need quoting. Cautious Autoconf users
1200 would keep the quotes, but many Autoconf users find such precautions
1201 annoying, and would rewrite the example as follows:
1204 AC_CHECK_HEADER(stdio.h,
1205 [AC_DEFINE(HAVE_STDIO_H, 1,
1206 [Define to 1 if you have <stdio.h>.])],
1207 [AC_MSG_ERROR([sorry, can't do anything for you])])
1211 This is safe, so long as you adopt good naming conventions and do not
1212 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1213 @samp{h}. Though it is also safe here to omit the quotes around
1214 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1215 message strings are more likely to inadvertently contain commas.
1217 The following example is wrong and dangerous, as it is underquoted:
1220 AC_CHECK_HEADER(stdio.h,
1221 AC_DEFINE(HAVE_STDIO_H, 1,
1222 Define to 1 if you have <stdio.h>.),
1223 AC_MSG_ERROR([sorry, can't do anything for you]))
1226 In other cases, you may have to use text that also resembles a macro
1227 call. You must quote that text even when it is not passed as a macro
1228 argument. For example, these two approaches in @file{configure.ac}
1229 (quoting just the potential problems, or quoting the entire line) will
1230 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1233 echo "Hard rock was here! --[AC_DC]"
1234 [echo "Hard rock was here! --AC_DC"]
1238 which results in this text in @file{configure}:
1241 echo "Hard rock was here! --AC_DC"
1242 echo "Hard rock was here! --AC_DC"
1246 When you use the same text in a macro argument, you must therefore have
1247 an extra quotation level (since one is stripped away by the macro
1248 substitution). In general, then, it is a good idea to @emph{use double
1249 quoting for all literal string arguments}, either around just the
1250 problematic portions, or over the entire argument:
1253 AC_MSG_WARN([[AC_DC] stinks --Iron Maiden])
1254 AC_MSG_WARN([[AC_DC stinks --Iron Maiden]])
1257 However, the above example triggers a warning about a possibly
1258 unexpanded macro when running @command{autoconf}, because it collides
1259 with the namespace of macros reserved for the Autoconf language. To be
1260 really safe, you can use additional escaping (either a quadrigraph, or
1261 creative shell constructs) to silence that particular warning:
1264 echo "Hard rock was here! --AC""_DC"
1265 AC_MSG_WARN([[AC@@&t@@_DC stinks --Iron Maiden]])
1268 You are now able to understand one of the constructs of Autoconf that
1269 has been continually misunderstood@enddots{} The rule of thumb is that
1270 @emph{whenever you expect macro expansion, expect quote expansion};
1271 i.e., expect one level of quotes to be lost. For instance:
1274 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1278 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1279 @samp{char b[10];} and is expanded once, which results in
1280 @samp{char b10;}. (There was an idiom common in Autoconf's past to
1281 address this issue via the M4 @code{changequote} primitive, but do not
1282 use it!) Let's take a closer look: the author meant the first argument
1283 to be understood as a literal, and therefore it must be quoted twice:
1286 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1290 Voil@`a, you actually produce @samp{char b[10];} this time!
1292 On the other hand, descriptions (e.g., the last parameter of
1293 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1294 are subject to line breaking, for example---and should not be double quoted.
1295 Even if these descriptions are short and are not actually broken, double
1296 quoting them yields weird results.
1298 Some macros take optional arguments, which this documentation represents
1299 as @ovar{arg} (not to be confused with the quote characters). You may
1300 just leave them empty, or use @samp{[]} to make the emptiness of the
1301 argument explicit, or you may simply omit the trailing commas. The
1302 three lines below are equivalent:
1305 AC_CHECK_HEADERS([stdio.h], [], [], [])
1306 AC_CHECK_HEADERS([stdio.h],,,)
1307 AC_CHECK_HEADERS([stdio.h])
1310 It 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
1312 rely on the newline after the macro call to terminate the commands.
1313 This approach makes the generated @command{configure} script a little
1314 easier to read by not inserting lots of blank lines. It is generally
1315 safe to set shell variables on the same line as a macro call, because
1316 the shell allows assignments without intervening newlines.
1318 You can include comments in @file{configure.ac} files by starting them
1319 with the @samp{#}. For example, it is helpful to begin
1320 @file{configure.ac} files with a line like this:
1323 # Process this file with autoconf to produce a configure script.
1326 @node Autoconf Input Layout
1327 @subsection Standard @file{configure.ac} Layout
1329 The order in which @file{configure.ac} calls the Autoconf macros is not
1330 important, with a few exceptions. Every @file{configure.ac} must
1331 contain 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
1333 rely on other macros having been called first, because they check
1334 previously set values of some variables to decide what to do. These
1335 macros are noted in the individual descriptions (@pxref{Existing
1336 Tests}), and they also warn you when @command{configure} is created if they
1337 are called out of order.
1339 To encourage consistency, here is a suggested order for calling the
1340 Autoconf macros. Generally speaking, the things near the end of this
1341 list are those that could depend on things earlier in it. For example,
1342 library functions could be affected by types and libraries.
1346 Autoconf requirements
1347 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1348 information on the package
1350 checks for libraries
1351 checks for header files
1353 checks for structures
1354 checks for compiler characteristics
1355 checks for library functions
1356 checks for system services
1357 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1363 @node autoscan Invocation
1364 @section Using @command{autoscan} to Create @file{configure.ac}
1365 @cindex @command{autoscan}
1367 The @command{autoscan} program can help you create and/or maintain a
1368 @file{configure.ac} file for a software package. @command{autoscan}
1369 examines source files in the directory tree rooted at a directory given
1370 as a command line argument, or the current directory if none is given.
1371 It searches the source files for common portability problems and creates
1372 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1373 for that package, and checks a possibly existing @file{configure.ac} for
1376 When using @command{autoscan} to create a @file{configure.ac}, you
1377 should manually examine @file{configure.scan} before renaming it to
1378 @file{configure.ac}; it probably needs some adjustments.
1379 Occasionally, @command{autoscan} outputs a macro in the wrong order
1380 relative to another macro, so that @command{autoconf} produces a warning;
1381 you need to move such macros manually. Also, if you want the package to
1382 use a configuration header file, you must add a call to
1383 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}). You might
1384 also have to change or add some @code{#if} directives to your program in
1385 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1386 information about a program that can help with that job).
1388 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1389 consider adding its suggestions. The file @file{autoscan.log}
1390 contains detailed information on why a macro is requested.
1392 @command{autoscan} uses several data files (installed along with Autoconf)
1393 to determine which macros to output when it finds particular symbols in
1394 a package's source files. These data files all have the same format:
1395 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1396 output if that symbol is encountered. Lines starting with @samp{#} are
1399 @command{autoscan} accepts the following options:
1404 Print a summary of the command line options and exit.
1408 Print the version number of Autoconf and exit.
1412 Print the names of the files it examines and the potentially interesting
1413 symbols it finds in them. This output can be voluminous.
1417 Don't remove temporary files.
1419 @item --include=@var{dir}
1421 Append @var{dir} to the include path. Multiple invocations accumulate.
1423 @item --prepend-include=@var{dir}
1425 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1428 @node ifnames Invocation
1429 @section Using @command{ifnames} to List Conditionals
1430 @cindex @command{ifnames}
1432 @command{ifnames} can help you write @file{configure.ac} for a software
1433 package. It prints the identifiers that the package already uses in C
1434 preprocessor conditionals. If a package has already been set up to have
1435 some 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
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
1442 output a sorted list of all the identifiers that appear in those files
1443 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1444 directives. It prints each identifier on a line, followed by a
1445 space-separated list of the files in which that identifier occurs.
1448 @command{ifnames} accepts the following options:
1453 Print a summary of the command line options and exit.
1457 Print the version number of Autoconf and exit.
1460 @node autoconf Invocation
1461 @section Using @command{autoconf} to Create @command{configure}
1462 @cindex @command{autoconf}
1464 To 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
1467 Autoconf macros. If you give @command{autoconf} an argument, it reads that
1468 file instead of @file{configure.ac} and writes the configuration script
1469 to the standard output instead of to @command{configure}. If you give
1470 @command{autoconf} the argument @option{-}, it reads from the standard
1471 input instead of @file{configure.ac} and writes the configuration script
1472 to the standard output.
1474 The Autoconf macros are defined in several files. Some of the files are
1475 distributed with Autoconf; @command{autoconf} reads them first. Then it
1476 looks for the optional file @file{acsite.m4} in the directory that
1477 contains the distributed Autoconf macro files, and for the optional file
1478 @file{aclocal.m4} in the current directory. Those files can contain
1479 your site's or the package's own Autoconf macro definitions
1480 (@pxref{Writing Autoconf Macros}, for more information). If a macro is
1481 defined in more than one of the files that @command{autoconf} reads, the
1482 last definition it reads overrides the earlier ones.
1484 @command{autoconf} accepts the following options:
1489 Print a summary of the command line options and exit.
1493 Print the version number of Autoconf and exit.
1497 Report processing steps.
1501 Don't remove the temporary files.
1505 Remake @file{configure} even if newer than its input files.
1507 @item --include=@var{dir}
1509 Append @var{dir} to the include path. Multiple invocations accumulate.
1511 @item --prepend-include=@var{dir}
1513 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1515 @item --output=@var{file}
1516 @itemx -o @var{file}
1517 Save output (script or trace) to @var{file}. The file @option{-} stands
1518 for the standard output.
1520 @item --warnings=@var{category}
1521 @itemx -W @var{category}
1523 Report the warnings related to @var{category} (which can actually be a
1524 comma separated list). @xref{Reporting Messages}, macro
1525 @code{AC_DIAGNOSE}, for a comprehensive list of categories. Special
1530 report all the warnings
1536 treats warnings as errors
1538 @item no-@var{category}
1539 disable warnings falling into @var{category}
1542 Warnings about @samp{syntax} are enabled by default, and the environment
1543 variable @env{WARNINGS}, a comma separated list of categories, is
1544 honored as well. Passing @option{-W @var{category}} actually behaves as if
1545 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}. To
1546 disable the defaults and @env{WARNINGS}, and then
1547 enable warnings about obsolete constructs, use @option{-W
1551 @cindex Macro invocation stack
1552 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1553 displays a back trace for errors, but not for warnings; if you want
1554 them, just pass @option{-W error}. @xref{autom4te Invocation}, for some
1557 @item --trace=@var{macro}[:@var{format}]
1558 @itemx -t @var{macro}[:@var{format}]
1559 Do not create the @command{configure} script, but list the calls to
1560 @var{macro} according to the @var{format}. Multiple @option{--trace}
1561 arguments can be used to list several macros. Multiple @option{--trace}
1562 arguments for a single macro are not cumulative; instead, you should
1563 just make @var{format} as long as needed.
1565 The @var{format} is a regular string, with newlines if desired, and
1566 several special escape codes. It defaults to @samp{$f:$l:$n:$%}; see
1567 @ref{autom4te Invocation}, for details on the @var{format}.
1569 @item --initialization
1571 By default, @option{--trace} does not trace the initialization of the
1572 Autoconf macros (typically the @code{AC_DEFUN} definitions). This
1573 results in a noticeable speedup, but can be disabled by this option.
1577 It is often necessary to check the content of a @file{configure.ac}
1578 file, but parsing it yourself is extremely fragile and error-prone. It
1579 is suggested that you rely upon @option{--trace} to scan
1580 @file{configure.ac}. For instance, to find the list of variables that
1581 are substituted, use:
1585 $ @kbd{autoconf -t AC_SUBST}
1586 configure.ac:2:AC_SUBST:ECHO_C
1587 configure.ac:2:AC_SUBST:ECHO_N
1588 configure.ac:2:AC_SUBST:ECHO_T
1589 @i{More traces deleted}
1594 The example below highlights the difference between @samp{$@@},
1595 @samp{$*}, and @samp{$%}.
1599 $ @kbd{cat configure.ac}
1600 AC_DEFINE(This, is, [an
1602 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1609 %: This:is:an [example]
1614 The @var{format} gives you a lot of freedom:
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}
1627 A long @var{separator} can be used to improve the readability of complex
1628 structures, and to ease their parsing (for instance when no single
1629 character is suitable as a separator):
1633 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1634 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1635 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1636 AUTOMAKE|:::::|automake|:::::|$missing_dir
1637 @i{More traces deleted}
1641 @node autoreconf Invocation
1642 @section Using @command{autoreconf} to Update @command{configure} Scripts
1643 @cindex @command{autoreconf}
1645 Installing the various components of the GNU Build System can be
1646 tedious: running @command{autopoint} for Gettext, @command{automake} for
1647 @file{Makefile.in} etc.@: in each directory. It may be needed either
1648 because some tools such as @command{automake} have been updated on your
1649 system, or because some of the sources such as @file{configure.ac} have
1650 been updated, or finally, simply in order to install the GNU Build
1651 System in a fresh tree.
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
1656 GNU Build System in the specified directories and their
1657 subdirectories (@pxref{Subdirectories}). By default, it only remakes
1658 those files that are older than their sources. The environment variables
1659 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1660 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1661 to override the invocation of the respective tools.
1663 If 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.
1667 @xref{Automatic Remaking}, for Make rules to automatically
1668 rebuild @command{configure} scripts when their source files change. That
1669 method handles the timestamps of configuration header templates
1670 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1671 @option{--localdir=@var{dir}}.
1674 @cindex @command{autopoint}
1675 Gettext supplies the @command{autopoint} command to add translation
1676 infrastructure to a source package. If you use @command{autopoint},
1677 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1678 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}. @xref{autopoint
1679 Invocation, , Invoking the @code{autopoint} Program, gettext,
1680 GNU @code{gettext} utilities}, for further details.
1683 @command{autoreconf} accepts the following options:
1688 Print a summary of the command line options and exit.
1692 Print the version number of Autoconf and exit.
1696 Print the name of each directory @command{autoreconf} examines and the
1697 commands it runs. If given two or more times, pass @option{--verbose}
1698 to subordinate tools that support it.
1702 Don't remove the temporary files.
1706 Remake even @file{configure} scripts and configuration headers that are
1707 newer than their input files (@file{configure.ac} and, if present,
1712 Install the missing auxiliary files in the package. By default, files
1713 are copied; this can be changed with @option{--symlink}.
1715 If deemed appropriate, this option triggers calls to
1716 @samp{automake --add-missing},
1717 @samp{libtoolize}, @samp{autopoint}, etc.
1719 @item --no-recursive
1720 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1721 macro @code{AC_CONFIG_SUBDIRS}).
1725 When used with @option{--install}, install symbolic links to the missing
1726 auxiliary files instead of copying them.
1730 When the directories were configured, update the configuration by
1731 running @samp{./config.status --recheck && ./config.status}, and then
1734 @item --include=@var{dir}
1736 Append @var{dir} to the include path. Multiple invocations accumulate.
1737 Passed on to @command{aclocal}, @command{autoconf} and
1738 @command{autoheader} internally.
1740 @item --prepend-include=@var{dir}
1742 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1743 Passed on to @command{autoconf} and @command{autoheader} internally.
1745 @item --warnings=@var{category}
1746 @itemx -W @var{category}
1748 Report the warnings related to @var{category} (which can actually be a
1749 comma separated list).
1753 related to cross compilation issues.
1756 report the uses of obsolete constructs.
1762 dubious syntactic constructs.
1765 report all the warnings
1771 treats warnings as errors
1773 @item no-@var{category}
1774 disable warnings falling into @var{category}
1777 Warnings about @samp{syntax} are enabled by default, and the environment
1778 variable @env{WARNINGS}, a comma separated list of categories, is
1779 honored as well. Passing @option{-W @var{category}} actually behaves as if
1780 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}. To
1781 disable the defaults and @env{WARNINGS}, and then
1782 enable warnings about obsolete constructs, use @option{-W
1786 If you want @command{autoreconf} to pass flags that are not listed here
1787 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1788 Due to a limitation in the Autoconf implementation these flags currently
1789 must be set on a single line in @file{Makefile.am}, without any
1792 @c ========================================= Initialization and Output Files.
1795 @chapter Initialization and Output Files
1797 Autoconf-generated @command{configure} scripts need some information about
1798 how to initialize, such as how to find the package's source files and
1799 about the output files to produce. The following sections describe the
1800 initialization and the creation of output files.
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
1818 @node Initializing configure
1819 @section Initializing @command{configure}
1821 Every @command{configure} script must call @code{AC_INIT} before doing
1822 anything else that produces output. Calls to silent macros, such as
1823 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1824 are generally used via @file{aclocal.m4}, since that is implicitly
1825 included before the start of @file{configure.ac}. The only other
1826 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1829 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1830 @ovar{tarname}, @ovar{url})
1832 Process any command-line arguments and perform various initializations
1835 Set the name of the @var{package} and its @var{version}. These are
1836 typically used in @option{--version} support, including that of
1837 @command{configure}. The optional argument @var{bug-report} should be
1838 the email to which users should send bug reports. The package
1839 @var{tarname} differs from @var{package}: the latter designates the full
1840 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1841 distribution tar ball names (e.g., @samp{autoconf}). It defaults to
1842 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1843 other than alphanumerics and underscores are changed to @samp{-}. If
1844 provided, @var{url} should be the home page for the package.
1846 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1847 there should not be any shell computation, but they can be computed by
1850 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1851 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1852 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1855 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1856 @acindex{PACKAGE_NAME}
1857 @ovindex PACKAGE_NAME
1858 @cvindex PACKAGE_NAME
1859 Exactly @var{package}.
1861 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1862 @acindex{PACKAGE_TARNAME}
1863 @ovindex PACKAGE_TARNAME
1864 @cvindex PACKAGE_TARNAME
1865 Exactly @var{tarname}, possibly generated from @var{package}.
1867 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1868 @acindex{PACKAGE_VERSION}
1869 @ovindex PACKAGE_VERSION
1870 @cvindex PACKAGE_VERSION
1871 Exactly @var{version}.
1873 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1874 @acindex{PACKAGE_STRING}
1875 @ovindex PACKAGE_STRING
1876 @cvindex PACKAGE_STRING
1877 Exactly @samp{@var{package} @var{version}}.
1879 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1880 @acindex{PACKAGE_BUGREPORT}
1881 @ovindex PACKAGE_BUGREPORT
1882 @cvindex PACKAGE_BUGREPORT
1883 Exactly @var{bug-report}, if one was provided.
1885 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1886 @acindex{PACKAGE_URL}
1887 @ovindex PACKAGE_URL
1888 @cvindex PACKAGE_URL
1889 Exactly @var{url}, if one was provided. If @var{url} was empty, but
1890 @var{package} begins with @samp{GNU }, then this defaults to
1891 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1896 If your @command{configure} script does its own option processing, it
1897 should inspect @samp{$@@} or @samp{$*} immediately after calling
1898 @code{AC_INIT}, because other Autoconf macros liberally use the
1899 @command{set} command to process strings, and this has the side effect
1900 of updating @samp{$@@} and @samp{$*}. However, we suggest that you use
1901 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1902 implement your own option processing. @xref{Site Configuration}.
1905 @section Dealing with Autoconf versions
1906 @cindex Autoconf version
1907 @cindex version, Autoconf
1909 The following optional macros can be used to help choose the minimum
1910 version of Autoconf that can successfully compile a given
1911 @file{configure.ac}.
1913 @defmac AC_PREREQ (@var{version})
1916 Ensure that a recent enough version of Autoconf is being used. If the
1917 version of Autoconf being used to create @command{configure} is
1918 earlier than @var{version}, print an error message to the standard
1919 error output and exit with failure (exit status is 63). For example:
1922 AC_PREREQ([@value{VERSION}])
1925 This macro may be used before @code{AC_INIT}.
1928 @defmac AC_AUTOCONF_VERSION
1929 @acindex{AUTOCONF_VERSION}
1930 This macro was introduced in Autoconf 2.62. It identifies the version
1931 of Autoconf that is currently parsing the input file, in a format
1932 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1933 other words, for this release of Autoconf, its value is
1934 @samp{@value{VERSION}}. One potential use of this macro is for writing
1935 conditional fallbacks based on when a feature was added to Autoconf,
1936 rather than using @code{AC_PREREQ} to require the newer version of
1937 Autoconf. However, remember that the Autoconf philosophy favors feature
1938 checks over version checks.
1940 You should not expand this macro directly; use
1941 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead. This is because some
1943 have a beta version of Autoconf installed, with arbitrary letters
1944 included in its version string. This means it is possible for the
1945 version string to contain the name of a defined macro, such that
1946 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1947 macro during rescanning, and change the version string to be different
1948 than what you intended to check.
1952 @section Notices in @command{configure}
1953 @cindex Notices in @command{configure}
1955 The following macros manage version numbers for @command{configure}
1956 scripts. Using them is optional.
1958 @defmac AC_COPYRIGHT (@var{copyright-notice})
1960 @cindex Copyright Notice
1961 State that, in addition to the Free Software Foundation's copyright on
1962 the Autoconf macros, parts of your @command{configure} are covered by the
1963 @var{copyright-notice}.
1965 The @var{copyright-notice} shows up in both the head of
1966 @command{configure} and in @samp{configure --version}.
1970 @defmac AC_REVISION (@var{revision-info})
1973 Copy revision stamp @var{revision-info} into the @command{configure}
1974 script, with any dollar signs or double-quotes removed. This macro lets
1975 you put a revision stamp from @file{configure.ac} into @command{configure}
1976 without RCS or CVS changing it when you check in
1977 @command{configure}. That way, you can determine easily which revision of
1978 @file{configure.ac} a particular @command{configure} corresponds to.
1980 For example, this line in @file{configure.ac}:
1982 @c The @w prevents RCS from changing the example in the manual.
1984 AC_REVISION([@w{$}Revision: 1.30 $])
1988 produces this in @command{configure}:
1992 # From configure.ac Revision: 1.30
1998 @section Finding @command{configure} Input
2000 @anchor{AC_CONFIG_SRCDIR}
2001 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2002 @acindex{CONFIG_SRCDIR}
2003 @var{unique-file-in-source-dir} is some file that is in the package's
2004 source directory; @command{configure} checks for this file's existence to
2005 make sure that the directory that it is told contains the source code in
2006 fact does. Occasionally people accidentally specify the wrong directory
2007 with @option{--srcdir}; this is a safety check. @xref{configure
2008 Invocation}, for more information.
2012 @c FIXME: Remove definitively once --install explained.
2014 @c Small packages may store all their macros in @code{aclocal.m4}. As the
2015 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2016 @c to split the macros in several files. In this case, Autoconf must be
2017 @c told which files to load, and in which order.
2019 @c @defmac AC_INCLUDE (@var{file}@dots{})
2020 @c @acindex{INCLUDE}
2021 @c @c FIXME: There is no longer shell globbing.
2022 @c Read the macro definitions that appear in the listed files. A list of
2023 @c space-separated file names or shell globbing patterns is expected. The
2024 @c files are read in the order they're listed.
2026 @c Because the order of definition of macros is important (only the last
2027 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2028 @c loads @file{acsite.m4} and @file{aclocal.m4}. Note that
2029 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2030 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2031 @c the latter case, non-macro lines from included files may end up in the
2032 @c @file{configure} script, whereas in the former case, they'd be discarded
2033 @c just like any text that appear before @code{AC_INIT}.
2036 Packages that do manual configuration or use the @command{install} program
2037 might need to tell @command{configure} where to find some other shell
2038 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2039 it looks are correct for most cases.
2041 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2042 @acindex{CONFIG_AUX_DIR}
2043 Use the auxiliary build tools (e.g., @file{install-sh},
2044 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2045 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2046 These are auxiliary files used in configuration. @var{dir} can be
2047 either absolute or relative to @file{@var{srcdir}}. The default is
2048 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2049 @file{@var{srcdir}/../..}, whichever is the first that contains
2050 @file{install-sh}. The other files are not checked for, so that using
2051 @code{AC_PROG_INSTALL} does not automatically require distributing the
2052 other auxiliary files. It checks for @file{install.sh} also, but that
2053 name is obsolete because some @command{make} have a rule that creates
2054 @file{install} from it if there is no makefile.
2056 The auxiliary directory is commonly named @file{build-aux}.
2057 If you need portability to DOS variants, do not name the
2058 auxiliary directory @file{aux}. @xref{File System Conventions}.
2061 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2062 @acindex{REQUIRE_AUX_FILE}
2063 Declares that @var{file} is expected in the directory defined above. In
2064 Autoconf proper, this macro does nothing: its sole purpose is to be
2065 traced by third-party tools to produce a list of expected auxiliary
2066 files. For instance it is called by macros like @code{AC_PROG_INSTALL}
2067 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2068 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2071 Similarly, packages that use @command{aclocal} should declare where
2072 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2074 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2075 @acindex{CONFIG_MACRO_DIR}
2076 Specify @var{dir} as the location of additional local Autoconf macros.
2077 This macro is intended for use by future versions of commands like
2078 @command{autoreconf} that trace macro calls. It should be called
2079 directly from @file{configure.ac} so that tools that install macros for
2080 @command{aclocal} can find the macros' declarations.
2082 Note that if you use @command{aclocal} from Automake to generate
2083 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2084 @var{dir}} in your top-level @file{Makefile.am}. Due to a limitation in
2085 the Autoconf implementation of @command{autoreconf}, these include
2086 directives currently must be set on a single line in @file{Makefile.am},
2087 without any backslash-newlines.
2092 @section Outputting Files
2093 @cindex Outputting files
2095 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2096 calling @code{AC_OUTPUT}. That is the macro that generates and runs
2097 @file{config.status}, which in turn creates the makefiles and any
2098 other files resulting from configuration. This is the only required
2099 macro besides @code{AC_INIT} (@pxref{Input}).
2104 @cindex Instantiation
2105 Generate @file{config.status} and launch it. Call this macro once, at
2106 the end of @file{configure.ac}.
2108 @file{config.status} performs all the configuration actions: all the
2109 output files (see @ref{Configuration Files}, macro
2110 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2111 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2112 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2113 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2114 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2117 The location of your @code{AC_OUTPUT} invocation is the exact point
2118 where configuration actions are taken: any code afterwards is
2119 executed by @command{configure} once @command{config.status} was run. If
2120 you want to bind actions to @command{config.status} itself
2121 (independently of whether @command{configure} is being run), see
2122 @ref{Configuration Commands, , Running Arbitrary Configuration
2126 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2127 @xref{Obsolete Macros}, for a description of the arguments that
2128 @code{AC_OUTPUT} used to support.
2131 If you run @command{make} in subdirectories, you should run it using the
2132 @command{make} variable @code{MAKE}. Most versions of @command{make} set
2133 @code{MAKE} to the name of the @command{make} program plus any options it
2134 was given. (But many do not include in it the values of any variables
2135 set on the command line, so those are not passed on automatically.)
2136 Some old versions of @command{make} do not set this variable. The
2137 following macro allows you to use it even with those versions.
2139 @anchor{AC_PROG_MAKE_SET}
2140 @defmac AC_PROG_MAKE_SET
2141 @acindex{PROG_MAKE_SET}
2143 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2144 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2145 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2146 @code{$(MAKE)}, such as @samp{MAKE=make}. Calls @code{AC_SUBST} for
2150 If you use this macro, place a line like this in each @file{Makefile.in}
2151 that runs @command{MAKE} on other directories:
2159 @node Configuration Actions
2160 @section Performing Configuration Actions
2161 @cindex Configuration actions
2163 @file{configure} is designed so that it appears to do everything itself,
2164 but there is actually a hidden slave: @file{config.status}.
2165 @file{configure} is in charge of examining your system, but it is
2166 @file{config.status} that actually takes the proper actions based on the
2167 results of @file{configure}. The most typical task of
2168 @file{config.status} is to @emph{instantiate} files.
2170 @acindex{CONFIG_@var{ITEMS}}
2171 This section describes the common behavior of the four standard
2172 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2173 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}. They all
2174 have this prototype:
2176 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2179 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2183 where the arguments are:
2187 A blank-or-newline-separated list of tags, which are typically the names of
2188 the files to instantiate.
2190 You are encouraged to use literals as @var{tags}. In particular, you
2194 @dots{} && my_foos="$my_foos fooo"
2195 @dots{} && my_foos="$my_foos foooo"
2196 AC_CONFIG_@var{ITEMS}([$my_foos])
2200 and use this instead:
2203 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2204 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2207 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2208 special @var{tag} values: they may have the form @samp{@var{output}} or
2209 @samp{@var{output}:@var{inputs}}. The file @var{output} is instantiated
2210 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2212 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2213 for example, asks for
2214 the creation of the file @file{Makefile} that contains the expansion of the
2215 output variables in the concatenation of @file{boiler/top.mk} and
2216 @file{boiler/bot.mk}.
2218 The special value @samp{-} might be used to denote the standard output
2219 when used in @var{output}, or the standard input when used in the
2220 @var{inputs}. You most probably don't need to use this in
2221 @file{configure.ac}, but it is convenient when using the command line
2222 interface of @file{./config.status}, see @ref{config.status Invocation},
2225 The @var{inputs} may be absolute or relative file names. In the latter
2226 case they are first looked for in the build tree, and then in the source
2227 tree. Input files should be text files, and a line length below 2000
2228 bytes should be safe.
2231 Shell commands output literally into @file{config.status}, and
2232 associated with a tag that the user can use to tell @file{config.status}
2233 which commands to run. The commands are run each time a @var{tag}
2234 request is given to @file{config.status}, typically each time the file
2235 @file{@var{tag}} is created.
2237 The variables set during the execution of @command{configure} are
2238 @emph{not} available here: you first need to set them via the
2239 @var{init-cmds}. Nonetheless the following variables are precomputed:
2243 The name of the top source directory, assuming that the working
2244 directory is the top build directory. This
2245 is what the @command{configure} option @option{--srcdir} sets.
2248 The name of the top source directory, assuming that the working
2249 directory is the current build directory.
2251 @item ac_top_build_prefix
2252 The name of the top build directory, assuming that the working
2253 directory is the current build directory.
2254 It can be empty, or else ends with a slash, so that you may concatenate
2258 The name of the corresponding source directory, assuming that the
2259 working directory is the current build directory.
2262 The name of a temporary directory within the build tree, which you
2263 can use if you need to create additional temporary files. The
2264 directory is cleaned up when @command{config.status} is done or
2265 interrupted. Please use package-specific file name prefixes to
2266 avoid clashing with files that @command{config.status} may use
2271 The @dfn{current} directory refers to the directory (or
2272 pseudo-directory) containing the input part of @var{tags}. For
2276 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2280 with @option{--srcdir=../package} produces the following values:
2283 # Argument of --srcdir
2285 # Reversing deep/dir
2286 ac_top_build_prefix='../../'
2287 # Concatenation of $ac_top_build_prefix and srcdir
2288 ac_top_srcdir='../../../package'
2289 # Concatenation of $ac_top_srcdir and deep/dir
2290 ac_srcdir='../../../package/deep/dir'
2294 independently of @samp{in/in.in}.
2297 Shell commands output @emph{unquoted} near the beginning of
2298 @file{config.status}, and executed each time @file{config.status} runs
2299 (regardless of the tag). Because they are unquoted, for example,
2300 @samp{$var} is output as the value of @code{var}. @var{init-cmds}
2301 is typically used by @file{configure} to give @file{config.status} some
2302 variables it needs to run the @var{commands}.
2304 You should be extremely cautious in your variable names: all the
2305 @var{init-cmds} share the same name space and may overwrite each other
2306 in unpredictable ways. Sorry@enddots{}
2309 All these macros can be called multiple times, with different
2310 @var{tag} values, of course!
2313 @node Configuration Files
2314 @section Creating Configuration Files
2315 @cindex Creating configuration files
2316 @cindex Configuration file creation
2318 Be sure to read the previous section, @ref{Configuration Actions}.
2320 @anchor{AC_CONFIG_FILES}
2321 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2322 @acindex{CONFIG_FILES}
2323 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2324 file (by default @file{@var{file}.in}), substituting the output variable
2326 @c Before we used to have this feature, which was later rejected
2327 @c because it complicates the writing of makefiles:
2328 @c If the file would be unchanged, it is left untouched, to preserve
2330 This macro is one of the instantiating macros; see @ref{Configuration
2331 Actions}. @xref{Makefile Substitutions}, for more information on using
2332 output variables. @xref{Setting Output Variables}, for more information
2333 on creating them. This macro creates the directory that the file is in
2334 if it doesn't exist. Usually, makefiles are created this way,
2335 but other files, such as @file{.gdbinit}, can be specified as well.
2337 Typical calls to @code{AC_CONFIG_FILES} look like this:
2340 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2341 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2344 You can override an input file name by appending to @var{file} a
2345 colon-separated list of input files. Examples:
2348 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2349 [lib/Makefile:boiler/lib.mk])
2353 Doing this allows you to keep your file names acceptable to
2355 to prepend and/or append boilerplate to the file.
2360 @node Makefile Substitutions
2361 @section Substitutions in Makefiles
2362 @cindex Substitutions in makefiles
2363 @cindex Makefile substitutions
2365 Each subdirectory in a distribution that contains something to be
2366 compiled or installed should come with a file @file{Makefile.in}, from
2367 which @command{configure} creates a file @file{Makefile} in that directory.
2368 To create @file{Makefile}, @command{configure} performs a simple variable
2369 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2370 @file{Makefile.in} with the value that @command{configure} has determined
2371 for that variable. Variables that are substituted into output files in
2372 this way are called @dfn{output variables}. They are ordinary shell
2373 variables that are set in @command{configure}. To make @command{configure}
2374 substitute a particular variable into the output files, the macro
2375 @code{AC_SUBST} must be called with that variable name as an argument.
2376 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2377 left unchanged. @xref{Setting Output Variables}, for more information
2378 on creating output variables with @code{AC_SUBST}.
2380 A software package that uses a @command{configure} script should be
2381 distributed with a file @file{Makefile.in}, but no makefile; that
2382 way, the user has to properly configure the package for the local system
2383 before compiling it.
2385 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2386 GNU Coding Standards}, for more information on what to put in
2390 * Preset Output Variables:: Output variables that are always set
2391 * Installation Directory Variables:: Other preset output variables
2392 * Changed Directory Variables:: Warnings about @file{datarootdir}
2393 * Build Directories:: Supporting multiple concurrent compiles
2394 * Automatic Remaking:: Makefile rules for configuring
2397 @node Preset Output Variables
2398 @subsection Preset Output Variables
2399 @cindex Output variables
2401 Some output variables are preset by the Autoconf macros. Some of the
2402 Autoconf macros set additional output variables, which are mentioned in
2403 the descriptions for those macros. @xref{Output Variable Index}, for a
2404 complete list of output variables. @xref{Installation Directory
2405 Variables}, for the list of the preset ones related to installation
2406 directories. Below are listed the other preset ones, many of which are
2407 precious variables (@pxref{Setting Output Variables},
2410 The preset variables which are available during @file{config.status}
2411 (@pxref{Configuration Actions}) may also be used during
2412 @command{configure} tests. For example, it is permissible to reference
2413 @samp{$srcdir} when constructing a list of directories to pass via
2414 option @option{-I} during a compiler feature check. When used in this
2415 manner, coupled with the fact that @command{configure} is always run
2416 from the top build directory, it is sufficient to use just
2417 @samp{$srcdir} instead of @samp{$top_srcdir}.
2419 @c Just say no to ASCII sorting! We're humans, not computers.
2420 @c These variables are listed as they would be in a dictionary:
2428 Debugging and optimization options for the C compiler. If it is not set
2429 in the environment when @command{configure} runs, the default value is set
2430 when you call @code{AC_PROG_CC} (or empty if you don't). @command{configure}
2431 uses this variable when compiling or linking programs to test for C features.
2433 If a compiler option affects only the behavior of the preprocessor
2434 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2435 instead. If it affects only the linker (e.g., @option{-L
2436 @var{directory}}), it should be put into @code{LDFLAGS} instead. If it
2437 affects only the compiler proper, @code{CFLAGS} is the natural home for
2438 it. If an option affects multiple phases of the compiler, though,
2439 matters get tricky. One approach to put such options directly into
2440 @code{CC}, e.g., @code{CC='gcc -m64'}. Another is to put them into both
2441 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2443 However, remember that some @file{Makefile} variables are reserved by
2444 the GNU Coding Standards for the use of the ``user''---the person
2445 building the package. For instance, @code{CFLAGS} is one such variable.
2447 Sometimes package developers are tempted to set user variables such as
2448 @code{CFLAGS} because it appears to make their job easier. However, the
2449 package itself should never set a user variable, particularly not to
2450 include switches that are required for proper compilation of the
2451 package. Since these variables are documented as being for the package
2452 builder, that person rightfully expects to be able to override any of
2453 these variables at build time. If the package developer needs to add
2454 switches without interfering with the user, the proper way to do that is
2455 to introduce an additional variable. Automake makes this easy by
2456 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2457 automake, GNU Automake}), but the concept is the same even if
2458 Automake is not used.
2461 @defvar configure_input
2462 @ovindex configure_input
2463 A comment saying that the file was generated automatically by
2464 @command{configure} and giving the name of the input file.
2465 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2466 of every makefile it creates. For other files, you should
2467 reference this variable in a comment at the top of each input file. For
2468 example, an input shell script should begin like this:
2472 # @@configure_input@@
2476 The presence of that line also reminds people editing the file that it
2477 needs to be processed by @command{configure} in order to be used.
2483 Preprocessor options for the C, C++, Objective C, and Objective C++
2484 preprocessors and compilers. If
2485 it is not set in the environment when @command{configure} runs, the default
2486 value is empty. @command{configure} uses this variable when preprocessing
2487 or compiling programs to test for C, C++, Objective C, and Objective C++
2490 This variable's contents should contain options like @option{-I},
2491 @option{-D}, and @option{-U} that affect only the behavior of the
2492 preprocessor. Please see the explanation of @code{CFLAGS} for what you
2493 can do if an option affects other phases of the compiler as well.
2495 Currently, @command{configure} always links as part of a single
2496 invocation of the compiler that also preprocesses and compiles, so it
2497 uses this variable also when linking programs. However, it is unwise to
2498 depend on this behavior because the GNU Coding Standards do
2499 not require it and many packages do not use @code{CPPFLAGS} when linking
2502 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2509 Debugging and optimization options for the C++ compiler. It acts like
2510 @code{CFLAGS}, but for C++ instead of C.
2515 @option{-D} options to pass to the C compiler. If @code{AC_CONFIG_HEADERS}
2516 is called, @command{configure} replaces @samp{@@DEFS@@} with
2517 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}). This
2518 variable is not defined while @command{configure} is performing its tests,
2519 only when creating the output files. @xref{Setting Output Variables}, for
2520 how to check the results of previous tests.
2529 How does one suppress the trailing newline from @command{echo} for
2530 question-answer message pairs? These variables provide a way:
2533 echo $ECHO_N "And the winner is... $ECHO_C"
2535 echo "$@{ECHO_T@}dead."
2539 Some old and uncommon @command{echo} implementations offer no means to
2540 achieve this, in which case @code{ECHO_T} is set to tab. You might not
2547 Debugging and optimization options for the Erlang compiler. If it is not set
2548 in the environment when @command{configure} runs, the default value is empty.
2549 @command{configure} uses this variable when compiling
2550 programs to test for Erlang features.
2556 Debugging and optimization options for the Fortran compiler. If it
2557 is not set in the environment when @command{configure} runs, the default
2558 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2559 @command{configure} uses this variable when compiling or linking
2560 programs to test for Fortran features.
2566 Debugging and optimization options for the Fortran 77 compiler. If it
2567 is not set in the environment when @command{configure} runs, the default
2568 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2569 @command{configure} uses this variable when compiling or linking
2570 programs to test for Fortran 77 features.
2576 Options for the linker. If it is not set
2577 in the environment when @command{configure} runs, the default value is empty.
2578 @command{configure} uses this variable when linking programs to test for
2579 C, C++, Objective C, Objective C++, and Fortran features.
2581 This variable's contents should contain options like @option{-s} and
2582 @option{-L} that affect only the behavior of the linker. Please see the
2583 explanation of @code{CFLAGS} for what you can do if an option also
2584 affects other phases of the compiler.
2586 Don't use this variable to pass library names
2587 (@option{-l}) to the linker; use @code{LIBS} instead.
2593 @option{-l} options to pass to the linker. The default value is empty,
2594 but some Autoconf macros may prepend extra libraries to this variable if
2595 those libraries are found and provide necessary functions, see
2596 @ref{Libraries}. @command{configure} uses this variable when linking
2597 programs to test for C, C++, Objective C, Objective C++, and Fortran
2604 Debugging and optimization options for the Objective C compiler. It
2605 acts like @code{CFLAGS}, but for Objective C instead of C.
2609 @evindex OBJCXXFLAGS
2610 @ovindex OBJCXXFLAGS
2611 Debugging and optimization options for the Objective C++ compiler. It
2612 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2617 Rigorously equal to @samp{.}. Added for symmetry only.
2620 @defvar abs_builddir
2621 @ovindex abs_builddir
2622 Absolute name of @code{builddir}.
2625 @defvar top_builddir
2626 @ovindex top_builddir
2627 The relative name of the top level of the current build tree. In the
2628 top-level directory, this is the same as @code{builddir}.
2631 @defvar top_build_prefix
2632 @ovindex top_build_prefix
2633 The relative name of the top level of the current build tree with final
2634 slash if nonemtpy. This is the same as @code{top_builddir}, except that
2635 it contains zero or more runs of @code{../}, so it should not be
2636 appended with a slash for concatenation. This helps for @command{make}
2637 implementations that otherwise do not treat @file{./file} and @file{file}
2638 as equal in the toplevel build directory.
2641 @defvar abs_top_builddir
2642 @ovindex abs_top_builddir
2643 Absolute name of @code{top_builddir}.
2648 The name of the directory that contains the source code for
2654 Absolute name of @code{srcdir}.
2659 The name of the top-level source code directory for the
2660 package. In the top-level directory, this is the same as @code{srcdir}.
2663 @defvar abs_top_srcdir
2664 @ovindex abs_top_srcdir
2665 Absolute name of @code{top_srcdir}.
2668 @node Installation Directory Variables
2669 @subsection Installation Directory Variables
2670 @cindex Installation directories
2671 @cindex Directories, installation
2673 The following variables specify the directories for
2674 package installation, see @ref{Directory Variables, , Variables for
2675 Installation Directories, standards, The GNU Coding
2676 Standards}, for more information. Each variable corresponds to an
2677 argument of @command{configure}; trailing slashes are stripped so that
2678 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2679 between directory names. See the end of this section for
2680 details on when and how to use these variables.
2684 The directory for installing executables that users run.
2689 The directory for installing idiosyncratic read-only
2690 architecture-independent data.
2694 @ovindex datarootdir
2695 The root of the directory tree for read-only architecture-independent
2701 The directory for installing documentation files (other than Info and
2707 The directory for installing documentation files in DVI format.
2711 @ovindex exec_prefix
2712 The installation prefix for architecture-dependent files. By default
2713 it's the same as @var{prefix}. You should avoid installing anything
2714 directly to @var{exec_prefix}. However, the default value for
2715 directories containing architecture-dependent files should be relative
2716 to @var{exec_prefix}.
2721 The directory for installing HTML documentation.
2726 The directory for installing C header files.
2731 The directory for installing documentation in Info format.
2736 The directory for installing object code libraries.
2741 The directory for installing executables that other programs run.
2746 The directory for installing locale-dependent but
2747 architecture-independent data, such as message catalogs. This directory
2748 usually has a subdirectory per locale.
2751 @defvar localstatedir
2752 @ovindex localstatedir
2753 The directory for installing modifiable single-machine data.
2758 The top-level directory for installing documentation in man format.
2761 @defvar oldincludedir
2762 @ovindex oldincludedir
2763 The directory for installing C header files for non-GCC compilers.
2768 The directory for installing PDF documentation.
2773 The common installation prefix for all files. If @var{exec_prefix}
2774 is defined to a different value, @var{prefix} is used only for
2775 architecture-independent files.
2780 The directory for installing PostScript documentation.
2785 The directory for installing executables that system
2789 @defvar sharedstatedir
2790 @ovindex sharedstatedir
2791 The directory for installing modifiable architecture-independent data.
2796 The directory for installing read-only single-machine data.
2800 Most of these variables have values that rely on @code{prefix} or
2801 @code{exec_prefix}. It is deliberate that the directory output
2802 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2803 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2804 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2806 This behavior is mandated by the GNU Coding Standards, so that when
2811 she can still specify a different prefix from the one specified to
2812 @command{configure}, in which case, if needed, the package should hard
2813 code dependencies corresponding to the make-specified prefix.
2816 she can specify a different installation location, in which case the
2817 package @emph{must} still depend on the location which was compiled in
2818 (i.e., never recompile when @samp{make install} is run). This is an
2819 extremely important feature, as many people may decide to install all
2820 the files of a package grouped together, and then install links from
2821 the final locations to there.
2824 In order to support these features, it is essential that
2825 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2826 so that its value can be expanded based
2827 on the current value of @code{prefix}.
2829 A corollary is that you should not use these variables except in
2830 makefiles. For instance, instead of trying to evaluate @code{datadir}
2831 in @file{configure} and hard-coding it in makefiles using
2832 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2834 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2835 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2837 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2838 @code{bindir} and friends in your shell scripts and other files; instead,
2839 let @command{make} manage their replacement. For instance Autoconf
2840 ships templates of its shell scripts ending with @samp{.in}, and uses a
2841 makefile snippet similar to the following to build scripts like
2842 @command{autoheader} and @command{autom4te}:
2847 -e 's|@@bindir[@@]|$(bindir)|g' \
2848 -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2849 -e 's|@@prefix[@@]|$(prefix)|g'
2853 autoheader autom4te: Makefile
2856 test -f ./$@@.in || srcdir=$(srcdir)/; \
2857 $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2864 autoheader: $(srcdir)/autoheader.in
2865 autom4te: $(srcdir)/autom4te.in
2869 Some details are noteworthy:
2872 @item @samp{@@bindir[@@]}
2873 The brackets prevent @command{configure} from replacing
2874 @samp{@@bindir@@} in the Sed expression itself.
2875 Brackets are preferable to a backslash here, since
2876 Posix says @samp{\@@} is not portable.
2878 @item @samp{$(bindir)}
2879 Don't use @samp{@@bindir@@}! Use the matching makefile variable
2882 @item @samp{$(pkgdatadir)}
2883 The example takes advantage of the variable @samp{$(pkgdatadir)}
2884 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2887 Don't use @samp{/} in the Sed expressions that replace file names since
2889 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2890 Use a shell metacharacter instead, such as @samp{|}.
2892 @item special characters
2893 File names, file name components, and the value of @code{VPATH} should
2894 not contain shell metacharacters or white
2895 space. @xref{Special Chars in Variables}.
2897 @item dependency on @file{Makefile}
2898 Since @code{edit} uses values that depend on the configuration specific
2899 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2900 the output depends on @file{Makefile}, not @file{configure.ac}.
2903 The main rule is generic, and uses @samp{$@@} extensively to
2904 avoid the need for multiple copies of the rule.
2906 @item Separated dependencies and single suffix rules
2907 You can't use them! The above snippet cannot be (portably) rewritten
2911 autoconf autoheader: Makefile
2921 @xref{Single Suffix Rules}, for details.
2923 @item @samp{$(srcdir)}
2924 Be sure to specify the name of the source directory,
2925 otherwise the package won't support separated builds.
2928 For the more specific installation of Erlang libraries, the following variables
2931 @defvar ERLANG_INSTALL_LIB_DIR
2932 @ovindex ERLANG_INSTALL_LIB_DIR
2933 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2934 The common parent directory of Erlang library installation directories.
2935 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2936 macro in @file{configure.ac}.
2939 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2940 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2941 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2942 The installation directory for Erlang library @var{library}.
2943 This variable is set by using the
2944 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2945 macro in @file{configure.ac}.
2948 @xref{Erlang Libraries}, for details.
2951 @node Changed Directory Variables
2952 @subsection Changed Directory Variables
2953 @cindex @file{datarootdir}
2955 In Autoconf 2.60, the set of directory variables has changed, and the
2956 defaults of some variables have been adjusted
2957 (@pxref{Installation Directory Variables}) to changes in the
2958 GNU Coding Standards. Notably, @file{datadir}, @file{infodir}, and
2959 @file{mandir} are now expressed in terms of @file{datarootdir}. If you are
2960 upgrading from an earlier Autoconf version, you may need to adjust your files
2961 to ensure that the directory variables are substituted correctly
2962 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2963 in place. For example, in a @file{Makefile.in}, adding
2966 datarootdir = @@datarootdir@@
2970 is usually sufficient. If you use Automake to create @file{Makefile.in},
2971 it will add this for you.
2973 To help with the transition, Autoconf warns about files that seem to use
2974 @code{datarootdir} without defining it. In some cases, it then expands
2975 the value of @code{$datarootdir} in substitutions of the directory
2976 variables. The following example shows such a warning:
2979 $ @kbd{cat configure.ac}
2981 AC_CONFIG_FILES([Makefile])
2983 $ @kbd{cat Makefile.in}
2985 datadir = @@datadir@@
2988 configure: creating ./config.status
2989 config.status: creating Makefile
2990 config.status: WARNING:
2991 Makefile.in seems to ignore the --datarootdir setting
2992 $ @kbd{cat Makefile}
2994 datadir = $@{prefix@}/share
2997 Usually one can easily change the file to accommodate both older and newer
3001 $ @kbd{cat Makefile.in}
3003 datarootdir = @@datarootdir@@
3004 datadir = @@datadir@@
3006 configure: creating ./config.status
3007 config.status: creating Makefile
3008 $ @kbd{cat Makefile}
3010 datarootdir = $@{prefix@}/share
3011 datadir = $@{datarootdir@}
3014 @acindex{DATAROOTDIR_CHECKED}
3015 In some cases, however, the checks may not be able to detect that a suitable
3016 initialization of @code{datarootdir} is in place, or they may fail to detect
3017 that such an initialization is necessary in the output file. If, after
3018 auditing your package, there are still spurious @file{configure} warnings about
3019 @code{datarootdir}, you may add the line
3022 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3026 to your @file{configure.ac} to disable the warnings. This is an exception
3027 to the usual rule that you should not define a macro whose name begins with
3028 @code{AC_} (@pxref{Macro Names}).
3032 @node Build Directories
3033 @subsection Build Directories
3034 @cindex Build directories
3035 @cindex Directories, build
3037 You can support compiling a software package for several architectures
3038 simultaneously from the same copy of the source code. The object files
3039 for each architecture are kept in their own directory.
3041 To support doing this, @command{make} uses the @code{VPATH} variable to
3042 find the files that are in the source directory. GNU Make
3043 can do this. Most other recent @command{make} programs can do this as
3044 well, though they may have difficulties and it is often simpler to
3045 recommend GNU @command{make} (@pxref{VPATH and Make}). Older
3046 @command{make} programs do not support @code{VPATH}; when using them, the
3047 source code must be in the same directory as the object files.
3049 If you are using GNU Automake, the remaining details in this
3050 section are already covered for you, based on the contents of your
3051 @file{Makefile.am}. But if you are using Autoconf in isolation, then
3052 supporting @code{VPATH} requires the following in your
3060 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3063 @command{configure} substitutes the correct value for @code{srcdir} when
3064 it produces @file{Makefile}.
3066 Do not use the @command{make} variable @code{$<}, which expands to the
3067 file name of the file in the source directory (found with @code{VPATH}),
3068 except in implicit rules. (An implicit rule is one such as @samp{.c.o},
3069 which tells how to create a @file{.o} file from a @file{.c} file.) Some
3070 versions of @command{make} do not set @code{$<} in explicit rules; they
3071 expand it to an empty value.
3073 Instead, Make command lines should always refer to source
3074 files by prefixing them with @samp{$(srcdir)/}. For example:
3077 time.info: time.texinfo
3078 $(MAKEINFO) '$(srcdir)/time.texinfo'
3081 @node Automatic Remaking
3082 @subsection Automatic Remaking
3083 @cindex Automatic remaking
3084 @cindex Remaking automatically
3086 You can put rules like the following in the top-level @file{Makefile.in}
3087 for a package to automatically update the configuration information when
3088 you change the configuration files. This example includes all of the
3089 optional files, such as @file{aclocal.m4} and those related to
3090 configuration header files. Omit from the @file{Makefile.in} rules for
3091 any of these files that your package does not use.
3093 The @samp{$(srcdir)/} prefix is included because of limitations in the
3094 @code{VPATH} mechanism.
3096 The @file{stamp-} files are necessary because the timestamps of
3097 @file{config.h.in} and @file{config.h} are not changed if remaking
3098 them does not change their contents. This feature avoids unnecessary
3099 recompilation. You should include the file @file{stamp-h.in} in your
3100 package's distribution, so that @command{make} considers
3101 @file{config.h.in} up to date. Don't use @command{touch}
3102 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3103 @command{echo} (using
3104 @command{date} would cause needless differences, hence CVS
3109 $(srcdir)/configure: configure.ac aclocal.m4
3110 cd '$(srcdir)' && autoconf
3112 # autoheader might not change config.h.in, so touch a stamp file.
3113 $(srcdir)/config.h.in: stamp-h.in
3114 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3115 cd '$(srcdir)' && autoheader
3116 echo timestamp > '$(srcdir)/stamp-h.in'
3119 stamp-h: config.h.in config.status
3122 Makefile: Makefile.in config.status
3125 config.status: configure
3126 ./config.status --recheck
3131 (Be careful if you copy these lines directly into your makefile, as you
3132 need to convert the indented lines to start with the tab character.)
3134 In addition, you should use
3137 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3141 so @file{config.status} ensures that @file{config.h} is considered up to
3142 date. @xref{Output}, for more information about @code{AC_OUTPUT}.
3144 @xref{config.status Invocation}, for more examples of handling
3145 configuration-related dependencies.
3147 @node Configuration Headers
3148 @section Configuration Header Files
3149 @cindex Configuration Header
3150 @cindex @file{config.h}
3152 When a package contains more than a few tests that define C preprocessor
3153 symbols, the command lines to pass @option{-D} options to the compiler
3154 can get quite long. This causes two problems. One is that the
3155 @command{make} output is hard to visually scan for errors. More
3156 seriously, the command lines can exceed the length limits of some
3157 operating systems. As an alternative to passing @option{-D} options to
3158 the compiler, @command{configure} scripts can create a C header file
3159 containing @samp{#define} directives. The @code{AC_CONFIG_HEADERS}
3160 macro selects this kind of output. Though it can be called anywhere
3161 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3162 it right after @code{AC_INIT}.
3164 The package should @samp{#include} the configuration header file before
3165 any other header files, to prevent inconsistencies in declarations (for
3166 example, if it redefines @code{const}).
3168 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3169 option (or @option{-I..}; whichever directory contains @file{config.h}).
3170 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3171 the directory of the currently read file, i.e., the source directory, not
3172 the build directory.
3174 With the appropriate @option{-I} option, you can use
3175 @samp{#include <config.h>}. Actually, it's a good habit to use it,
3176 because in the rare case when the source directory contains another
3177 @file{config.h}, the build directory should be searched first.
3180 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3181 @acindex{CONFIG_HEADERS}
3182 @cvindex HAVE_CONFIG_H
3183 This macro is one of the instantiating macros; see @ref{Configuration
3184 Actions}. Make @code{AC_OUTPUT} create the file(s) in the
3185 blank-or-newline-separated list @var{header} containing C preprocessor
3186 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3187 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3188 The usual name for @var{header} is @file{config.h}.
3190 If @var{header} already exists and its contents are identical to what
3191 @code{AC_OUTPUT} would put in it, it is left alone. Doing this allows
3192 making some changes in the configuration without needlessly causing
3193 object files that depend on the header file to be recompiled.
3195 Usually the input file is named @file{@var{header}.in}; however, you can
3196 override the input file name by appending to @var{header} a
3197 colon-separated list of input files. For example, you might need to make
3198 the input file name acceptable to DOS variants:
3201 AC_CONFIG_HEADERS([config.h:config.hin])
3208 This macro is defined as the name of the first declared config header
3209 and undefined if no config headers have been declared up to this point.
3210 A third-party macro may, for example, require use of a config header
3211 without invoking AC_CONFIG_HEADERS twice, like this:
3214 AC_CONFIG_COMMANDS_PRE(
3215 [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3220 @xref{Configuration Actions}, for more details on @var{header}.
3223 * Header Templates:: Input for the configuration headers
3224 * autoheader Invocation:: How to create configuration templates
3225 * Autoheader Macros:: How to specify CPP templates
3228 @node Header Templates
3229 @subsection Configuration Header Templates
3230 @cindex Configuration Header Template
3231 @cindex Header templates
3232 @cindex @file{config.h.in}
3234 Your distribution should contain a template file that looks as you want
3235 the final header file to look, including comments, with @code{#undef}
3236 statements which are used as hooks. For example, suppose your
3237 @file{configure.ac} makes these calls:
3240 AC_CONFIG_HEADERS([conf.h])
3241 AC_CHECK_HEADERS([unistd.h])
3245 Then you could have code like the following in @file{conf.h.in}.
3246 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3247 to 1, if and only if the system has @file{unistd.h}.
3251 /* Define as 1 if you have unistd.h. */
3252 #undef HAVE_UNISTD_H
3256 The format of the template file is stricter than what the C preprocessor
3257 is required to accept. A directive line should contain only whitespace,
3258 @samp{#undef}, and @samp{HAVE_UNISTD_H}. The use of @samp{#define}
3259 instead of @samp{#undef}, or of comments on the same line as
3260 @samp{#undef}, is strongly discouraged. Each hook should only be listed
3261 once. Other preprocessor lines, such as @samp{#ifdef} or
3262 @samp{#include}, are copied verbatim from the template into the
3265 Since it is a tedious task to keep a template header up to date, you may
3266 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3268 During the instantiation of the header, each @samp{#undef} line in the
3269 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3270 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3271 been executed during the @command{configure} run, the @samp{#undef} line is
3272 commented out. (This is important, e.g., for @samp{_POSIX_SOURCE}:
3273 on many systems, it can be implicitly defined by the compiler, and
3274 undefining it in the header would then break compilation of subsequent
3277 Currently, @emph{all} remaining @samp{#undef} lines in the header
3278 template are commented out, whether or not there was a corresponding
3279 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3280 for future releases of Autoconf.
3282 Generally speaking, since you should not use @samp{#define}, and you
3283 cannot guarantee whether a @samp{#undef} directive in the header
3284 template will be converted to a @samp{#define} or commented out in the
3285 generated header file, the template file cannot be used for conditional
3286 definition effects. Consequently, if you need to use the construct
3297 you must place it outside of the template.
3298 If you absolutely need to hook it to the config header itself, please put
3299 the directives to a separate file, and @samp{#include} that file from the
3300 config header template. If you are using @command{autoheader}, you would
3301 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3304 @node autoheader Invocation
3305 @subsection Using @command{autoheader} to Create @file{config.h.in}
3306 @cindex @command{autoheader}
3308 The @command{autoheader} program can create a template file of C
3309 @samp{#define} statements for @command{configure} to use.
3310 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3311 @file{configure} sources to determine the name of the template.
3312 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3313 input file name, @command{autoheader} uses the first one.)
3315 It is recommended that only one input file is used. If you want to append
3316 a boilerplate code, it is preferable to use
3317 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3318 File @file{conf_post.h} is not processed during the configuration then,
3319 which make things clearer. Analogically, @code{AH_TOP} can be used to
3320 prepend a boilerplate code.
3322 In order to do its job, @command{autoheader} needs you to document all
3323 of the symbols that you might use. Typically this is done via an
3324 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3325 is a literal symbol and whose third argument describes the symbol
3326 (@pxref{Defining Symbols}). Alternatively, you can use
3327 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3328 suitable input file for a subsequent configuration header file.
3329 Symbols defined by Autoconf's builtin tests are already documented properly;
3330 you need to document only those that you
3333 You might wonder why @command{autoheader} is needed: after all, why
3334 would @command{configure} need to ``patch'' a @file{config.h.in} to
3335 produce a @file{config.h} instead of just creating @file{config.h} from
3336 scratch? Well, when everything rocks, the answer is just that we are
3337 wasting our time maintaining @command{autoheader}: generating
3338 @file{config.h} directly is all that is needed. When things go wrong,
3339 however, you'll be thankful for the existence of @command{autoheader}.
3341 The fact that the symbols are documented is important in order to
3342 @emph{check} that @file{config.h} makes sense. The fact that there is a
3343 well-defined list of symbols that should be defined (or not) is
3344 also important for people who are porting packages to environments where
3345 @command{configure} cannot be run: they just have to @emph{fill in the
3348 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3350 If you give @command{autoheader} an argument, it uses that file instead
3351 of @file{configure.ac} and writes the header file to the standard output
3352 instead of to @file{config.h.in}. If you give @command{autoheader} an
3353 argument of @option{-}, it reads the standard input instead of
3354 @file{configure.ac} and writes the header file to the standard output.
3356 @command{autoheader} accepts the following options:
3361 Print a summary of the command line options and exit.
3365 Print the version number of Autoconf and exit.
3369 Report processing steps.
3373 Don't remove the temporary files.
3377 Remake the template file even if newer than its input files.
3379 @item --include=@var{dir}
3381 Append @var{dir} to the include path. Multiple invocations accumulate.
3383 @item --prepend-include=@var{dir}
3385 Prepend @var{dir} to the include path. Multiple invocations accumulate.
3387 @item --warnings=@var{category}
3388 @itemx -W @var{category}
3390 Report the warnings related to @var{category} (which can actually be a
3391 comma separated list). Current categories include:
3395 report the uses of obsolete constructs
3398 report all the warnings
3404 treats warnings as errors
3406 @item no-@var{category}
3407 disable warnings falling into @var{category}
3414 @node Autoheader Macros
3415 @subsection Autoheader Macros
3416 @cindex Autoheader macros
3418 @command{autoheader} scans @file{configure.ac} and figures out which C
3419 preprocessor symbols it might define. It knows how to generate
3420 templates for symbols defined by @code{AC_CHECK_HEADERS},
3421 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3422 symbol, you must define a template for it. If there are missing
3423 templates, @command{autoheader} fails with an error message.
3425 The template for a @var{symbol} is created
3426 by @command{autoheader} from
3427 the @var{description} argument to an @code{AC_DEFINE};
3428 see @ref{Defining Symbols}.
3430 For special needs, you can use the following macros.
3433 @defmac AH_TEMPLATE (@var{key}, @var{description})
3435 Tell @command{autoheader} to generate a template for @var{key}. This macro
3436 generates standard templates just like @code{AC_DEFINE} when a
3437 @var{description} is given.
3442 AH_TEMPLATE([CRAY_STACKSEG_END],
3443 [Define to one of _getb67, GETB67, getb67
3444 for Cray-2 and Cray-YMP systems. This
3445 function is required for alloca.c support
3450 generates the following template, with the description properly
3454 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3455 Cray-YMP systems. This function is required for alloca.c
3456 support on those systems. */
3457 #undef CRAY_STACKSEG_END
3462 @defmac AH_VERBATIM (@var{key}, @var{template})
3464 Tell @command{autoheader} to include the @var{template} as-is in the header
3465 template file. This @var{template} is associated with the @var{key},
3466 which is used to sort all the different templates and guarantee their
3467 uniqueness. It should be a symbol that can be defined via @code{AC_DEFINE}.
3471 @defmac AH_TOP (@var{text})
3473 Include @var{text} at the top of the header template file.
3477 @defmac AH_BOTTOM (@var{text})
3479 Include @var{text} at the bottom of the header template file.
3483 Please note that @var{text} gets included ``verbatim'' to the template file,
3484 not to the resulting config header, so it can easily get mangled when the
3485 template is processed. There is rarely a need for something other than
3488 AH_BOTTOM([#include <custom.h>])
3493 @node Configuration Commands
3494 @section Running Arbitrary Configuration Commands
3495 @cindex Configuration commands
3496 @cindex Commands for configuration
3498 You can execute arbitrary commands before, during, and after
3499 @file{config.status} is run. The three following macros accumulate the
3500 commands to run when they are called multiple times.
3501 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3502 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3504 @anchor{AC_CONFIG_COMMANDS}
3505 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3506 @acindex{CONFIG_COMMANDS}
3507 Specify additional shell commands to run at the end of
3508 @file{config.status}, and shell commands to initialize any variables
3509 from @command{configure}. Associate the commands with @var{tag}.
3510 Since typically the @var{cmds} create a file, @var{tag} should
3511 naturally be the name of that file. If needed, the directory hosting
3512 @var{tag} is created. This macro is one of the instantiating macros;
3513 see @ref{Configuration Actions}.
3515 Here is an unrealistic example:
3518 AC_CONFIG_COMMANDS([fubar],
3519 [echo this is extra $fubar, and so on.],
3523 Here is a better one:
3525 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3529 The following two macros look similar, but in fact they are not of the same
3530 breed: they are executed directly by @file{configure}, so you cannot use
3531 @file{config.status} to rerun them.
3533 @c Yet it is good to leave them here. The user sees them together and
3534 @c decides which best fits their needs.
3536 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3537 @acindex{CONFIG_COMMANDS_PRE}
3538 Execute the @var{cmds} right before creating @file{config.status}.
3540 This macro presents the last opportunity to call @code{AC_SUBST},
3541 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3544 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3545 @acindex{CONFIG_COMMANDS_POST}
3546 Execute the @var{cmds} right after creating @file{config.status}.
3552 @node Configuration Links
3553 @section Creating Configuration Links
3554 @cindex Configuration links
3555 @cindex Links for configuration
3557 You may find it convenient to create links whose destinations depend upon
3558 results of tests. One can use @code{AC_CONFIG_COMMANDS} but the
3559 creation of relative symbolic links can be delicate when the package is
3560 built in a directory different from the source directory.
3562 @anchor{AC_CONFIG_LINKS}
3563 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3565 @acindex{CONFIG_LINKS}
3567 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3568 the corresponding link name @var{dest}. Makes a symbolic link if
3569 possible, otherwise a hard link if possible, otherwise a copy. The
3570 @var{dest} and @var{source} names should be relative to the top level
3571 source or build directory. This macro is one of the instantiating
3572 macros; see @ref{Configuration Actions}.
3574 For example, this call:
3577 AC_CONFIG_LINKS([host.h:config/$machine.h
3578 object.h:config/$obj_format.h])
3582 creates in the current directory @file{host.h} as a link to
3583 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3584 link to @file{@var{srcdir}/config/$obj_format.h}.
3586 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3587 impossible for @samp{config.status} to guess the links to establish.
3591 ./config.status host.h object.h
3594 to create the links.
3599 @node Subdirectories
3600 @section Configuring Other Packages in Subdirectories
3601 @cindex Configure subdirectories
3602 @cindex Subdirectory configure
3604 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3605 makefiles in subdirectories. However, @command{configure} scripts
3606 that control more than one independent package can use
3607 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3608 packages in subdirectories.
3610 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3611 @acindex{CONFIG_SUBDIRS}
3613 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3614 @var{dir} in the given blank-or-newline-separated list. Each @var{dir} should
3615 be a literal, i.e., please do not use:
3618 if test "x$package_foo_enabled" = xyes; then
3619 my_subdirs="$my_subdirs foo"
3621 AC_CONFIG_SUBDIRS([$my_subdirs])
3625 because this prevents @samp{./configure --help=recursive} from
3626 displaying the options of the package @code{foo}. Instead, you should
3630 if test "x$package_foo_enabled" = xyes; then
3631 AC_CONFIG_SUBDIRS([foo])
3635 If a given @var{dir} is not found, an error is reported: if the
3636 subdirectory is optional, write:
3639 if test -d "$srcdir/foo"; then
3640 AC_CONFIG_SUBDIRS([foo])
3644 @c NB: Yes, below we mean configure.in, not configure.ac.
3645 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3646 of @command{configure}. This is for packages that might use a
3647 non-Autoconf script @command{Configure}, which can't be called through a
3648 wrapper @command{configure} since it would be the same file on
3649 case-insensitive file systems. Likewise, if a @var{dir} contains
3650 @file{configure.in} but no @command{configure}, the Cygnus
3651 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3653 The subdirectory @command{configure} scripts are given the same command
3654 line options that were given to this @command{configure} script, with minor
3655 changes if needed, which include:
3659 adjusting a relative name for the cache file;
3662 adjusting a relative name for the source directory;
3665 propagating the current value of @code{$prefix}, including if it was
3666 defaulted, and if the default values of the top level and of the subdirectory
3667 @file{configure} differ.
3670 This macro also sets the output variable @code{subdirs} to the list of
3671 directories @samp{@var{dir} @dots{}}. Make rules can use
3672 this variable to determine which subdirectories to recurse into.
3674 This macro may be called multiple times.
3677 @node Default Prefix
3678 @section Default Prefix
3679 @cindex Install prefix
3680 @cindex Prefix for install
3682 By default, @command{configure} sets the prefix for files it installs to
3683 @file{/usr/local}. The user of @command{configure} can select a different
3684 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3685 There are two ways to change the default: when creating
3686 @command{configure}, and when running it.
3688 Some software packages might want to install in a directory other than
3689 @file{/usr/local} by default. To accomplish that, use the
3690 @code{AC_PREFIX_DEFAULT} macro.
3692 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3693 @acindex{PREFIX_DEFAULT}
3694 Set the default installation prefix to @var{prefix} instead of
3698 It may be convenient for users to have @command{configure} guess the
3699 installation prefix from the location of a related program that they
3700 have already installed. If you wish to do that, you can call
3701 @code{AC_PREFIX_PROGRAM}.
3703 @anchor{AC_PREFIX_PROGRAM}
3704 @defmac AC_PREFIX_PROGRAM (@var{program})
3705 @acindex{PREFIX_PROGRAM}
3706 If the user did not specify an installation prefix (using the
3707 @option{--prefix} option), guess a value for it by looking for
3708 @var{program} in @env{PATH}, the way the shell does. If @var{program}
3709 is found, set the prefix to the parent of the directory containing
3710 @var{program}, else default the prefix as described above
3711 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}). For example, if
3712 @var{program} is @code{gcc} and the @env{PATH} contains
3713 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3718 @c ======================================================== Existing tests
3720 @node Existing Tests
3721 @chapter Existing Tests
3723 These macros test for particular system features that packages might
3724 need or want to use. If you need to test for a kind of feature that
3725 none of these macros check for, you can probably do it by calling
3726 primitive test macros with appropriate arguments (@pxref{Writing
3729 These tests print messages telling the user which feature they're
3730 checking for, and what they find. They cache their results for future
3731 @command{configure} runs (@pxref{Caching Results}).
3733 Some of these macros set output variables. @xref{Makefile
3734 Substitutions}, for how to get their values. The phrase ``define
3735 @var{name}'' is used below as a shorthand to mean ``define the C
3736 preprocessor symbol @var{name} to the value 1''. @xref{Defining
3737 Symbols}, for how to get those symbol definitions into your program.
3740 * Common Behavior:: Macros' standard schemes
3741 * Alternative Programs:: Selecting between alternative programs
3742 * Files:: Checking for the existence of files
3743 * Libraries:: Library archives that might be missing
3744 * Library Functions:: C library functions that might be missing
3745 * Header Files:: Header files that might be missing
3746 * Declarations:: Declarations that may be missing
3747 * Structures:: Structures or members that might be missing
3748 * Types:: Types that might be missing
3749 * Compilers and Preprocessors:: Checking for compiling programs
3750 * System Services:: Operating system services
3751 * Posix Variants:: Special kludges for specific Posix variants
3752 * Erlang Libraries:: Checking for the existence of Erlang libraries
3755 @node Common Behavior
3756 @section Common Behavior
3757 @cindex Common autoconf behavior
3759 Much effort has been expended to make Autoconf easy to learn. The most
3760 obvious way to reach this goal is simply to enforce standard interfaces
3761 and behaviors, avoiding exceptions as much as possible. Because of
3762 history and inertia, unfortunately, there are still too many exceptions
3763 in Autoconf; nevertheless, this section describes some of the common
3767 * Standard Symbols:: Symbols defined by the macros
3768 * Default Includes:: Includes used by the generic macros
3771 @node Standard Symbols
3772 @subsection Standard Symbols
3773 @cindex Standard symbols
3775 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3776 their test transform their @var{argument} values to a standard alphabet.
3777 First, @var{argument} is converted to upper case and any asterisks
3778 (@samp{*}) are each converted to @samp{P}. Any remaining characters
3779 that are not alphanumeric are converted to underscores.
3784 AC_CHECK_TYPES([struct $Expensive*])
3788 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3792 @node Default Includes
3793 @subsection Default Includes
3794 @cindex Default includes
3795 @cindex Includes, default
3797 Several tests depend upon a set of header files. Since these headers
3798 are not universally available, tests actually have to provide a set of
3799 protected includes, such as:
3803 #ifdef TIME_WITH_SYS_TIME
3804 # include <sys/time.h>
3807 # ifdef HAVE_SYS_TIME_H
3808 # include <sys/time.h>
3817 Unless you know exactly what you are doing, you should avoid using
3818 unconditional includes, and check the existence of the headers you
3819 include beforehand (@pxref{Header Files}).
3821 Most generic macros use the following macro to provide the default set
3824 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3825 @acindex{INCLUDES_DEFAULT}
3826 Expand to @var{include-directives} if defined, otherwise to:
3831 #ifdef HAVE_SYS_TYPES_H
3832 # include <sys/types.h>
3834 #ifdef HAVE_SYS_STAT_H
3835 # include <sys/stat.h>
3838 # include <stdlib.h>
3839 # include <stddef.h>
3841 # ifdef HAVE_STDLIB_H
3842 # include <stdlib.h>
3845 #ifdef HAVE_STRING_H
3846 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3847 # include <memory.h>
3849 # include <string.h>
3851 #ifdef HAVE_STRINGS_H
3852 # include <strings.h>
3854 #ifdef HAVE_INTTYPES_H
3855 # include <inttypes.h>
3857 #ifdef HAVE_STDINT_H
3858 # include <stdint.h>
3860 #ifdef HAVE_UNISTD_H
3861 # include <unistd.h>
3866 If the default includes are used, then check for the presence of these
3867 headers and their compatibility, i.e., you don't need to run
3868 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3870 These headers are checked for in the same order as they are included.
3871 For instance, on some systems @file{string.h} and @file{strings.h} both
3872 exist, but conflict. Then @code{HAVE_STRING_H} is defined, not
3873 @code{HAVE_STRINGS_H}.
3876 @node Alternative Programs
3877 @section Alternative Programs
3878 @cindex Programs, checking
3880 These macros check for the presence or behavior of particular programs.
3881 They are used to choose between several alternative programs and to
3882 decide what to do once one has been chosen. If there is no macro
3883 specifically defined to check for a program you need, and you don't need
3884 to check for any special properties of it, then you can use one of the
3885 general program-check macros.
3888 * Particular Programs:: Special handling to find certain programs
3889 * Generic Programs:: How to find other programs
3892 @node Particular Programs
3893 @subsection Particular Program Checks
3895 These macros check for particular programs---whether they exist, and
3896 in some cases whether they support certain features.
3902 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3903 order, and set output variable @code{AWK} to the first one that is found.
3904 It tries @code{gawk} first because that is reported to be the
3905 best implementation. The result can be overridden by setting the
3906 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3909 @defmac AC_PROG_GREP
3913 Look for the best available @code{grep} or @code{ggrep} that accepts the
3914 longest input lines possible, and that supports multiple @option{-e} options.
3915 Set the output variable @code{GREP} to whatever is chosen.
3916 @xref{grep, , Limitations of Usual Tools}, for more information about
3917 portability problems with the @command{grep} command family. The result
3918 can be overridden by setting the @code{GREP} variable and is cached in the
3919 @code{ac_cv_path_GREP} variable.
3922 @defmac AC_PROG_EGREP
3923 @acindex{PROG_EGREP}
3926 Check whether @code{$GREP -E} works, or else look for the best available
3927 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3928 Set the output variable @code{EGREP} to whatever is chosen. The result
3929 can be overridden by setting the @code{EGREP} variable and is cached in the
3930 @code{ac_cv_path_EGREP} variable.
3933 @defmac AC_PROG_FGREP
3934 @acindex{PROG_FGREP}
3937 Check whether @code{$GREP -F} works, or else look for the best available
3938 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3939 Set the output variable @code{FGREP} to whatever is chosen. The result
3940 can be overridden by setting the @code{FGREP} variable and is cached in the
3941 @code{ac_cv_path_FGREP} variable.
3944 @defmac AC_PROG_INSTALL
3945 @acindex{PROG_INSTALL}
3947 @ovindex INSTALL_PROGRAM
3948 @ovindex INSTALL_DATA
3949 @ovindex INSTALL_SCRIPT
3950 @caindex path_install
3951 Set output variable @code{INSTALL} to the name of a BSD-compatible
3952 @command{install} program, if one is found in the current @env{PATH}.
3953 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3954 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3955 default directories) to determine @var{dir} (@pxref{Output}). Also set
3956 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3957 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3959 @samp{@@INSTALL@@} is special, as its value may vary for different
3960 configuration files.
3962 This macro screens out various instances of @command{install} known not to
3963 work. It prefers to find a C program rather than a shell script, for
3964 speed. Instead of @file{install-sh}, it can also use @file{install.sh},
3965 but that name is obsolete because some @command{make} programs have a rule
3966 that creates @file{install} from it if there is no makefile. Further, this
3967 macro requires @command{install} to be able to install multiple files into a
3968 target directory in a single invocation.
3970 Autoconf comes with a copy of @file{install-sh} that you can use. If
3971 you use @code{AC_PROG_INSTALL}, you must include either
3972 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3973 @command{configure} produces an error message saying it can't find
3974 them---even if the system you're on has a good @command{install} program.
3975 This check is a safety measure to prevent you from accidentally leaving
3976 that file out, which would prevent your package from installing on
3977 systems that don't have a BSD-compatible @command{install} program.
3979 If you need to use your own installation program because it has features
3980 not found in standard @command{install} programs, there is no reason to use
3981 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3982 @file{Makefile.in} files.
3984 The result of the test can be overridden by setting the variable
3985 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
3988 @defmac AC_PROG_MKDIR_P
3989 @acindex{PROG_MKDIR_P}
3992 Set output variable @code{MKDIR_P} to a program that ensures that for
3993 each argument, a directory named by this argument exists, creating it
3994 and its parent directories if needed, and without race conditions when
3995 two instances of the program attempt to make the same directory at
3996 nearly the same time.
3998 This macro uses the @samp{mkdir -p} command if possible. Otherwise, it
3999 falls back on invoking @command{install-sh} with the @option{-d} option,
4000 so your package should
4001 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4002 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4003 is vulnerable to race conditions, so if you want to support parallel
4005 different packages into the same directory you need to make sure you
4006 have an up-to-date @file{install-sh}. In particular, be careful about
4007 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4009 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4010 in M4sh}), but it sets an output variable intended for use in other
4011 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4012 @command{configure}. Also, @code{AS_MKDIR_P} does not accept options,
4013 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4014 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4015 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4016 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4017 Finally, @code{AS_MKDIR_P} does not check for race condition
4018 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4020 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4021 configuration files.
4023 The result of the test can be overridden by setting the variable
4024 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4027 @anchor{AC_PROG_LEX}
4032 @cvindex YYTEXT_POINTER
4033 @ovindex LEX_OUTPUT_ROOT
4035 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4036 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4037 place. Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4038 @option{-ll}, if found. If neither variant is available, set @code{LEX}
4039 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4040 alongside the source @file{file.l}, this default allows users without a
4041 lexer generator to still build the package even if the timestamp for
4042 @file{file.l} is inadvertantly changed.
4044 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4045 of to @samp{char []}. Also set output variable @code{LEX_OUTPUT_ROOT} to
4046 the base of the file name that the lexer generates; usually
4047 @file{lex.yy}, but sometimes something else. These results vary
4048 according to whether @code{lex} or @code{flex} is being used.
4050 You are encouraged to use Flex in your sources, since it is both more
4051 pleasant to use than plain Lex and the C source it produces is portable.
4052 In order to ensure portability, however, you must either provide a
4053 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4054 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4055 statement in the scanner's source. Once this done, the scanner is
4056 portable (unless @emph{you} felt free to use nonportable constructs) and
4057 does not depend on any library. In this case, and in this case only, it
4058 is suggested that you use this Autoconf snippet:
4062 if test "x$LEX" != xflex; then
4063 LEX="$SHELL $missing_dir/missing flex"
4064 AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4065 AC_SUBST([LEXLIB], [''])
4069 The shell script @command{missing} can be found in the Automake
4072 Remember that the user may have supplied an alternate location in
4073 @env{LEX}, so if Flex is required, it is better to check that the user
4074 provided something sufficient by parsing the output of @samp{$LEX
4075 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4077 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4078 (indirectly) this macro twice, which causes an annoying but benign
4079 ``@code{AC_PROG_LEX} invoked multiple times'' warning. Future versions
4080 of Automake will fix this issue; meanwhile, just ignore this message.
4082 As part of running the test, this macro may delete any file in the
4083 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4085 The result of this test can be influenced by setting the variable
4086 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4089 @anchor{AC_PROG_LN_S}
4090 @defmac AC_PROG_LN_S
4093 If @samp{ln -s} works on the current file system (the operating system
4094 and file system support symbolic links), set the output variable
4095 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4096 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4098 If you make a link in a directory other than the current directory, its
4099 meaning depends on whether @samp{ln} or @samp{ln -s} is used. To safely
4100 create links using @samp{$(LN_S)}, either find out which form is used
4101 and adjust the arguments, or always invoke @code{ln} in the directory
4102 where the link is to be created.
4104 In other words, it does not work to do:
4112 (cd /x && $(LN_S) foo bar)
4116 @defmac AC_PROG_RANLIB
4117 @acindex{PROG_RANLIB}
4119 @c @caindex prog_RANLIB
4120 @c @caindex prog_ac_ct_RANLIB
4121 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4122 is found, and otherwise to @samp{:} (do nothing).
4129 Set output variable @code{SED} to a Sed implementation that conforms to
4130 Posix and does not have arbitrary length limits. Report an error if no
4131 acceptable Sed is found. @xref{sed, , Limitations of Usual Tools}, for more
4132 information about portability problems with Sed.
4134 The result of this test can be overridden by setting the @code{SED} variable
4135 and is cached in the @code{ac_cv_path_SED} variable.
4138 @defmac AC_PROG_YACC
4144 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4145 -y}. Otherwise, if @code{byacc} is found, set @code{YACC} to
4146 @samp{byacc}. Otherwise set @code{YACC} to @samp{yacc}.
4147 The result of this test can be influenced by setting the variable
4148 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4151 @node Generic Programs
4152 @subsection Generic Program and File Checks
4154 These macros are used to find programs not covered by the ``particular''
4155 test macros. If you need to check the behavior of a program as well as
4156 find out whether it is present, you have to write your own test for it
4157 (@pxref{Writing Tests}). By default, these macros use the environment
4158 variable @env{PATH}. If you need to check for a program that might not
4159 be in the user's @env{PATH}, you can pass a modified path to use
4163 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4164 [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4165 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4168 You are strongly encouraged to declare the @var{variable} passed to
4169 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4170 @code{AC_ARG_VAR}, for more details.
4172 @anchor{AC_CHECK_PROG}
4173 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4174 @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4176 @acindex{CHECK_PROG}
4177 @caindex prog_@var{variable}
4178 Check whether program @var{prog-to-check-for} exists in @var{path}. If
4179 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4180 @var{value-if-not-found}, if given. Always pass over @var{reject} (an
4181 absolute file name) even if it is the first found in the search path; in
4182 that case, set @var{variable} using the absolute file name of the
4183 @var{prog-to-check-for} found that is not @var{reject}. If
4184 @var{variable} was already set, do nothing. Calls @code{AC_SUBST} for
4185 @var{variable}. The result of this test can be overridden by setting the
4186 @var{variable} variable or the cache variable
4187 @code{ac_cv_prog_@var{variable}}.
4190 @anchor{AC_CHECK_PROGS}
4191 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4192 @ovar{value-if-not-found}, @dvar{path, $PATH})
4193 @acindex{CHECK_PROGS}
4194 @caindex prog_@var{variable}
4195 Check for each program in the blank-separated list
4196 @var{progs-to-check-for} existing in the @var{path}. If one is found, set
4197 @var{variable} to the name of that program. Otherwise, continue
4198 checking the next program in the list. If none of the programs in the
4199 list are found, set @var{variable} to @var{value-if-not-found}; if
4200 @var{value-if-not-found} is not specified, the value of @var{variable}
4201 is not changed. Calls @code{AC_SUBST} for @var{variable}. The result of
4202 this test can be overridden by setting the @var{variable} variable or the
4203 cache variable @code{ac_cv_prog_@var{variable}}.
4206 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4207 @ovar{value-if-not-found}, @dvar{path, $PATH})
4208 @acindex{CHECK_TARGET_TOOL}
4209 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4210 with a prefix of the target type as determined by
4211 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4212 If the tool cannot be found with a prefix, and if the build and target
4213 types are equal, then it is also searched for without a prefix.
4215 As noted in @ref{Specifying Target Triplets}, the
4216 target is rarely specified, because most of the time it is the same
4217 as the host: it is the type of system for which any compiler tool in
4218 the package produces code. What this macro looks for is,
4219 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4220 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4221 uses to produce objects, archives or executables}.
4224 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4225 @ovar{value-if-not-found}, @dvar{path, $PATH})
4226 @acindex{CHECK_TOOL}
4227 @c @caindex prog_@var{VARIABLE}
4228 @c @caindex prog_ac_ct_@var{VARIABLE}
4229 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4230 with a prefix of the host type as specified by @option{--host}, followed by a
4231 dash. For example, if the user runs
4232 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4234 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4237 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4238 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4239 @var{path}, or to @samp{:} if neither program exists.
4241 When cross-compiling, this macro will issue a warning if no program
4242 prefixed with the host type could be found.
4243 For more information, see @ref{Specifying Target Triplets}.
4246 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4247 @ovar{value-if-not-found}, @dvar{path, $PATH})
4248 @acindex{CHECK_TARGET_TOOLS}
4249 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4250 @var{progs-to-check-for} are checked with a prefix of the target type as
4251 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4252 (@pxref{Canonicalizing}). If none of the tools can be found with a
4253 prefix, and if the build and target types are equal, then the first one
4254 without a prefix is used. If a tool is found, set @var{variable} to
4255 the name of that program. If none of the tools in the list are found,
4256 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4257 is not specified, the value of @var{variable} is not changed. Calls
4258 @code{AC_SUBST} for @var{variable}.
4261 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4262 @ovar{value-if-not-found}, @dvar{path, $PATH})
4263 @acindex{CHECK_TOOLS}
4264 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4265 @var{progs-to-check-for} are checked with a prefix of the host type as
4266 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4267 (@pxref{Canonicalizing}). If none of the tools can be found with a
4268 prefix, then the first one without a prefix is used. If a tool is found,
4269 set @var{variable} to the name of that program. If none of the tools in
4270 the list are found, set @var{variable} to @var{value-if-not-found}; if
4271 @var{value-if-not-found} is not specified, the value of @var{variable}
4272 is not changed. Calls @code{AC_SUBST} for @var{variable}.
4274 When cross-compiling, this macro will issue a warning if no program
4275 prefixed with the host type could be found.
4276 For more information, see @ref{Specifying Target Triplets}.
4279 @anchor{AC_PATH_PROG}
4280 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4281 @ovar{value-if-not-found}, @dvar{path, $PATH})
4283 @caindex path_@var{variable}
4284 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4285 name of @var{prog-to-check-for} if found. The result of this test
4286 can be overridden by setting the @var{variable} variable. A positive
4287 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4291 @anchor{AC_PATH_PROGS}
4292 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4293 @ovar{value-if-not-found}, @dvar{path, $PATH})
4294 @acindex{PATH_PROGS}
4295 @caindex path_@var{variable}
4296 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4297 are found, set @var{variable} to the absolute name of the program
4298 found. The result of this test can be overridden by setting the
4299 @var{variable} variable. A positive result of this test is cached in
4300 the @code{ac_cv_path_@var{variable}} variable.
4303 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4304 @var{progs-to-check-for}, @var{feature-test}, @
4305 @ovar{action-if-not-found}, @dvar{path, $PATH})
4306 @acindex{PATH_PROGS_FEATURE_CHECK}
4307 @caindex path_@var{variable}
4308 This macro was introduced in Autoconf 2.62. If @var{variable} is not
4309 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4310 its value. Otherwise, check for each program in the blank-separated
4311 list @var{progs-to-check-for} existing in @var{path}. For each program
4312 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4313 set to the absolute name of the candidate program. If no invocation of
4314 @var{feature-test} sets the shell variable
4315 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4316 executed. @var{feature-test} will be run even when
4317 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4318 choose a better candidate found later in @var{path}; to accept the
4319 current setting and bypass all futher checks, @var{feature-test} can
4320 execute @code{ac_path_@var{variable}_found=:}.
4322 Note that this macro has some subtle differences from
4323 @code{AC_CHECK_PROGS}. It is designed to be run inside
4324 @code{AC_CACHE_VAL}, therefore, it should have no side effects. In
4325 particular, @var{variable} is not set to the final value of
4326 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4327 run. Also, on failure, any action can be performed, whereas
4328 @code{AC_CHECK_PROGS} only performs
4329 @code{@var{variable}=@var{value-if-not-found}}.
4331 Here is an example, similar to what Autoconf uses in its own configure
4332 script. It will search for an implementation of @command{m4} that
4333 supports the @code{indir} builtin, even if it goes by the name
4334 @command{gm4} or is not the first implementation on @env{PATH}.
4337 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4338 [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4339 [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4340 test "x$m4out" = x0 \
4341 && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4342 [AC_MSG_ERROR([could not find m4 that supports indir])])])
4343 AC_SUBST([M4], [$ac_cv_path_M4])
4347 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4348 @ovar{value-if-not-found}, @dvar{path, $PATH})
4349 @acindex{PATH_TARGET_TOOL}
4350 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4351 name of the program if it is found.
4354 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4355 @ovar{value-if-not-found}, @dvar{path, $PATH})
4357 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4358 name of the program if it is found.
4360 When cross-compiling, this macro will issue a warning if no program
4361 prefixed with the host type could be found.
4362 For more information, see @ref{Specifying Target Triplets}.
4368 @cindex File, checking
4370 You might also need to check for the existence of files. Before using
4371 these macros, ask yourself whether a runtime test might not be a better
4372 solution. Be aware that, like most Autoconf macros, they test a feature
4373 of the host machine, and therefore, they die when cross-compiling.
4375 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4376 @ovar{action-if-not-found})
4377 @acindex{CHECK_FILE}
4378 @caindex file_@var{file}
4379 Check whether file @var{file} exists on the native system. If it is
4380 found, execute @var{action-if-found}, otherwise do
4381 @var{action-if-not-found}, if given. The result of this test is cached
4382 in the @code{ac_cv_file_@var{file}} variable, with characters not
4383 suitable for a variable name mapped to underscores.
4386 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4387 @ovar{action-if-not-found})
4388 @acindex{CHECK_FILES}
4389 @caindex file_@var{file}
4390 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4391 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4392 for each file found. The results of each test are cached in the
4393 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4394 a variable name mapped to underscores.
4399 @section Library Files
4400 @cindex Library, checking
4402 The following macros check for the presence of certain C, C++, or Fortran
4403 library archive files.
4405 @anchor{AC_CHECK_LIB}
4406 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4407 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4409 @caindex lib_@var{library}_@var{function}
4410 Test whether the library @var{library} is available by trying to link
4411 a test program that calls function @var{function} with the library.
4412 @var{function} should be a function provided by the library.
4414 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4415 the @var{library} argument.
4417 @var{action-if-found} is a list of shell commands to run if the link
4418 with the library succeeds; @var{action-if-not-found} is a list of shell
4419 commands to run if the link fails. If @var{action-if-found} is not
4420 specified, the default action prepends @option{-l@var{library}} to
4421 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4422 capitals). This macro is intended to support building @code{LIBS} in
4423 a right-to-left (least-dependent to most-dependent) fashion such that
4424 library dependencies are satisfied as a natural side effect of
4425 consecutive tests. Linkers are sensitive to library ordering
4426 so the order in which @code{LIBS} is generated is important to reliable
4427 detection of libraries.
4429 If linking with @var{library} results in unresolved symbols that would
4430 be resolved by linking with additional libraries, give those libraries
4431 as the @var{other-libraries} argument, separated by spaces:
4432 e.g., @option{-lXt -lX11}. Otherwise, this macro may fail to detect
4433 that @var{library} is present, because linking the test program can
4434 fail with unresolved symbols. The @var{other-libraries} argument
4435 should be limited to cases where it is desirable to test for one library
4436 in the presence of another that is not already in @code{LIBS}.
4438 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4439 in some common cases. Many standard functions like @code{gethostbyname}
4440 appear in the standard C library on some hosts, and in special libraries
4441 like @code{nsl} on other hosts. On some hosts the special libraries
4442 contain variant implementations that you may not want to use. These
4443 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4444 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4446 The result of this test is cached in the
4447 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4450 @anchor{AC_SEARCH_LIBS}
4451 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4452 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4453 @acindex{SEARCH_LIBS}
4454 @caindex search_@var{function}
4455 Search for a library defining @var{function} if it's not already
4456 available. This equates to calling
4457 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4458 no libraries, then for each library listed in @var{search-libs}.
4460 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4461 to contain @var{function}, and run @var{action-if-found}. If the
4462 function is not found, run @var{action-if-not-found}.
4464 If linking with @var{library} results in unresolved symbols that would
4465 be resolved by linking with additional libraries, give those libraries
4466 as the @var{other-libraries} argument, separated by spaces:
4467 e.g., @option{-lXt -lX11}. Otherwise, this macro fails to detect
4468 that @var{function} is present, because linking the test program
4469 always fails with unresolved symbols.
4471 The result of this test is cached in the
4472 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4473 @var{function} is already available, as @samp{no} if no library
4474 containing @var{function} was found, otherwise as the
4475 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4480 @node Library Functions
4481 @section Library Functions
4483 The following macros check for particular C library functions.
4484 If there is no macro specifically defined to check for a function you need,
4485 and you don't need to check for any special properties of
4486 it, then you can use one of the general function-check macros.
4489 * Function Portability:: Pitfalls with usual functions
4490 * Particular Functions:: Special handling to find certain functions
4491 * Generic Functions:: How to find other functions
4494 @node Function Portability
4495 @subsection Portability of C Functions
4496 @cindex Portability of C functions
4497 @cindex C function portability
4499 Most usual functions can either be missing, or be buggy, or be limited
4500 on some architectures. This section tries to make an inventory of these
4501 portability issues. By definition, this list always requires
4502 additions. Please help us keeping it as complete as possible.
4507 @prindex @code{exit}
4508 On ancient hosts, @code{exit} returned @code{int}.
4509 This is because @code{exit} predates @code{void}, and there was a long
4510 tradition of it returning @code{int}.
4512 On current hosts, the problem more likely is that @code{exit} is not
4513 declared, due to C++ problems of some sort or another. For this reason
4514 we suggest that test programs not invoke @code{exit}, but return from
4515 @code{main} instead.
4519 @prindex @code{free}
4520 The C standard says a call @code{free (NULL)} does nothing, but
4521 some old systems don't support this (e.g., NextStep).
4527 @prindex @code{isinf}
4528 @prindex @code{isnan}
4529 The C99 standard says that @code{isinf} and @code{isnan} are
4530 macros. On some systems just macros are available
4531 (e.g., HP-UX and Solaris 10), on
4532 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4533 systems only functions (e.g., IRIX 6 and Solaris 9). In some cases
4534 these functions are declared in nonstandard headers like
4535 @code{<sunmath.h>} and defined in non-default libraries like
4536 @option{-lm} or @option{-lsunmath}.
4538 The C99 @code{isinf} and @code{isnan} macros work correctly with
4539 @code{long double} arguments, but pre-C99 systems that use functions
4540 typically assume @code{double} arguments. On such a system,
4541 @code{isinf} incorrectly returns true for a finite @code{long double}
4542 argument that is outside the range of @code{double}.
4544 The best workaround for these issues is to use gnulib modules
4545 @code{isinf} and @code{isnan} (@pxref{Gnulib}). But a lighter weight
4546 solution involves code like the following.
4553 (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4554 : sizeof (x) == sizeof (double) ? isnan_d (x) \
4556 static inline int isnan_f (float x) @{ return x != x; @}
4557 static inline int isnan_d (double x) @{ return x != x; @}
4558 static inline int isnan_ld (long double x) @{ return x != x; @}
4563 (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4564 : sizeof (x) == sizeof (double) ? isinf_d (x) \
4566 static inline int isinf_f (float x)
4567 @{ return !isnan (x) && isnan (x - x); @}
4568 static inline int isinf_d (double x)
4569 @{ return !isnan (x) && isnan (x - x); @}
4570 static inline int isinf_ld (long double x)
4571 @{ return !isnan (x) && isnan (x - x); @}
4575 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4576 compilers that lack the @code{inline} keyword. Some optimizing
4577 compilers mishandle these definitions, but systems with that bug
4578 typically have many other floating point corner-case compliance problems
4579 anyway, so it's probably not worth worrying about.
4583 @prindex @code{malloc}
4584 The C standard says a call @code{malloc (0)} is implementation
4585 dependent. It can return either @code{NULL} or a new non-null pointer.
4586 The latter is more common (e.g., the GNU C Library) but is by
4587 no means universal. @code{AC_FUNC_MALLOC}
4588 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4592 @prindex @code{putenv}
4593 Posix prefers @code{setenv} to @code{putenv}; among other things,
4594 @code{putenv} is not required of all Posix implementations, but
4597 Posix specifies that @code{putenv} puts the given string directly in
4598 @code{environ}, but some systems make a copy of it instead (e.g.,
4599 glibc 2.0, or BSD). And when a copy is made, @code{unsetenv} might
4600 not free it, causing a memory leak (e.g., FreeBSD 4).
4602 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4603 environment, but this is not standard usage and it dumps core
4604 on some systems (e.g., AIX).
4606 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4607 environment, rather than inserting it with an empty value.
4609 @item @code{realloc}
4611 @prindex @code{realloc}
4612 The C standard says a call @code{realloc (NULL, size)} is equivalent
4613 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4616 @item @code{signal} handler
4618 @prindex @code{signal}
4619 @prindex @code{sigaction}
4620 Normally @code{signal} takes a handler function with a return type of
4621 @code{void}, but some old systems required @code{int} instead. Any
4622 actual @code{int} value returned is not used; this is only a
4623 difference in the function prototype demanded.
4625 All systems we know of in current use return @code{void}. The
4626 @code{int} was to support K&R C, where of course @code{void} is not
4627 available. The obsolete macro @code{AC_TYPE_SIGNAL}
4628 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4631 In most cases, it is more robust to use @code{sigaction} when it is
4632 available, rather than @code{signal}.
4634 @item @code{snprintf}
4635 @c @fuindex snprintf
4636 @prindex @code{snprintf}
4637 @c @fuindex vsnprintf
4638 @prindex @code{vsnprintf}
4639 The C99 standard says that if the output array isn't big enough
4640 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4641 truncate the output and return the number of bytes that ought to have
4642 been produced. Some older systems return the truncated length (e.g.,
4643 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4644 (e.g., earlier GNU C Library versions), and some the buffer
4645 length without truncation (e.g., 32-bit Solaris 7). Also, some buggy
4646 older systems ignore the length and overrun the buffer (e.g., 64-bit
4649 @item @code{sprintf}
4651 @prindex @code{sprintf}
4652 @c @fuindex vsprintf
4653 @prindex @code{vsprintf}
4654 The C standard says @code{sprintf} and @code{vsprintf} return the
4655 number of bytes written. On some ancient systems (SunOS 4 for
4656 instance) they return the buffer pointer instead, but these no
4657 longer need to be worried about.
4661 @prindex @code{sscanf}
4662 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4664 input string be writable (though it doesn't actually change it). This
4665 can be a problem when using @command{gcc} since it normally puts
4666 constant strings in read-only memory (@pxref{Incompatibilities,
4667 Incompatibilities of GCC, , gcc, Using and
4668 Porting the GNU Compiler Collection}). Apparently in some cases even
4669 having format strings read-only can be a problem.
4671 @item @code{strerror_r}
4672 @c @fuindex strerror_r
4673 @prindex @code{strerror_r}
4674 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4675 systems (e.g., GNU C Library version 2.2.4) provide a
4676 different version returning a @code{char *}. @code{AC_FUNC_STRERROR_R}
4677 can detect which is in use (@pxref{Particular Functions}).
4679 @item @code{strnlen}
4681 @prindex @code{strnlen}
4682 AIX 4.3 provides a broken version which produces the
4686 strnlen ("foobar", 0) = 0
4687 strnlen ("foobar", 1) = 3
4688 strnlen ("foobar", 2) = 2
4689 strnlen ("foobar", 3) = 1
4690 strnlen ("foobar", 4) = 0
4691 strnlen ("foobar", 5) = 6
4692 strnlen ("foobar", 6) = 6
4693 strnlen ("foobar", 7) = 6
4694 strnlen ("foobar", 8) = 6
4695 strnlen ("foobar", 9) = 6
4698 @item @code{sysconf}
4700 @prindex @code{sysconf}
4701 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4702 9) have @code{_SC_PAGE_SIZE} instead. This can be tested with
4707 @prindex @code{unlink}
4708 The Posix spec says that @code{unlink} causes the given file to be
4709 removed only after there are no more open file handles for it. Some
4710 non-Posix hosts have trouble with this requirement, though,
4711 and some DOS variants even corrupt the file system.
4713 @item @code{unsetenv}
4714 @c @fuindex unsetenv
4715 @prindex @code{unsetenv}
4716 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4717 can be removed with a call @code{putenv ("FOO=")}, as described under
4718 @code{putenv} above.
4720 @item @code{va_copy}
4722 @prindex @code{va_copy}
4723 The C99 standard provides @code{va_copy} for copying
4724 @code{va_list} variables. It may be available in older environments
4725 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4726 pre-C99 mode). These can be tested with @code{#ifdef}. A fallback to
4727 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4730 @item @code{va_list}
4732 @prindex @code{va_list}
4733 @code{va_list} is not necessarily just a pointer. It can be a
4734 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4735 not portable. Or it can be an array (e.g., @command{gcc} in some
4736 PowerPC configurations), which means as a function parameter it can be
4737 effectively call-by-reference and library routines might modify the
4738 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4741 @item Signed @code{>>}
4742 Normally the C @code{>>} right shift of a signed type replicates the
4743 high bit, giving a so-called ``arithmetic'' shift. But care should be
4744 taken since Standard C doesn't require that behavior. On those
4745 few processors without a native arithmetic shift (for instance Cray
4746 vector systems) zero bits may be shifted in, the same as a shift of an
4749 @item Integer @code{/}
4750 C divides signed integers by truncating their quotient toward zero,
4751 yielding the same result as Fortran. However, before C99 the standard
4752 allowed C implementations to take the floor or ceiling of the quotient
4753 in some cases. Hardly any implementations took advantage of this
4754 freedom, though, and it's probably not worth worrying about this issue
4759 @node Particular Functions
4760 @subsection Particular Function Checks
4761 @cindex Function, checking
4763 These macros check for particular C functions---whether they exist, and
4764 in some cases how they respond when given certain arguments.
4766 @anchor{AC_FUNC_ALLOCA}
4767 @defmac AC_FUNC_ALLOCA
4768 @acindex{FUNC_ALLOCA}
4770 @cvindex HAVE_ALLOCA_H
4773 @prindex @code{alloca}
4775 @c @caindex working_alloca_h
4776 Check how to get @code{alloca}. Tries to get a builtin version by
4777 checking for @file{alloca.h} or the predefined C preprocessor macros
4778 @code{__GNUC__} and @code{_AIX}. If this macro finds @file{alloca.h},
4779 it defines @code{HAVE_ALLOCA_H}.
4781 If those attempts fail, it looks for the function in the standard C
4782 library. If any of those methods succeed, it defines
4783 @code{HAVE_ALLOCA}. Otherwise, it sets the output variable
4784 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4785 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4786 garbage collect). This variable is separate from @code{LIBOBJS} so
4787 multiple programs can share the value of @code{ALLOCA} without needing
4788 to create an actual library, in case only some of them use the code in
4789 @code{LIBOBJS}. The @samp{$@{LIBOBJDIR@}} prefix serves the same
4790 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4792 This macro does not try to get @code{alloca} from the System V R3
4793 @file{libPW} or the System V R4 @file{libucb} because those libraries
4794 contain some incompatible functions that cause trouble. Some versions
4795 do not even contain @code{alloca} or contain a buggy version. If you
4796 still want to use their @code{alloca}, use @code{ar} to extract
4797 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4799 Source files that use @code{alloca} should start with a piece of code
4800 like the following, to declare it properly.
4804 #ifdef HAVE_ALLOCA_H
4805 # include <alloca.h>
4806 #elif defined __GNUC__
4807 # define alloca __builtin_alloca
4809 # define alloca __alloca
4810 #elif defined _MSC_VER
4811 # include <malloc.h>
4812 # define alloca _alloca
4814 # include <stddef.h>
4818 void *alloca (size_t);
4824 @defmac AC_FUNC_CHOWN
4825 @acindex{FUNC_CHOWN}
4828 @prindex @code{chown}
4829 @caindex func_chown_works
4830 If the @code{chown} function is available and works (in particular, it
4831 should accept @option{-1} for @code{uid} and @code{gid}), define
4832 @code{HAVE_CHOWN}. The result of this macro is cached in the
4833 @code{ac_cv_func_chown_works} variable.
4836 @anchor{AC_FUNC_CLOSEDIR_VOID}
4837 @defmac AC_FUNC_CLOSEDIR_VOID
4838 @acindex{FUNC_CLOSEDIR_VOID}
4839 @cvindex CLOSEDIR_VOID
4840 @c @fuindex closedir
4841 @prindex @code{closedir}
4842 @caindex func_closedir_void
4843 If the @code{closedir} function does not return a meaningful value,
4844 define @code{CLOSEDIR_VOID}. Otherwise, callers ought to check its
4845 return value for an error indicator.
4847 Currently this test is implemented by running a test program. When
4848 cross compiling the pessimistic assumption that @code{closedir} does not
4849 return a meaningful value is made.
4851 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4854 This macro is obsolescent, as @code{closedir} returns a meaningful value
4855 on current systems. New programs need not use this macro.
4858 @defmac AC_FUNC_ERROR_AT_LINE
4859 @acindex{FUNC_ERROR_AT_LINE}
4860 @c @fuindex error_at_line
4861 @prindex @code{error_at_line}
4862 @caindex lib_error_at_line
4863 If the @code{error_at_line} function is not found, require an
4864 @code{AC_LIBOBJ} replacement of @samp{error}.
4866 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4870 @defmac AC_FUNC_FNMATCH
4871 @acindex{FUNC_FNMATCH}
4873 @prindex @code{fnmatch}
4874 @caindex func_fnmatch_works
4875 If the @code{fnmatch} function conforms to Posix, define
4876 @code{HAVE_FNMATCH}. Detect common implementation bugs, for example,
4877 the bugs in Solaris 2.4.
4879 Unlike the other specific
4880 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4881 broken/missing @code{fnmatch}. This is for historical reasons.
4882 See @code{AC_REPLACE_FNMATCH} below.
4884 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4887 This macro is obsolescent. New programs should use Gnulib's
4888 @code{fnmatch-posix} module. @xref{Gnulib}.
4891 @defmac AC_FUNC_FNMATCH_GNU
4892 @acindex{FUNC_FNMATCH_GNU}
4894 @prindex @code{fnmatch}
4895 @caindex func_fnmatch_gnu
4896 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4897 whether @code{fnmatch} supports GNU extensions. Detect common
4898 implementation bugs, for example, the bugs in the GNU C
4901 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4904 This macro is obsolescent. New programs should use Gnulib's
4905 @code{fnmatch-gnu} module. @xref{Gnulib}.
4908 @anchor{AC_FUNC_FORK}
4909 @defmac AC_FUNC_FORK
4911 @cvindex HAVE_VFORK_H
4912 @cvindex HAVE_WORKING_FORK
4913 @cvindex HAVE_WORKING_VFORK
4916 @prindex @code{fork}
4918 @prindex @code{vfork}
4920 @c @caindex func_fork
4921 @c @caindex func_fork_works
4922 This macro checks for the @code{fork} and @code{vfork} functions. If a
4923 working @code{fork} is found, define @code{HAVE_WORKING_FORK}. This macro
4924 checks whether @code{fork} is just a stub by trying to run it.
4926 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}. If a working
4927 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}. Otherwise,
4928 define @code{vfork} to be @code{fork} for backward compatibility with
4929 previous versions of @command{autoconf}. This macro checks for several known
4930 errors in implementations of @code{vfork} and considers the system to not
4931 have a working @code{vfork} if it detects any of them. It is not considered
4932 to be an implementation error if a child's invocation of @code{signal}
4933 modifies the parent's signal handler, since child processes rarely change
4934 their signal handlers.
4936 Since this macro defines @code{vfork} only for backward compatibility with
4937 previous versions of @command{autoconf} you're encouraged to define it
4938 yourself in new code:
4941 #ifndef HAVE_WORKING_VFORK
4948 @defmac AC_FUNC_FSEEKO
4949 @acindex{FUNC_FSEEKO}
4950 @cvindex _LARGEFILE_SOURCE
4951 @cvindex HAVE_FSEEKO
4953 @prindex @code{fseeko}
4955 @prindex @code{ftello}
4956 @c @caindex sys_largefile_source
4957 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4958 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4959 visible on some systems (e.g., glibc 2.2). Otherwise linkage problems
4960 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4961 largefile-sensitive systems where @code{off_t} does not default to a
4962 64bit entity. All systems with @code{fseeko} also supply @code{ftello}.
4965 @defmac AC_FUNC_GETGROUPS
4966 @acindex{FUNC_GETGROUPS}
4967 @cvindex HAVE_GETGROUPS
4968 @ovindex GETGROUPS_LIBS
4969 @c @fuindex getgroups
4970 @prindex @code{getgroups}
4971 @caindex func_getgroups_works
4972 If the @code{getgroups} function is available and works (unlike on
4973 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4974 @code{HAVE_GETGROUPS}. Set @code{GETGROUPS_LIBS} to any libraries
4975 needed to get that function. This macro runs @code{AC_TYPE_GETGROUPS}.
4978 @anchor{AC_FUNC_GETLOADAVG}
4979 @defmac AC_FUNC_GETLOADAVG
4980 @acindex{FUNC_GETLOADAVG}
4985 @cvindex HAVE_NLIST_H
4986 @cvindex NLIST_NAME_UNION
4987 @cvindex GETLOADAVG_PRIVILEGED
4988 @cvindex NEED_SETGID
4989 @cvindex C_GETLOADAVG
4991 @ovindex NEED_SETGID
4993 @ovindex GETLOADAVG_LIBS
4994 @c @fuindex getloadavg
4995 @prindex @code{getloadavg}
4996 Check how to get the system load averages. To perform its tests
4997 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4998 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4999 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5001 If the system has the @code{getloadavg} function, define
5002 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5003 necessary to get that function. Also add @code{GETLOADAVG_LIBS} to
5004 @code{LIBS}. Otherwise, require an @code{AC_LIBOBJ} replacement for
5005 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5006 possibly define several other C preprocessor macros and output
5011 Define @code{C_GETLOADAVG}.
5014 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5019 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5022 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5023 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}. The obsolete symbol
5024 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5027 Programs may need to be installed set-group-ID (or set-user-ID) for
5028 @code{getloadavg} to work. In this case, define
5029 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5030 to @samp{true} (and otherwise to @samp{false}), and set
5031 @code{KMEM_GROUP} to the name of the group that should own the installed
5035 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent. New programs should
5036 use Gnulib's @code{getloadavg} module. @xref{Gnulib}.
5039 @anchor{AC_FUNC_GETMNTENT}
5040 @defmac AC_FUNC_GETMNTENT
5041 @acindex{FUNC_GETMNTENT}
5042 @cvindex HAVE_GETMNTENT
5043 @c @fuindex getmntent
5044 @prindex @code{getmntent}
5045 @caindex search_getmntent
5046 Check for @code{getmntent} in the standard C library, and then in the
5047 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5048 IRIX 4, PTX, and UnixWare, respectively. Then, if
5049 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5050 @code{ac_cv_func_getmntent} to @code{yes}. Otherwise set
5051 @code{ac_cv_func_getmntent} to @code{no}.
5053 The result of this macro can be overridden by setting the cache variable
5054 @code{ac_cv_search_getmntent}.
5057 @defmac AC_FUNC_GETPGRP
5058 @acindex{FUNC_GETPGRP}
5059 @cvindex GETPGRP_VOID
5062 @prindex @code{getpgid}
5063 @prindex @code{getpgrp}
5064 @caindex func_getpgrp_void
5065 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5066 @code{getpgrp}; this is the Posix behavior. On older BSD
5067 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5068 behaves like Posix's @code{getpgid}.
5078 This macro does not check whether
5079 @code{getpgrp} exists at all; if you need to work in that situation,
5080 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5082 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5085 This macro is obsolescent, as current systems have a @code{getpgrp}
5086 whose signature conforms to Posix. New programs need not use this macro.
5089 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5090 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5091 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5093 @prindex @code{lstat}
5094 @caindex func_lstat_dereferences_slashed_symlink
5095 If @file{link} is a symbolic link, then @code{lstat} should treat
5096 @file{link/} the same as @file{link/.}. However, many older
5097 @code{lstat} implementations incorrectly ignore trailing slashes.
5099 It is safe to assume that if @code{lstat} incorrectly ignores
5100 trailing slashes, then other symbolic-link-aware functions like
5101 @code{unlink} also incorrectly ignore trailing slashes.
5103 If @code{lstat} behaves properly, define
5104 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5105 @code{AC_LIBOBJ} replacement of @code{lstat}.
5107 The result of this macro is cached in the
5108 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5111 @defmac AC_FUNC_MALLOC
5112 @acindex{FUNC_MALLOC}
5113 @cvindex HAVE_MALLOC
5116 @prindex @code{malloc}
5117 @caindex func_malloc_0_nonnull
5118 If the @code{malloc} function is compatible with the GNU C
5119 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5120 pointer), define @code{HAVE_MALLOC} to 1. Otherwise define
5121 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5122 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5123 native @code{malloc} is not used in the main project.
5125 Typically, the replacement file @file{malloc.c} should look like (note
5126 the @samp{#undef malloc}):
5132 #include <sys/types.h>
5136 /* Allocate an N-byte block of memory from the heap.
5137 If N is zero, allocate a 1-byte block. */
5140 rpl_malloc (size_t n)
5148 The result of this macro is cached in the
5149 @code{ac_cv_func_malloc_0_nonnull} variable.
5152 @defmac AC_FUNC_MBRTOWC
5153 @acindex{FUNC_MBRTOWC}
5154 @cvindex HAVE_MBRTOWC
5156 @prindex @code{mbrtowc}
5157 @caindex func_mbrtowc
5158 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5159 type @code{mbstate_t} are properly declared.
5161 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5165 @defmac AC_FUNC_MEMCMP
5166 @acindex{FUNC_MEMCMP}
5169 @prindex @code{memcmp}
5170 @caindex func_memcmp_working
5171 If the @code{memcmp} function is not available, or does not work on
5172 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5173 bytes or more and with at least one buffer not starting on a 4-byte
5174 boundary (such as the one on NeXT x86 OpenStep), require an
5175 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5177 The result of this macro is cached in the
5178 @code{ac_cv_func_memcmp_working} variable.
5180 This macro is obsolescent, as current systems have a working
5181 @code{memcmp}. New programs need not use this macro.
5184 @defmac AC_FUNC_MKTIME
5185 @acindex{FUNC_MKTIME}
5188 @prindex @code{mktime}
5189 @caindex func_working_mktime
5190 If the @code{mktime} function is not available, or does not work
5191 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5192 For the purposes of this test, @code{mktime} should conform to the
5193 Posix standard and should be the inverse of
5196 The result of this macro is cached in the
5197 @code{ac_cv_func_working_mktime} variable.
5200 @anchor{AC_FUNC_MMAP}
5201 @defmac AC_FUNC_MMAP
5205 @prindex @code{mmap}
5206 @caindex func_mmap_fixed_mapped
5207 If the @code{mmap} function exists and works correctly, define
5208 @code{HAVE_MMAP}. This checks only private fixed mapping of already-mapped
5211 The result of this macro is cached in the
5212 @code{ac_cv_func_mmap_fixed_mapped} variable.
5215 @defmac AC_FUNC_OBSTACK
5216 @acindex{FUNC_OBSTACK}
5217 @cvindex HAVE_OBSTACK
5219 @caindex func_obstack
5220 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5221 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5223 The result of this macro is cached in the @code{ac_cv_func_obstack}
5227 @defmac AC_FUNC_REALLOC
5228 @acindex{FUNC_REALLOC}
5229 @cvindex HAVE_REALLOC
5232 @prindex @code{realloc}
5233 @caindex func_realloc_0_nonnull
5234 If the @code{realloc} function is compatible with the GNU C
5235 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5236 valid pointer), define @code{HAVE_REALLOC} to 1. Otherwise define
5237 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5238 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5239 the native @code{realloc} is not used in the main project. See
5240 @code{AC_FUNC_MALLOC} for details.
5242 The result of this macro is cached in the
5243 @code{ac_cv_func_realloc_0_nonnull} variable.
5246 @defmac AC_FUNC_SELECT_ARGTYPES
5247 @acindex{FUNC_SELECT_ARGTYPES}
5248 @cvindex SELECT_TYPE_ARG1
5249 @cvindex SELECT_TYPE_ARG234
5250 @cvindex SELECT_TYPE_ARG5
5252 @prindex @code{select}
5253 @c @caindex func_select_args
5254 Determines the correct type to be passed for each of the
5255 @code{select} function's arguments, and defines those types
5256 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5257 @code{SELECT_TYPE_ARG5} respectively. @code{SELECT_TYPE_ARG1} defaults
5258 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5259 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5261 This macro is obsolescent, as current systems have a @code{select} whose
5262 signature conforms to Posix. New programs need not use this macro.
5265 @defmac AC_FUNC_SETPGRP
5266 @acindex{FUNC_SETPGRP}
5267 @cvindex SETPGRP_VOID
5269 @prindex @code{setpgrp}
5270 @caindex func_setpgrp_void
5271 If @code{setpgrp} takes no argument (the Posix version), define
5272 @code{SETPGRP_VOID}. Otherwise, it is the BSD version, which takes
5273 two process IDs as arguments. This macro does not check whether
5274 @code{setpgrp} exists at all; if you need to work in that situation,
5275 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5277 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5280 This macro is obsolescent, as current systems have a @code{setpgrp}
5281 whose signature conforms to Posix. New programs need not use this macro.
5284 @defmac AC_FUNC_STAT
5285 @defmacx AC_FUNC_LSTAT
5287 @acindex{FUNC_LSTAT}
5288 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5289 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5291 @prindex @code{stat}
5293 @prindex @code{lstat}
5294 @caindex func_stat_empty_string_bug
5295 @caindex func_lstat_empty_string_bug
5296 Determine whether @code{stat} or @code{lstat} have the bug that it
5297 succeeds when given the zero-length file name as argument. The @code{stat}
5298 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5301 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5302 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5305 The results of these macros are cached in the
5306 @code{ac_cv_func_stat_empty_string_bug} and the
5307 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5309 These macros are obsolescent, as no current systems have the bug.
5310 New programs need not use these macros.
5313 @anchor{AC_FUNC_STRCOLL}
5314 @defmac AC_FUNC_STRCOLL
5315 @acindex{FUNC_STRCOLL}
5316 @cvindex HAVE_STRCOLL
5318 @prindex @code{strcoll}
5319 @caindex func_strcoll_works
5320 If the @code{strcoll} function exists and works correctly, define
5321 @code{HAVE_STRCOLL}. This does a bit more than
5322 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5323 definitions of @code{strcoll} that should not be used.
5325 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5329 @defmac AC_FUNC_STRERROR_R
5330 @acindex{FUNC_STRERROR_R}
5331 @cvindex HAVE_STRERROR_R
5332 @cvindex HAVE_DECL_STRERROR_R
5333 @cvindex STRERROR_R_CHAR_P
5334 @c @fuindex strerror_r
5335 @caindex func_strerror_r_char_p
5336 @prindex @code{strerror_r}
5337 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5338 it is declared, define @code{HAVE_DECL_STRERROR_R}. If it returns a
5339 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5340 returns an @code{int} error number. The Thread-Safe Functions option of
5341 Posix requires @code{strerror_r} to return @code{int}, but
5342 many systems (including, for example, version 2.2.4 of the GNU C
5343 Library) return a @code{char *} value that is not necessarily equal to
5344 the buffer argument.
5346 The result of this macro is cached in the
5347 @code{ac_cv_func_strerror_r_char_p} variable.
5350 @anchor{AC_FUNC_STRFTIME}
5351 @defmac AC_FUNC_STRFTIME
5352 @acindex{FUNC_STRFTIME}
5353 @cvindex HAVE_STRFTIME
5354 @c @fuindex strftime
5355 @prindex @code{strftime}
5356 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5357 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5359 This macro is obsolescent, as no current systems require the @file{intl}
5360 library for @code{strftime}. New programs need not use this macro.
5363 @defmac AC_FUNC_STRTOD
5364 @acindex{FUNC_STRTOD}
5367 @prindex @code{strtod}
5368 @caindex func_strtod
5370 If the @code{strtod} function does not exist or doesn't work correctly,
5371 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}. In this case,
5372 because @file{strtod.c} is likely to need @samp{pow}, set the output
5373 variable @code{POW_LIB} to the extra library needed.
5375 This macro caches its result in the @code{ac_cv_func_strtod} variable
5376 and depends upon the result in the @code{ac_cv_func_pow} variable.
5379 @defmac AC_FUNC_STRTOLD
5380 @acindex{FUNC_STRTOLD}
5381 @cvindex HAVE_STRTOLD
5382 @prindex @code{strtold}
5383 @caindex func_strtold
5384 If the @code{strtold} function exists and conforms to C99, define
5385 @code{HAVE_STRTOLD}.
5387 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5390 @defmac AC_FUNC_STRNLEN
5391 @acindex{FUNC_STRNLEN}
5392 @cvindex HAVE_STRNLEN
5394 @prindex @code{strnlen}
5395 @caindex func_strnlen_working
5396 If the @code{strnlen} function is not available, or is buggy (like the one
5397 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5399 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5403 @anchor{AC_FUNC_UTIME_NULL}
5404 @defmac AC_FUNC_UTIME_NULL
5405 @acindex{FUNC_UTIME_NULL}
5406 @cvindex HAVE_UTIME_NULL
5408 @prindex @code{utime}
5409 @caindex func_utime_null
5410 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5411 the present, define @code{HAVE_UTIME_NULL}.
5413 This macro caches its result in the @code{ac_cv_func_utime_null}
5416 This macro is obsolescent, as all current systems have a @code{utime}
5417 that behaves this way. New programs need not use this macro.
5420 @anchor{AC_FUNC_VPRINTF}
5421 @defmac AC_FUNC_VPRINTF
5422 @acindex{FUNC_VPRINTF}
5423 @cvindex HAVE_VPRINTF
5424 @cvindex HAVE_DOPRNT
5426 @prindex @code{vprintf}
5427 @c @fuindex vsprintf
5428 @prindex @code{vsprintf}
5429 If @code{vprintf} is found, define @code{HAVE_VPRINTF}. Otherwise, if
5430 @code{_doprnt} is found, define @code{HAVE_DOPRNT}. (If @code{vprintf}
5431 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5432 are also available.)
5434 This macro is obsolescent, as all current systems have @code{vprintf}.
5435 New programs need not use this macro.
5438 @defmac AC_REPLACE_FNMATCH
5439 @acindex{REPLACE_FNMATCH}
5441 @prindex @code{fnmatch}
5442 @hdrindex{fnmatch.h}
5443 @caindex func_fnmatch_works
5444 If the @code{fnmatch} function does not conform to Posix (see
5445 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5447 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5448 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5449 copy of the source code of GNU @code{fnmatch}. If necessary,
5450 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5451 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5452 included in place of the system @code{<fnmatch.h>}.
5454 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5457 This macro is obsolescent, as it assumes the use of particular source
5458 files. New programs should use Gnulib's @code{fnmatch-posix} module,
5459 which provides this macro along with the source files. @xref{Gnulib}.
5464 @node Generic Functions
5465 @subsection Generic Function Checks
5467 These macros are used to find functions not covered by the ``particular''
5468 test macros. If the functions might be in libraries other than the
5469 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5470 If you need to check the behavior of a function as well as find out
5471 whether it is present, you have to write your own test for
5472 it (@pxref{Writing Tests}).
5474 @anchor{AC_CHECK_FUNC}
5475 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5476 @ovar{action-if-not-found})
5477 @acindex{CHECK_FUNC}
5478 @caindex func_@var{function}
5479 If C function @var{function} is available, run shell commands
5480 @var{action-if-found}, otherwise @var{action-if-not-found}. If you just
5481 want to define a symbol if the function is available, consider using
5482 @code{AC_CHECK_FUNCS} instead. This macro checks for functions with C
5483 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5484 standardized than C++. (@pxref{Language Choice}, for more information
5485 about selecting the language for checks.)
5487 This macro caches its result in the @code{ac_cv_func_@var{function}}
5491 @anchor{AC_CHECK_FUNCS}
5492 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5493 @ovar{action-if-not-found})
5494 @acindex{CHECK_FUNCS}
5495 @cvindex HAVE_@var{function}
5496 For each @var{function} enumerated in the blank-or-newline-separated argument
5497 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5498 If @var{action-if-found} is given, it is additional shell code to
5499 execute when one of the functions is found. You can give it a value of
5500 @samp{break} to break out of the loop on the first match. If
5501 @var{action-if-not-found} is given, it is executed when one of the
5502 functions is not found.
5504 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5507 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5508 @acindex{CHECK_FUNCS_ONCE}
5509 @cvindex HAVE_@var{function}
5510 For each @var{function} enumerated in the blank-or-newline-separated argument
5511 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5512 This is a once-only variant of @code{AC_CHECK_FUNCS}. It generates the
5513 checking code at most once, so that @command{configure} is smaller and
5514 faster; but the checks cannot be conditionalized and are always done once,
5515 early during the @command{configure} run.
5520 Autoconf follows a philosophy that was formed over the years by those
5521 who have struggled for portability: isolate the portability issues in
5522 specific files, and then program as if you were in a Posix
5523 environment. Some functions may be missing or unfixable, and your
5524 package must be ready to replace them.
5526 Suitable replacements for many such problem functions are available from
5527 Gnulib (@pxref{Gnulib}).
5529 @defmac AC_LIBOBJ (@var{function})
5532 Specify that @samp{@var{function}.c} must be included in the executables
5533 to replace a missing or broken implementation of @var{function}.
5535 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5536 variable @code{LIBOBJS} if it is not already in, and calls
5537 @code{AC_LIBSOURCE} for @samp{@var{function}.c}. You should not
5538 directly change @code{LIBOBJS}, since this is not traceable.
5541 @defmac AC_LIBSOURCE (@var{file})
5543 Specify that @var{file} might be needed to compile the project. If you
5544 need to know what files might be needed by a @file{configure.ac}, you
5545 should trace @code{AC_LIBSOURCE}. @var{file} must be a literal.
5547 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5548 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}. In
5549 that case, since shell variables cannot be traced statically, you must
5550 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5551 might cause @code{AC_LIBOBJ} to need. For example, if you want to pass
5552 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5553 @code{"foo"} or @code{"bar"}, you should do:
5556 AC_LIBSOURCE([foo.c])
5557 AC_LIBSOURCE([bar.c])
5558 AC_LIBOBJ([$foo_or_bar])
5562 There is usually a way to avoid this, however, and you are encouraged to
5563 simply call @code{AC_LIBOBJ} with literal arguments.
5565 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5566 slightly different semantics: the old macro took the function name,
5567 e.g., @code{foo}, as its argument rather than the file name.
5570 @defmac AC_LIBSOURCES (@var{files})
5571 @acindex{LIBSOURCES}
5572 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5573 comma-separated M4 list. Thus, the above example might be rewritten:
5576 AC_LIBSOURCES([foo.c, bar.c])
5577 AC_LIBOBJ([$foo_or_bar])
5581 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5582 @acindex{CONFIG_LIBOBJ_DIR}
5583 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5584 @var{directory}, a name relative to the top level of the
5585 source tree. The replacement directory defaults to @file{.}, the top
5586 level directory, and the most typical value is @file{lib}, corresponding
5587 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5589 @command{configure} might need to know the replacement directory for the
5590 following reasons: (i) some checks use the replacement files, (ii) some
5591 macros bypass broken system headers by installing links to the
5592 replacement headers (iii) when used in conjunction with Automake,
5593 within each makefile, @var{directory} is used as a relative path
5594 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5595 @code{LTLIBOBJS}, etc.
5600 It is common to merely check for the existence of a function, and ask
5601 for its @code{AC_LIBOBJ} replacement if missing. The following macro is
5602 a convenient shorthand.
5604 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5605 @acindex{REPLACE_FUNCS}
5606 @cvindex HAVE_@var{function}
5608 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5609 @var{action-if-not-found}. You can declare your replacement function by
5610 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}. If the
5611 system has the function, it probably declares it in a header file you
5612 should be including, so you shouldn't redeclare it lest your declaration
5617 @section Header Files
5618 @cindex Header, checking
5620 The following macros check for the presence of certain C header files.
5621 If there is no macro specifically defined to check for a header file you need,
5622 and you don't need to check for any special properties of
5623 it, then you can use one of the general header-file check macros.
5626 * Header Portability:: Collected knowledge on common headers
5627 * Particular Headers:: Special handling to find certain headers
5628 * Generic Headers:: How to find other headers
5631 @node Header Portability
5632 @subsection Portability of Headers
5633 @cindex Portability of headers
5634 @cindex Header portability
5636 This section tries to collect knowledge about common headers, and the
5637 problems they cause. By definition, this list always requires
5638 additions. Please help us keeping it as complete as possible.
5642 @item @file{limits.h}
5643 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5644 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5645 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5648 @item @file{inttypes.h} vs.@: @file{stdint.h}
5649 @hdrindex{inttypes.h}
5651 The C99 standard says that @file{inttypes.h} includes
5652 @file{stdint.h}, so there's no need to include @file{stdint.h}
5653 separately in a standard environment. Some implementations have
5654 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5655 know of any implementation that has @file{stdint.h} but not
5658 @item @file{linux/irda.h}
5659 @hdrindex{linux/irda.h}
5660 It requires @file{linux/types.h} and @file{sys/socket.h}.
5662 @item @file{linux/random.h}
5663 @hdrindex{linux/random.h}
5664 It requires @file{linux/types.h}.
5666 @item @file{net/if.h}
5668 On Darwin, this file requires that @file{sys/socket.h} be included
5669 beforehand. One should run:
5672 AC_CHECK_HEADERS([sys/socket.h])
5673 AC_CHECK_HEADERS([net/if.h], [], [],
5676 # include <stdlib.h>
5677 # include <stddef.h>
5679 # ifdef HAVE_STDLIB_H
5680 # include <stdlib.h>
5683 #ifdef HAVE_SYS_SOCKET_H
5684 # include <sys/socket.h>
5689 @item @file{netinet/if_ether.h}
5690 @hdrindex{netinet/if_ether.h}
5691 On Darwin, this file requires that @file{stdio.h} and
5692 @file{sys/socket.h} be included beforehand. One should run:
5695 AC_CHECK_HEADERS([sys/socket.h])
5696 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5699 # include <stdlib.h>
5700 # include <stddef.h>
5702 # ifdef HAVE_STDLIB_H
5703 # include <stdlib.h>
5706 #ifdef HAVE_SYS_SOCKET_H
5707 # include <sys/socket.h>
5712 @item @file{stdint.h}
5713 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5715 @item @file{stdlib.h}
5717 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5719 @item @file{sys/mount.h}
5720 @hdrindex{sys/mount.h}
5721 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5722 @file{sys/params.h} is a prerequisite.
5724 @item @file{sys/ptem.h}
5725 @hdrindex{sys/ptem.h}
5726 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5728 @item @file{sys/socket.h}
5729 @hdrindex{sys/socket.h}
5730 On Darwin, @file{stdlib.h} is a prerequisite.
5732 @item @file{sys/ucred.h}
5733 @hdrindex{sys/ucred.h}
5734 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5736 @item @file{X11/extensions/scrnsaver.h}
5737 @hdrindex{X11/extensions/scrnsaver.h}
5738 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5739 so required that you might not even consider looking for it.
5742 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5743 [[#include <X11/Xlib.h>
5749 @node Particular Headers
5750 @subsection Particular Header Checks
5752 These macros check for particular system header files---whether they
5753 exist, and in some cases whether they declare certain symbols.
5755 @defmac AC_HEADER_ASSERT
5756 @acindex{HEADER_ASSERT}
5759 Check whether to enable assertions in the style of @file{assert.h}.
5760 Assertions are enabled by default, but the user can override this by
5761 invoking @command{configure} with the @option{--disable-assert} option.
5764 @anchor{AC_HEADER_DIRENT}
5765 @defmac AC_HEADER_DIRENT
5766 @acindex{HEADER_DIRENT}
5767 @cvindex HAVE_DIRENT_H
5768 @cvindex HAVE_NDIR_H
5769 @cvindex HAVE_SYS_DIR_H
5770 @cvindex HAVE_SYS_NDIR_H
5772 @hdrindex{sys/ndir.h}
5773 @hdrindex{sys/dir.h}
5775 Check for the following header files. For the first one that is
5776 found and defines @samp{DIR}, define the listed C preprocessor macro:
5778 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5779 @item @file{dirent.h} @tab @code{HAVE_DIRENT_H}
5780 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5781 @item @file{sys/dir.h} @tab @code{HAVE_SYS_DIR_H}
5782 @item @file{ndir.h} @tab @code{HAVE_NDIR_H}
5785 The directory-library declarations in your source code should look
5786 something like the following:
5790 #include <sys/types.h>
5791 #ifdef HAVE_DIRENT_H
5792 # include <dirent.h>
5793 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5795 # define dirent direct
5796 # define NAMLEN(dirent) ((dirent)->d_namlen)
5797 # ifdef HAVE_SYS_NDIR_H
5798 # include <sys/ndir.h>
5800 # ifdef HAVE_SYS_DIR_H
5801 # include <sys/dir.h>
5810 Using the above declarations, the program would declare variables to be
5811 of type @code{struct dirent}, not @code{struct direct}, and would access
5812 the length of a directory entry name by passing a pointer to a
5813 @code{struct dirent} to the @code{NAMLEN} macro.
5815 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5817 This macro is obsolescent, as all current systems with directory
5818 libraries have @code{<dirent.h>}. New programs need not use this macro.
5820 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5821 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5824 @anchor{AC_HEADER_MAJOR}
5825 @defmac AC_HEADER_MAJOR
5826 @acindex{HEADER_MAJOR}
5827 @cvindex MAJOR_IN_MKDEV
5828 @cvindex MAJOR_IN_SYSMACROS
5829 @hdrindex{sys/mkdev.h}
5830 @hdrindex{sys/sysmacros.h}
5831 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5832 @code{makedev}, but @file{sys/mkdev.h} does, define
5833 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5834 @code{MAJOR_IN_SYSMACROS}.
5837 @defmac AC_HEADER_RESOLV
5838 @acindex{HEADER_RESOLV}
5839 @cvindex HAVE_RESOLV_H
5841 Checks for header @file{resolv.h}, checking for prerequisites first.
5842 To properly use @file{resolv.h}, your code should contain something like
5846 #ifdef HAVE_SYS_TYPES_H
5847 # include <sys/types.h>
5849 #ifdef HAVE_NETINET_IN_H
5850 # include <netinet/in.h> /* inet_ functions / structs */
5852 #ifdef HAVE_ARPA_NAMESER_H
5853 # include <arpa/nameser.h> /* DNS HEADER struct */
5862 @anchor{AC_HEADER_STAT}
5863 @defmac AC_HEADER_STAT
5864 @acindex{HEADER_STAT}
5865 @cvindex STAT_MACROS_BROKEN
5866 @hdrindex{sys/stat.h}
5867 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5868 @file{sys/stat.h} do not work properly (returning false positives),
5869 define @code{STAT_MACROS_BROKEN}. This is the case on Tektronix UTekV,
5870 Amdahl UTS and Motorola System V/88.
5872 This macro is obsolescent, as no current systems have the bug.
5873 New programs need not use this macro.
5876 @defmac AC_HEADER_STDBOOL
5877 @acindex{HEADER_STDBOOL}
5878 @cvindex HAVE_STDBOOL_H
5880 @hdrindex{stdbool.h}
5882 @caindex header_stdbool_h
5883 If @file{stdbool.h} exists and conforms to C99, define
5884 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5885 @code{HAVE__BOOL} to 1. To fulfill the C99 requirements, your
5886 @file{system.h} could contain the following code:
5889 #ifdef HAVE_STDBOOL_H
5890 # include <stdbool.h>
5896 # define _Bool signed char
5902 # define __bool_true_false_are_defined 1
5906 Alternatively you can use the @samp{stdbool} package of Gnulib
5907 (@pxref{Gnulib}); it packages the above code into a replacement header
5908 and contains a few other bells and whistles.
5910 This macro caches its result in the @code{ac_cv_header_stdbool_h}
5914 @anchor{AC_HEADER_STDC}
5915 @defmac AC_HEADER_STDC
5916 @acindex{HEADER_STDC}
5917 @cvindex STDC_HEADERS
5923 @caindex header_stdc
5924 Define @code{STDC_HEADERS} if the system has C header files
5925 conforming to ANSI C89 (ISO C90).
5926 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5927 @file{string.h}, and @file{float.h}; if the system has those, it
5928 probably has the rest of the C89 header files. This macro also
5929 checks whether @file{string.h} declares @code{memchr} (and thus
5930 presumably the other @code{mem} functions), whether @file{stdlib.h}
5931 declare @code{free} (and thus presumably @code{malloc} and other related
5932 functions), and whether the @file{ctype.h} macros work on characters
5933 with the high bit set, as the C standard requires.
5935 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5936 determine whether the system has conforming header files (and probably C
5939 This macro caches its result in the @code{ac_cv_header_stdc} variable.
5941 This macro is obsolescent, as current systems have conforming header
5942 files. New programs need not use this macro.
5945 @hdrindex{strings.h}
5946 Nowadays @file{string.h} is part of the C standard and declares functions like
5947 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5948 BSD functions like @code{bcopy}; but
5949 historically, string functions were a major sticking point in this area.
5950 If you still want to worry about portability to ancient systems without
5951 standard headers, there is so much variation
5952 that it is probably easier to declare the functions you use than to
5953 figure out exactly what the system header files declare. Some ancient systems
5954 contained a mix of functions from the C standard and from BSD;
5955 some were mostly standard but lacked @samp{memmove}; some defined the
5956 BSD functions as macros in @file{string.h} or
5957 @file{strings.h}; some had only the BSD functions but
5958 @file{string.h}; some declared the memory functions in @file{memory.h},
5959 some in @file{string.h}; etc. It is probably sufficient to check for
5960 one string function and one memory function; if the library had the
5961 standard versions of those then it probably had most of the others.
5962 If you put the following in @file{configure.ac}:
5965 # This example is obsolescent.
5966 # Nowadays you can omit these macro calls.
5968 AC_CHECK_FUNCS([strchr memcpy])
5972 then, in your code, you can use declarations like this:
5976 /* This example is obsolescent.
5977 Nowadays you can just #include <string.h>. */
5979 # include <string.h>
5981 # ifndef HAVE_STRCHR
5982 # define strchr index
5983 # define strrchr rindex
5985 char *strchr (), *strrchr ();
5986 # ifndef HAVE_MEMCPY
5987 # define memcpy(d, s, n) bcopy ((s), (d), (n))
5988 # define memmove(d, s, n) bcopy ((s), (d), (n))
5995 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5996 or @code{strspn}, which have no BSD equivalent, then macros don't
5997 suffice to port to ancient hosts; you must provide an implementation of
5998 each function. An easy
5999 way to incorporate your implementations only when needed (since the ones
6000 in system C libraries may be hand optimized) is to, taking @code{memchr}
6001 for example, put it in @file{memchr.c} and use
6002 @samp{AC_REPLACE_FUNCS([memchr])}.
6005 @defmac AC_HEADER_SYS_WAIT
6006 @acindex{HEADER_SYS_WAIT}
6007 @cvindex HAVE_SYS_WAIT_H
6008 @hdrindex{sys/wait.h}
6009 @caindex header_sys_wait_h
6010 If @file{sys/wait.h} exists and is compatible with Posix, define
6011 @code{HAVE_SYS_WAIT_H}. Incompatibility can occur if @file{sys/wait.h}
6012 does not exist, or if it uses the old BSD @code{union wait} instead
6013 of @code{int} to store a status value. If @file{sys/wait.h} is not
6014 Posix compatible, then instead of including it, define the
6015 Posix macros with their usual interpretations. Here is an
6020 #include <sys/types.h>
6021 #ifdef HAVE_SYS_WAIT_H
6022 # include <sys/wait.h>
6025 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6028 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6034 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6037 This macro is obsolescent, as current systems are compatible with Posix.
6038 New programs need not use this macro.
6041 @cvindex _POSIX_VERSION
6043 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6044 Posix systems. If there is no @file{unistd.h}, it is definitely
6045 not a Posix system. However, some non-Posix systems do
6046 have @file{unistd.h}.
6048 The way to check whether the system supports Posix is:
6052 #ifdef HAVE_UNISTD_H
6053 # include <sys/types.h>
6054 # include <unistd.h>
6057 #ifdef _POSIX_VERSION
6058 /* Code for Posix systems. */
6063 @anchor{AC_HEADER_TIME}
6064 @defmac AC_HEADER_TIME
6065 @acindex{HEADER_TIME}
6066 @cvindex TIME_WITH_SYS_TIME
6068 @hdrindex{sys/time.h}
6069 @caindex header_time
6070 If a program may include both @file{time.h} and @file{sys/time.h},
6071 define @code{TIME_WITH_SYS_TIME}. On some ancient systems,
6072 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6073 protected against multiple inclusion, so programs could not explicitly
6074 include both files. This macro is useful in programs that use, for
6075 example, @code{struct timeval} as well as
6076 @code{struct tm}. It is best used in conjunction with
6077 @code{HAVE_SYS_TIME_H}, which can be checked for using
6078 @code{AC_CHECK_HEADERS([sys/time.h])}.
6082 #ifdef TIME_WITH_SYS_TIME
6083 # include <sys/time.h>
6086 # ifdef HAVE_SYS_TIME_H
6087 # include <sys/time.h>
6096 This macro caches its result in the @code{ac_cv_header_time} variable.
6098 This macro is obsolescent, as current systems can include both files
6099 when they exist. New programs need not use this macro.
6103 @defmac AC_HEADER_TIOCGWINSZ
6104 @acindex{HEADER_TIOCGWINSZ}
6105 @cvindex GWINSZ_IN_SYS_IOCTL
6106 @hdrindex{sys/ioctl.h}
6107 @hdrindex{termios.h}
6108 @c FIXME: I need clarifications from Jim.
6109 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6110 define @code{GWINSZ_IN_SYS_IOCTL}. Otherwise @code{TIOCGWINSZ} can be
6111 found in @file{<termios.h>}.
6117 #ifdef HAVE_TERMIOS_H
6118 # include <termios.h>
6121 #ifdef GWINSZ_IN_SYS_IOCTL
6122 # include <sys/ioctl.h>
6128 @node Generic Headers
6129 @subsection Generic Header Checks
6131 These macros are used to find system header files not covered by the
6132 ``particular'' test macros. If you need to check the contents of a header
6133 as well as find out whether it is present, you have to write your own
6134 test for it (@pxref{Writing Tests}).
6136 @anchor{AC_CHECK_HEADER}
6137 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6138 @ovar{action-if-not-found}, @ovar{includes})
6139 @acindex{CHECK_HEADER}
6140 @caindex header_@var{header-file}
6141 If the system header file @var{header-file} is compilable, execute shell
6142 commands @var{action-if-found}, otherwise execute
6143 @var{action-if-not-found}. If you just want to define a symbol if the
6144 header file is available, consider using @code{AC_CHECK_HEADERS}
6147 @var{includes} is decoded to determine the appropriate include
6148 directives. If omitted or empty, @file{configure} will check for both header
6149 existence (with the preprocessor) and usability (with the compiler),
6150 using @code{AC_INCLUDES_DEFAULT} for the compile test. If
6151 there is a discrepancy between the results, a warning is issued to the
6152 user, and the compiler results are favored (@pxref{Present But
6153 Cannot Be Compiled}). In general, favoring the compiler results means
6154 that a header will be treated as not found even though the file exists,
6155 because you did not provide enough prerequisites.
6157 Providing a non-empty @var{includes} argument allows the code to provide
6158 any prerequisites prior to including the header under test; it is common
6159 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6160 Includes}). With an explicit fourth argument, no preprocessor test is
6161 needed. As a special case, an @var{includes} of exactly @samp{-}
6162 triggers the older preprocessor check, which merely determines existence
6163 of the file in the preprocessor search path; this should only be used as
6164 a last resort (it is safer to determine the actual prerequisites and
6165 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6166 it obvious that only a preprocessor check is desired).
6168 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6169 variable, with characters not suitable for a variable name mapped to
6173 @anchor{AC_CHECK_HEADERS}
6174 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6175 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6177 @acindex{CHECK_HEADERS}
6178 @cvindex HAVE_@var{header}
6179 @caindex header_@var{header-file}
6180 For each given system header file @var{header-file} in the
6181 blank-separated argument list that exists, define
6182 @code{HAVE_@var{header-file}} (in all capitals). If @var{action-if-found}
6183 is given, it is additional shell code to execute when one of the header
6184 files is found. You can give it a value of @samp{break} to break out of
6185 the loop on the first match. If @var{action-if-not-found} is given, it
6186 is executed when one of the header files is not found.
6188 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6189 choose the set of preprocessor directives supplied before the header
6192 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6193 variable, with characters not suitable for a variable name mapped to
6197 Previous versions of Autoconf merely checked whether the header was
6198 accepted by the preprocessor. This was changed because the old test was
6199 inappropriate for typical uses. Headers are typically used to compile,
6200 not merely to preprocess, and the old behavior sometimes accepted
6201 headers that clashed at compile-time (@pxref{Present But Cannot Be
6202 Compiled}). If you need to check whether a header is preprocessable,
6203 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6205 Actually requiring a header to compile improves the robustness of the
6206 test, but it also requires
6207 that you make sure that headers that must be included before the
6208 @var{header-file} be part of the @var{includes}, (@pxref{Default
6209 Includes}). If looking for @file{bar.h}, which requires that
6210 @file{foo.h} be included before if it exists, we suggest the following
6214 AC_CHECK_HEADERS([foo.h])
6215 AC_CHECK_HEADERS([bar.h], [], [],
6222 The following variant generates smaller, faster @command{configure}
6223 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6225 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6226 @acindex{CHECK_HEADERS_ONCE}
6227 @cvindex HAVE_@var{header}
6228 For each given system header file @var{header-file} in the
6229 blank-separated argument list that exists, define
6230 @code{HAVE_@var{header-file}} (in all capitals).
6231 This is a once-only variant of @code{AC_CHECK_HEADERS}. It generates the
6232 checking code at most once, so that @command{configure} is smaller and
6233 faster; but the checks cannot be conditionalized and are always done once,
6234 early during the @command{configure} run. Thus, this macro is only safe
6235 for checking headers that do not have prerequisites beyond what
6236 @code{AC_INCLUDES_DEFAULT} provides.
6240 @section Declarations
6241 @cindex Declaration, checking
6243 The following macros check for the declaration of variables and
6244 functions. If there is no macro specifically defined to check for a
6245 symbol you need, then you can use the general macros (@pxref{Generic
6246 Declarations}) or, for more complex tests, you may use
6247 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6250 * Particular Declarations:: Macros to check for certain declarations
6251 * Generic Declarations:: How to find other declarations
6254 @node Particular Declarations
6255 @subsection Particular Declaration Checks
6257 There are no specific macros for declarations.
6259 @node Generic Declarations
6260 @subsection Generic Declaration Checks
6262 These macros are used to find declarations not covered by the ``particular''
6265 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6266 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6267 @acindex{CHECK_DECL}
6268 @caindex have_decl_@var{symbol}
6269 If @var{symbol} (a function, variable, or constant) is not declared in
6270 @var{includes} and a declaration is needed, run the shell commands
6271 @var{action-if-not-found}, otherwise @var{action-if-found}.
6272 @var{includes} is a series of include directives, defaulting to
6273 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6274 prior to the declaration under test.
6276 This macro actually tests whether @var{symbol} is defined as a macro or
6277 can be used as an r-value, not whether it is really declared, because it
6278 is much safer to avoid
6279 introducing extra declarations when they are not needed.
6281 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6282 variable, with characters not suitable for a variable name mapped to
6286 @anchor{AC_CHECK_DECLS}
6287 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6288 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6289 @acindex{CHECK_DECLS}
6290 @cvindex HAVE_DECL_@var{symbol}
6291 @caindex have_decl_@var{symbol}
6292 For each of the @var{symbols} (@emph{comma}-separated list), define
6293 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6294 @var{symbol} is declared, otherwise to @samp{0}. If
6295 @var{action-if-not-found} is given, it is additional shell code to
6296 execute when one of the function declarations is needed, otherwise
6297 @var{action-if-found} is executed.
6299 @var{includes} is a series of include directives, defaulting to
6300 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6301 prior to the declarations under test.
6303 This macro uses an M4 list as first argument:
6305 AC_CHECK_DECLS([strdup])
6306 AC_CHECK_DECLS([strlen])
6307 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6308 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6311 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6312 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6313 of leaving @code{HAVE_DECL_@var{symbol}} undeclared. When you are
6314 @emph{sure} that the check was performed, use
6315 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6318 #if !HAVE_DECL_SYMBOL
6319 extern char *symbol;
6324 If the test may have not been performed, however, because it is safer
6325 @emph{not} to declare a symbol than to use a declaration that conflicts
6326 with the system's one, you should use:
6329 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6330 void *malloc (size_t *s);
6335 You fall into the second category only in extreme situations: either
6336 your files may be used without being configured, or they are used during
6337 the configuration. In most cases the traditional approach is enough.
6339 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6340 variables, with characters not suitable for a variable name mapped to
6344 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6345 @acindex{CHECK_DECLS_ONCE}
6346 @cvindex HAVE_DECL_@var{symbol}
6347 For each of the @var{symbols} (@emph{comma}-separated list), define
6348 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6349 @var{symbol} is declared in the default include files, otherwise to
6350 @samp{0}. This is a once-only variant of @code{AC_CHECK_DECLS}. It
6351 generates the checking code at most once, so that @command{configure} is
6352 smaller and faster; but the checks cannot be conditionalized and are
6353 always done once, early during the @command{configure} run.
6359 @cindex Structure, checking
6361 The following macros check for the presence of certain members in C
6362 structures. If there is no macro specifically defined to check for a
6363 member you need, then you can use the general structure-member macros
6364 (@pxref{Generic Structures}) or, for more complex tests, you may use
6365 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6368 * Particular Structures:: Macros to check for certain structure members
6369 * Generic Structures:: How to find other structure members
6372 @node Particular Structures
6373 @subsection Particular Structure Checks
6375 The following macros check for certain structures or structure members.
6377 @defmac AC_STRUCT_DIRENT_D_INO
6378 @acindex{STRUCT_DIRENT_D_INO}
6379 @cvindex HAVE_STRUCT_DIRENT_D_INO
6380 @c @caindex header_dirent_dirent_h
6381 @c @caindex member_struct_dirent_d_ino
6382 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6383 Headers}). Then, if @code{struct dirent} contains a @code{d_ino}
6384 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6386 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6387 @code{d_ino}, not whether its contents are always reliable.
6388 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6389 though current systems hide this detail from the user and never return
6390 zero @code{d_ino} values.
6391 Many current systems report an incorrect @code{d_ino} for a directory
6392 entry that is a mount point.
6395 @defmac AC_STRUCT_DIRENT_D_TYPE
6396 @acindex{STRUCT_DIRENT_D_TYPE}
6397 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6398 @c @caindex header_dirent_dirent_h
6399 @c @caindex member_struct_dirent_d_type
6400 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6401 Headers}). Then, if @code{struct dirent} contains a @code{d_type}
6402 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6405 @anchor{AC_STRUCT_ST_BLOCKS}
6406 @defmac AC_STRUCT_ST_BLOCKS
6407 @acindex{STRUCT_ST_BLOCKS}
6408 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6409 @cvindex HAVE_ST_BLOCKS
6411 @caindex member_struct_stat_st_blocks
6412 If @code{struct stat} contains an @code{st_blocks} member, define
6413 @code{HAVE_STRUCT_STAT_ST_BLOCKS}. Otherwise, require an
6414 @code{AC_LIBOBJ} replacement of @samp{fileblocks}. The former name,
6415 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6418 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6422 @defmac AC_STRUCT_TM
6424 @cvindex TM_IN_SYS_TIME
6426 @hdrindex{sys/time.h}
6427 If @file{time.h} does not define @code{struct tm}, define
6428 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6429 had better define @code{struct tm}.
6431 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6432 current systems. New programs need not use this macro.
6435 @anchor{AC_STRUCT_TIMEZONE}
6436 @defmac AC_STRUCT_TIMEZONE
6437 @acindex{STRUCT_TIMEZONE}
6438 @cvindex HAVE_DECL_TZNAME
6439 @cvindex HAVE_STRUCT_TM_TM_ZONE
6440 @cvindex HAVE_TM_ZONE
6441 @cvindex HAVE_TZNAME
6442 @c @caindex member_struct_tm_tm_zone
6443 @c @caindex struct_tm
6444 Figure out how to get the current timezone. If @code{struct tm} has a
6445 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6446 obsoleted @code{HAVE_TM_ZONE}). Otherwise, if the external array
6447 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6448 define @code{HAVE_DECL_TZNAME}.
6451 @node Generic Structures
6452 @subsection Generic Structure Checks
6454 These macros are used to find structure members not covered by the
6455 ``particular'' test macros.
6457 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6458 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6459 @dvar{includes, AC_INCLUDES_DEFAULT})
6460 @acindex{CHECK_MEMBER}
6461 @caindex member_@var{aggregate}_@var{member}
6462 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6463 If no @var{includes} are specified, the default includes are used
6464 (@pxref{Default Includes}).
6467 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6468 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6469 [[#include <pwd.h>]])
6472 You can use this macro for submembers:
6475 AC_CHECK_MEMBER(struct top.middle.bot)
6478 This macro caches its result in the
6479 @code{av_cv_member_@var{aggregate}_@var{member}} variable, with
6480 characters not suitable for a variable name mapped to underscores.
6483 @anchor{AC_CHECK_MEMBERS}
6484 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6485 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6486 @acindex{CHECK_MEMBERS}
6487 @cvindex HAVE_@var{aggregate}_@var{member}
6488 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6489 @var{members} using the previous macro. When @var{member} belongs to
6490 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6491 capitals, with spaces and dots replaced by underscores). If
6492 @var{action-if-found} is given, it is executed for each of the found
6493 members. If @var{action-if-not-found} is given, it is executed for each
6494 of the members that could not be found.
6496 @var{includes} is a series of include directives, defaulting to
6497 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6498 prior to the members under test.
6500 This macro uses M4 lists:
6502 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6512 The following macros check for C types, either builtin or typedefs. If
6513 there is no macro specifically defined to check for a type you need, and
6514 you don't need to check for any special properties of it, then you can
6515 use a general type-check macro.
6518 * Particular Types:: Special handling to find certain types
6519 * Generic Types:: How to find other types
6522 @node Particular Types
6523 @subsection Particular Type Checks
6525 @hdrindex{sys/types.h}
6528 @hdrindex{inttypes.h}
6529 These macros check for particular C types in @file{sys/types.h},
6530 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6533 The Gnulib @code{stdint} module is an alternate way to define many of
6534 these symbols; it is useful if you prefer your code to assume a
6535 C99-or-better environment. @xref{Gnulib}.
6537 @anchor{AC_TYPE_GETGROUPS}
6538 @defmac AC_TYPE_GETGROUPS
6539 @acindex{TYPE_GETGROUPS}
6540 @cvindex GETGROUPS_T
6541 @caindex type_getgroups
6542 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6543 is the base type of the array argument to @code{getgroups}.
6545 This macro caches the base type in the @code{ac_cv_type_getgroups}
6549 @defmac AC_TYPE_INT8_T
6550 @acindex{TYPE_INT8_T}
6551 @cvindex HAVE_INT8_T
6554 If @file{stdint.h} or @file{inttypes.h} does not define the type
6555 @code{int8_t}, define @code{int8_t} to a signed
6556 integer type that is exactly 8 bits wide and that uses two's complement
6557 representation, if such a type exists.
6558 If you are worried about porting to hosts that lack such a type, you can
6559 use the results of this macro in C89-or-later code as follows:
6563 # include <stdint.h>
6565 #if defined INT8_MAX || defined int8_t
6566 @emph{code using int8_t}
6568 @emph{complicated alternative using >8-bit 'signed char'}
6572 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6575 @defmac AC_TYPE_INT16_T
6576 @acindex{TYPE_INT16_T}
6577 @cvindex HAVE_INT16_T
6580 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6583 @defmac AC_TYPE_INT32_T
6584 @acindex{TYPE_INT32_T}
6585 @cvindex HAVE_INT32_T
6588 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6591 @defmac AC_TYPE_INT64_T
6592 @acindex{TYPE_INT64_T}
6593 @cvindex HAVE_INT64_T
6596 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6599 @defmac AC_TYPE_INTMAX_T
6600 @acindex{TYPE_INTMAX_T}
6601 @cvindex HAVE_INTMAX_T
6603 @c @caindex type_intmax_t
6604 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6605 define @code{HAVE_INTMAX_T}. Otherwise, define @code{intmax_t} to the
6606 widest signed integer type.
6609 @defmac AC_TYPE_INTPTR_T
6610 @acindex{TYPE_INTPTR_T}
6611 @cvindex HAVE_INTPTR_T
6613 @c @caindex type_intptr_t
6614 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6615 define @code{HAVE_INTPTR_T}. Otherwise, define @code{intptr_t} to a
6616 signed integer type wide enough to hold a pointer, if such a type
6620 @defmac AC_TYPE_LONG_DOUBLE
6621 @acindex{TYPE_LONG_DOUBLE}
6622 @cvindex HAVE_LONG_DOUBLE
6623 @caindex type_long_double
6624 If the C compiler supports a working @code{long double} type, define
6625 @code{HAVE_LONG_DOUBLE}. The @code{long double} type might have the
6626 same range and precision as @code{double}.
6628 This macro caches its result in the @code{ac_cv_type_long_double}
6631 This macro is obsolescent, as current C compilers support @code{long
6632 double}. New programs need not use this macro.
6635 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6636 @acindex{TYPE_LONG_DOUBLE_WIDER}
6637 @cvindex HAVE_LONG_DOUBLE_WIDER
6638 @caindex type_long_double_wider
6639 If the C compiler supports a working @code{long double} type with more
6640 range or precision than the @code{double} type, define
6641 @code{HAVE_LONG_DOUBLE_WIDER}.
6643 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6647 @defmac AC_TYPE_LONG_LONG_INT
6648 @acindex{TYPE_LONG_LONG_INT}
6649 @cvindex HAVE_LONG_LONG_INT
6650 @caindex type_long_long_int
6651 If the C compiler supports a working @code{long long int} type, define
6652 @code{HAVE_LONG_LONG_INT}. However, this test does not test
6653 @code{long long int} values in preprocessor @code{#if} expressions,
6654 because too many compilers mishandle such expressions.
6655 @xref{Preprocessor Arithmetic}.
6657 This macro caches its result in the @code{ac_cv_type_long_long_int}
6661 @defmac AC_TYPE_MBSTATE_T
6662 @acindex{TYPE_MBSTATE_T}
6665 @caindex type_mbstate_t
6666 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6667 @code{mbstate_t} type. Also, define @code{mbstate_t} to be a type if
6668 @code{<wchar.h>} does not declare it.
6670 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6674 @anchor{AC_TYPE_MODE_T}
6675 @defmac AC_TYPE_MODE_T
6676 @acindex{TYPE_MODE_T}
6678 @caindex type_mode_t
6679 Define @code{mode_t} to a suitable type, if standard headers do not
6682 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6685 @anchor{AC_TYPE_OFF_T}
6686 @defmac AC_TYPE_OFF_T
6687 @acindex{TYPE_OFF_T}
6690 Define @code{off_t} to a suitable type, if standard headers do not
6693 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6696 @anchor{AC_TYPE_PID_T}
6697 @defmac AC_TYPE_PID_T
6698 @acindex{TYPE_PID_T}
6701 Define @code{pid_t} to a suitable type, if standard headers do not
6704 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6707 @anchor{AC_TYPE_SIZE_T}
6708 @defmac AC_TYPE_SIZE_T
6709 @acindex{TYPE_SIZE_T}
6711 @caindex type_size_t
6712 Define @code{size_t} to a suitable type, if standard headers do not
6715 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6718 @defmac AC_TYPE_SSIZE_T
6719 @acindex{TYPE_SSIZE_T}
6721 @caindex type_ssize_t
6722 Define @code{ssize_t} to a suitable type, if standard headers do not
6725 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6728 @anchor{AC_TYPE_UID_T}
6729 @defmac AC_TYPE_UID_T
6730 @acindex{TYPE_UID_T}
6734 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6735 headers do not define them.
6737 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6740 @defmac AC_TYPE_UINT8_T
6741 @acindex{TYPE_UINT8_T}
6742 @cvindex HAVE_UINT8_T
6745 If @file{stdint.h} or @file{inttypes.h} does not define the type
6746 @code{uint8_t}, define @code{uint8_t} to an
6747 unsigned integer type that is exactly 8 bits wide, if such a type
6749 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6752 @defmac AC_TYPE_UINT16_T
6753 @acindex{TYPE_UINT16_T}
6754 @cvindex HAVE_UINT16_T
6757 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6760 @defmac AC_TYPE_UINT32_T
6761 @acindex{TYPE_UINT32_T}
6762 @cvindex HAVE_UINT32_T
6765 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6768 @defmac AC_TYPE_UINT64_T
6769 @acindex{TYPE_UINT64_T}
6770 @cvindex HAVE_UINT64_T
6773 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6776 @defmac AC_TYPE_UINTMAX_T
6777 @acindex{TYPE_UINTMAX_T}
6778 @cvindex HAVE_UINTMAX_T
6780 @c @caindex type_uintmax_t
6781 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6782 define @code{HAVE_UINTMAX_T}. Otherwise, define @code{uintmax_t} to the
6783 widest unsigned integer type.
6786 @defmac AC_TYPE_UINTPTR_T
6787 @acindex{TYPE_UINTPTR_T}
6788 @cvindex HAVE_UINTPTR_T
6790 @c @caindex type_uintptr_t
6791 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6792 define @code{HAVE_UINTPTR_T}. Otherwise, define @code{uintptr_t} to an
6793 unsigned integer type wide enough to hold a pointer, if such a type
6797 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6798 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6799 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6800 @caindex type_unsigned_long_long_int
6801 If the C compiler supports a working @code{unsigned long long int} type,
6802 define @code{HAVE_UNSIGNED_LONG_LONG_INT}. However, this test does not test
6803 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6804 because too many compilers mishandle such expressions.
6805 @xref{Preprocessor Arithmetic}.
6807 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6812 @subsection Generic Type Checks
6814 These macros are used to check for types not covered by the ``particular''
6817 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6818 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6819 @acindex{CHECK_TYPE}
6820 @caindex type_@var{type}
6821 Check whether @var{type} is defined. It may be a compiler builtin type
6822 or defined by the @var{includes}. @var{includes} is a series of include
6823 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6824 Includes}), which are used prior to the type under test.
6826 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6827 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not). The
6828 same test is applied when compiling for C++, which means that in C++
6829 @var{type} should be a type-id and should not be an anonymous
6830 @samp{struct} or @samp{union}.
6832 This macro caches its result in the @code{ac_cv_type_@var{type}}
6833 variable, with @samp{*} mapped to @samp{p} and other characters not
6834 suitable for a variable name mapped to underscores.
6838 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6839 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6840 @acindex{CHECK_TYPES}
6841 @cvindex HAVE_@var{type}
6842 For each @var{type} of the @var{types} that is defined, define
6843 @code{HAVE_@var{type}} (in all capitals). Each @var{type} must follow
6844 the rules of @code{AC_CHECK_TYPE}. If no @var{includes} are
6845 specified, the default includes are used (@pxref{Default Includes}). If
6846 @var{action-if-found} is given, it is additional shell code to execute
6847 when one of the types is found. If @var{action-if-not-found} is given,
6848 it is executed when one of the types is not found.
6850 This macro uses M4 lists:
6852 AC_CHECK_TYPES([ptrdiff_t])
6853 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6854 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6859 Autoconf, up to 2.13, used to provide to another version of
6860 @code{AC_CHECK_TYPE}, broken by design. In order to keep backward
6861 compatibility, a simple heuristic, quite safe but not totally, is
6862 implemented. In case of doubt, read the documentation of the former
6863 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6866 @node Compilers and Preprocessors
6867 @section Compilers and Preprocessors
6869 @cindex Preprocessors
6872 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6873 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6874 the output of the compiler, typically to the empty string if
6875 Posix and @samp{.exe} if a DOS variant.
6878 They also define the output variable @code{OBJEXT} based on the
6879 output of the compiler, after @file{.c} files have been excluded, typically
6880 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6882 If the compiler being used does not produce executables, the tests fail. If
6883 the executables can't be run, and cross-compilation is not enabled, they
6884 fail too. @xref{Manual Configuration}, for more on support for cross
6888 * Specific Compiler Characteristics:: Some portability issues
6889 * Generic Compiler Characteristics:: Language independent tests and features
6890 * C Compiler:: Checking its characteristics
6891 * C++ Compiler:: Likewise
6892 * Objective C Compiler:: Likewise
6893 * Objective C++ Compiler:: Likewise
6894 * Erlang Compiler and Interpreter:: Likewise
6895 * Fortran Compiler:: Likewise
6898 @node Specific Compiler Characteristics
6899 @subsection Specific Compiler Characteristics
6901 Some compilers exhibit different behaviors.
6904 @item Static/Dynamic Expressions
6905 Autoconf relies on a trick to extract one bit of information from the C
6906 compiler: using negative array sizes. For instance the following
6907 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6911 static int test_array[sizeof (int) == 4 ? 1 : -1];
6915 To our knowledge, there is a single compiler that does not support this
6916 trick: the HP C compilers (the real ones, not only the
6917 ``bundled'') on HP-UX 11.00.
6918 They incorrectly reject the above program with the diagnostic
6919 ``Variable-length arrays cannot have static storage.''
6920 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
6921 not from the @code{? 1 : -1}, and
6922 Autoconf works around this problem by casting @code{sizeof (int)} to
6923 @code{long int} before comparing it.
6926 @node Generic Compiler Characteristics
6927 @subsection Generic Compiler Characteristics
6929 @anchor{AC_CHECK_SIZEOF}
6930 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6931 @dvar{includes, AC_INCLUDES_DEFAULT})
6932 @acindex{CHECK_SIZEOF}
6933 @cvindex SIZEOF_@var{type-or-expr}
6934 @caindex sizeof_@var{type-or-expr}
6935 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6936 the size in bytes of @var{type-or-expr}, which may be either a type or
6937 an expression returning a value that has a size. If the expression
6938 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6939 @var{includes} is a series of include directives, defaulting to
6940 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6941 prior to the expression under test.
6943 This macro now works even when cross-compiling. The @var{unused}
6944 argument was used when cross-compiling.
6946 For example, the call
6949 AC_CHECK_SIZEOF([int *])
6953 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6955 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
6956 variable, with @samp{*} mapped to @samp{p} and other characters not
6957 suitable for a variable name mapped to underscores.
6960 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6961 @acindex{CHECK_ALIGNOF}
6962 @cvindex ALIGNOF_@var{type}
6963 @caindex alignof_@var{type-or-expr}
6964 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6965 alignment in bytes of @var{type}. @samp{@var{type} y;} must be valid as
6966 a structure member declaration. If @samp{type} is unknown, the result
6967 is 0. If no @var{includes} are specified, the default includes are used
6968 (@pxref{Default Includes}).
6970 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
6971 variable, with @samp{*} mapped to @samp{p} and other characters not
6972 suitable for a variable name mapped to underscores.
6975 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6976 @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6977 @acindex{COMPUTE_INT}
6978 Store into the shell variable @var{var} the value of the integer
6979 @var{expression}. The
6980 value should fit in an initializer in a C variable of type @code{signed
6981 long}. To support cross compilation (in which case, the macro only works on
6982 hosts that use twos-complement arithmetic), it should be possible to evaluate
6983 the expression at compile-time. If no @var{includes} are specified, the
6984 default includes are used (@pxref{Default Includes}).
6986 Execute @var{action-if-fails} if the value cannot be determined correctly.
6989 @defmac AC_LANG_WERROR
6990 @acindex{LANG_WERROR}
6991 Normally Autoconf ignores warnings generated by the compiler, linker, and
6992 preprocessor. If this macro is used, warnings count as fatal
6993 errors for the current language. This macro is useful when the
6994 results of configuration are used where warnings are unacceptable; for
6995 instance, if parts of a program are built with the GCC
6997 option. If the whole program is built using @option{-Werror} it is
6998 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7005 @ovindex OPENMP_CFLAGS
7006 @ovindex OPENMP_CXXFLAGS
7007 @ovindex OPENMP_FFLAGS
7008 @ovindex OPENMP_FCFLAGS
7009 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
7010 and Fortran that simplify optimization of shared memory parallelism,
7011 which is a common problem on multicore CPUs.
7013 If the current language is C, the macro @code{AC_OPENMP} sets the
7014 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7015 supporting OpenMP@. @code{OPENMP_CFLAGS} is set to empty if the
7016 compiler already supports OpenMP, if it has no way to activate OpenMP
7017 support, or if the user rejects OpenMP support by invoking
7018 @samp{configure} with the @samp{--disable-openmp} option.
7020 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7021 preprocessing program source, and when linking programs. Therefore you
7022 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7023 that use OpenMP@. If you preprocess OpenMP-specific C code, you also
7024 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}. The presence of
7025 OpenMP support is revealed at compile time by the preprocessor macro
7028 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7029 shared library to the program's dependencies, so its use is recommended
7030 only on programs that actually require OpenMP.
7032 If the current language is C++, @code{AC_OPENMP} sets the variable
7033 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler. The same remarks
7036 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7037 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7038 respectively. Similar remarks as for C hold, except that
7039 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7040 signals OpenMP support.
7042 For portability, it is best to avoid spaces between @samp{#} and
7043 @samp{pragma omp}. That is, write @samp{#pragma omp}, not
7044 @samp{# pragma omp}. The Sun WorkShop 6.2 C compiler chokes on the
7049 @subsection C Compiler Characteristics
7051 The following macros provide ways to find and exercise a C Compiler.
7052 There are a few constructs that ought to be avoided, but do not deserve
7053 being checked for, since they can easily be worked around.
7056 @item Don't use lines containing solitary backslashes
7057 They tickle a bug in the HP-UX C compiler (checked on
7059 11.00, and 11i). When given the following source:
7064 * A comment with backslash-newlines in it. %@{ %@} *\
7068 " A string with backslash-newlines in it %@{ %@} \\
7070 char apostrophe = '\\
7078 the compiler incorrectly fails with the diagnostics ``Non-terminating
7079 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7080 Removing the lines with solitary backslashes solves the problem.
7082 @item Don't compile several files at once if output matters to you
7083 Some compilers, such as HP's, report names of files being
7084 compiled when given more than one file operand. For instance:
7093 This can cause problems if you observe the output of the compiler to
7094 detect failures. Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7095 b.o} solves the issue.
7097 @item Don't rely on @code{#error} failing
7098 The IRIX C compiler does not fail when #error is preprocessed; it
7099 simply emits a diagnostic and continues, exiting successfully. So,
7100 instead of an error directive like @code{#error "Unsupported word size"}
7101 it is more portable to use an invalid directive like @code{#Unsupported
7102 word size} in Autoconf tests. In ordinary source code, @code{#error} is
7103 OK, since installers with inadequate compilers like IRIX can simply
7104 examine these compilers' diagnostic output.
7106 @item Don't rely on correct @code{#line} support
7107 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7108 diagnoses @code{#line} directives whose line
7109 numbers are greater than 32767. Nothing in Posix
7110 makes this invalid. That is why Autoconf stopped issuing
7111 @code{#line} directives.
7114 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7120 @caindex prog_cc_c89
7121 Determine a C compiler to use. If @code{CC} is not already set in the
7122 environment, check for @code{gcc} and @code{cc}, then for other C
7123 compilers. Set output variable @code{CC} to the name of the compiler
7126 This macro may, however, be invoked with an optional first argument
7127 which, if specified, must be a blank-separated list of C compilers to
7128 search for. This just gives the user an opportunity to specify an
7129 alternative search list for the C compiler. For example, if you didn't
7130 like the default order, then you could invoke @code{AC_PROG_CC} like
7134 AC_PROG_CC([gcc cl cc])
7137 If the C compiler does not handle function prototypes correctly by
7138 default, try to add an option to output variable @code{CC} to make it
7139 so. This macro tries various options that select standard-conformance
7140 modes on various systems.
7142 After calling this macro you can check whether the C compiler has been
7143 set to accept ANSI C89 (ISO C90); if not, the shell
7145 @code{ac_cv_prog_cc_c89} is set to @samp{no}. See also
7146 @code{AC_C_PROTOTYPES} below.
7148 If using the GNU C compiler, set shell variable @code{GCC} to
7149 @samp{yes}. If output variable @code{CFLAGS} was not already set, set
7150 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7151 where GCC does not accept @option{-g}), or @option{-g} for
7152 other compilers. If your package does not like this default, then it is
7153 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7154 and before @code{AC_PROG_CC} to select an empty default instead.
7156 Many Autoconf macros use a compiler, and thus call
7157 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7158 determined before the body of the outermost @code{AC_DEFUN} macro.
7159 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7160 performs certain checks (such as the proper value of @env{EXEEXT}) only
7161 on the first invocation. Therefore, care must be used when invoking
7162 this macro from within another macro rather than at the top level
7163 (@pxref{Expanded Before Required}).
7166 @anchor{AC_PROG_CC_C_O}
7167 @defmac AC_PROG_CC_C_O
7168 @acindex{PROG_CC_C_O}
7169 @cvindex NO_MINUS_C_MINUS_O
7170 @caindex prog_cc_@var{compiler}_c_o
7171 If the C compiler does not accept the @option{-c} and @option{-o} options
7172 simultaneously, define @code{NO_MINUS_C_MINUS_O}. This macro actually
7173 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7174 the first @code{cc} in the path. The test fails if one fails. This
7175 macro was created for GNU Make to choose the default C compilation
7178 For the compiler @var{compiler}, this macro caches its result in the
7179 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7187 Set output variable @code{CPP} to a command that runs the
7188 C preprocessor. If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7189 It is only portable to run @code{CPP} on files with a @file{.c}
7192 Some preprocessors don't indicate missing include files by the error
7193 status. For such preprocessors an internal variable is set that causes
7194 other macros to check the standard error from the preprocessor and
7195 consider the test failed if any warnings have been reported.
7196 For most preprocessors, though, warnings do not cause include-file
7197 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7200 @defmac AC_PROG_CPP_WERROR
7201 @acindex{PROG_CPP_WERROR}
7203 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7204 preprocessor as errors even if the preprocessor exit status indicates
7205 success. This is useful for avoiding headers that generate mandatory
7206 warnings, such as deprecation notices.
7210 The following macros check for C compiler or machine architecture
7211 features. To check for characteristics not listed here, use
7212 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7213 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7215 @defmac AC_PROG_CC_STDC
7216 @acindex{PROG_CC_STDC}
7217 @caindex prog_cc_stdc
7218 If the C compiler cannot compile ISO Standard C (currently
7219 C99), try to add an option to output variable @code{CC} to make it work.
7220 If the compiler does not support C99, fall back to supporting
7223 After calling this macro you can check whether the C compiler has been
7224 set to accept Standard C; if not, the shell variable
7225 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7228 @defmac AC_PROG_CC_C89
7229 @acindex{PROG_CC_C89}
7230 @caindex prog_cc_c89
7231 If the C compiler is not in ANSI C89 (ISO C90) mode by
7232 default, try to add an option to output variable @code{CC} to make it
7233 so. This macro tries various options that select ANSI C89 on
7234 some system or another, preferring extended functionality modes over
7235 strict conformance modes. It considers the compiler to be in
7236 ANSI C89 mode if it handles function prototypes correctly.
7238 After calling this macro you can check whether the C compiler has been
7239 set to accept ANSI C89; if not, the shell variable
7240 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7242 This macro is called automatically by @code{AC_PROG_CC}.
7245 @defmac AC_PROG_CC_C99
7246 @acindex{PROG_CC_C99}
7247 @caindex prog_cc_c99
7248 If the C compiler is not in C99 mode by default, try to add an
7249 option to output variable @code{CC} to make it so. This macro tries
7250 various options that select C99 on some system or another, preferring
7251 extended functionality modes over strict conformance modes. It
7252 considers the compiler to be in C99 mode if it handles @code{_Bool},
7253 @code{//} comments, flexible array members, @code{inline}, signed and
7254 unsigned @code{long long int}, mixed code and declarations, named
7255 initialization of structs,
7256 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7257 in @code{for} loops, and variable length arrays.
7259 After calling this macro you can check whether the C compiler has been
7260 set to accept C99; if not, the shell variable
7261 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7264 @defmac AC_C_BACKSLASH_A
7265 @acindex{C_BACKSLASH_A}
7266 @cvindex HAVE_C_BACKSLASH_A
7267 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7270 This macro is obsolescent, as current C compilers understand @samp{\a}.
7271 New programs need not use this macro.
7274 @anchor{AC_C_BIGENDIAN}
7275 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7276 @ovar{action-if-unknown}, @ovar{action-if-universal})
7277 @acindex{C_BIGENDIAN}
7278 @cvindex WORDS_BIGENDIAN
7280 If words are stored with the most significant byte first (like Motorola
7281 and SPARC CPUs), execute @var{action-if-true}. If words are stored with
7282 the least significant byte first (like Intel and VAX CPUs), execute
7283 @var{action-if-false}.
7285 This macro runs a test-case if endianness cannot be determined from the
7286 system header files. When cross-compiling, the test-case is not run but
7287 grep'ed for some magic values. @var{action-if-unknown} is executed if
7288 the latter case fails to determine the byte sex of the host system.
7290 In some cases a single run of a compiler can generate code for multiple
7291 architectures. This can happen, for example, when generating Mac OS X
7292 universal binary files, which work on both PowerPC and Intel
7293 architectures. In this case, the different variants might be for
7294 different architectures whose endiannesses differ. If
7295 @command{configure} detects this, it executes @var{action-if-universal}
7296 instead of @var{action-if-unknown}.
7298 The default for @var{action-if-true} is to define
7299 @samp{WORDS_BIGENDIAN}. The default for @var{action-if-false} is to do
7300 nothing. The default for @var{action-if-unknown} is to
7301 abort configure and tell the installer how to bypass this test.
7302 And finally, the default for @var{action-if-universal} is to ensure that
7303 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7304 detected and the current code is big-endian; this default works only if
7305 @command{autoheader} is used (@pxref{autoheader Invocation}).
7307 If you use this macro without specifying @var{action-if-universal}, you
7308 should also use @code{AC_CONFIG_HEADERS}; otherwise
7309 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7318 If the C compiler does not fully support the @code{const} keyword,
7319 define @code{const} to be empty. Some C compilers that do
7320 not define @code{__STDC__} do support @code{const}; some compilers that
7321 define @code{__STDC__} do not completely support @code{const}. Programs
7322 can simply use @code{const} as if every C compiler supported it; for
7323 those that don't, the makefile or configuration header file
7324 defines it as empty.
7326 Occasionally installers use a C++ compiler to compile C code, typically
7327 because they lack a C compiler. This causes problems with @code{const},
7328 because C and C++ treat @code{const} differently. For example:
7335 is valid in C but not in C++. These differences unfortunately cannot be
7336 papered over by defining @code{const} to be empty.
7338 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7339 as this generally yields better results in practice. However, using a
7340 C++ compiler to compile C code is not recommended or supported, and
7341 installers who run into trouble in this area should get a C compiler
7342 like GCC to compile their C code.
7344 This macro caches its result in the @code{ac_cv_c_const} variable.
7346 This macro is obsolescent, as current C compilers support @code{const}.
7347 New programs need not use this macro.
7350 @defmac AC_C_RESTRICT
7351 @acindex{C_RESTRICT}
7354 If the C compiler recognizes a variant spelling for the @code{restrict}
7355 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7356 then define @code{restrict} to that; this is more likely to do the right
7357 thing with compilers that support language variants where plain
7358 @code{restrict} is not a keyword. Otherwise, if the C compiler
7359 recognizes the @code{restrict} keyword, don't do anything.
7360 Otherwise, define @code{restrict} to be empty.
7361 Thus, programs may simply use @code{restrict} as if every C compiler
7362 supported it; for those that do not, the makefile
7363 or configuration header defines it away.
7365 Although support in C++ for the @code{restrict} keyword is not
7366 required, several C++ compilers do accept the keyword.
7367 This macro works for them, too.
7369 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7370 if @code{restrict} is not supported, and a supported spelling otherwise.
7373 @defmac AC_C_VOLATILE
7374 @acindex{C_VOLATILE}
7376 If the C compiler does not understand the keyword @code{volatile},
7377 define @code{volatile} to be empty. Programs can simply use
7378 @code{volatile} as if every C compiler supported it; for those that do
7379 not, the makefile or configuration header defines it as
7382 If the correctness of your program depends on the semantics of
7383 @code{volatile}, simply defining it to be empty does, in a sense, break
7384 your code. However, given that the compiler does not support
7385 @code{volatile}, you are at its mercy anyway. At least your
7386 program compiles, when it wouldn't before.
7387 @xref{Volatile Objects}, for more about @code{volatile}.
7389 In general, the @code{volatile} keyword is a standard C feature, so
7390 you might expect that @code{volatile} is available only when
7391 @code{__STDC__} is defined. However, Ultrix 4.3's native compiler does
7392 support volatile, but does not define @code{__STDC__}.
7394 This macro is obsolescent, as current C compilers support @code{volatile}.
7395 New programs need not use this macro.
7398 @anchor{AC_C_INLINE}
7402 If the C compiler supports the keyword @code{inline}, do nothing.
7403 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7404 if it accepts one of those, otherwise define @code{inline} to be empty.
7407 @anchor{AC_C_CHAR_UNSIGNED}
7408 @defmac AC_C_CHAR_UNSIGNED
7409 @acindex{C_CHAR_UNSIGNED}
7410 @cvindex __CHAR_UNSIGNED__
7411 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7412 unless the C compiler predefines it.
7414 These days, using this macro is not necessary. The same information can
7415 be determined by this portable alternative, thus avoiding the use of
7416 preprocessor macros in the namespace reserved for the implementation.
7421 # define CHAR_UNSIGNED 1
7426 @defmac AC_C_STRINGIZE
7427 @acindex{C_STRINGIZE}
7428 @cvindex HAVE_STRINGIZE
7429 If the C preprocessor supports the stringizing operator, define
7430 @code{HAVE_STRINGIZE}. The stringizing operator is @samp{#} and is
7431 found in macros such as this:
7437 This macro is obsolescent, as current C compilers support the
7438 stringizing operator. New programs need not use this macro.
7441 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7442 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7443 @cvindex FLEXIBLE_ARRAY_MEMBER
7444 If the C compiler supports flexible array members, define
7445 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7446 That way, a declaration like this:
7452 double val[FLEXIBLE_ARRAY_MEMBER];
7457 will let applications use the ``struct hack'' even with compilers that
7458 do not support flexible array members. To allocate and use such an
7459 object, you can use code like this:
7463 size_t n = compute_value_count ();
7465 malloc (offsetof (struct s, val)
7466 + n * sizeof (double));
7468 for (i = 0; i < n; i++)
7469 p->val[i] = compute_value (i);
7473 @defmac AC_C_VARARRAYS
7474 @acindex{C_VARARRAYS}
7475 @cvindex HAVE_C_VARARRAYS
7476 If the C compiler supports variable-length arrays, define
7477 @code{HAVE_C_VARARRAYS}. A variable-length array is an array of automatic
7478 storage duration whose length is determined at run time, when the array
7484 @cvindex HAVE_TYPEOF
7486 If the C compiler supports GCC's @code{typeof} syntax either
7488 through a different spelling of the keyword (e.g., @code{__typeof__}),
7489 define @code{HAVE_TYPEOF}. If the support is available only through a
7490 different spelling, define @code{typeof} to that spelling.
7493 @defmac AC_C_PROTOTYPES
7494 @acindex{C_PROTOTYPES}
7496 @cvindex __PROTOTYPES
7498 If function prototypes are understood by the compiler (as determined by
7499 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7500 Defining @code{__PROTOTYPES} is for the benefit of
7501 header files that cannot use macros that infringe on user name space.
7503 This macro is obsolescent, as current C compilers support prototypes.
7504 New programs need not use this macro.
7507 @anchor{AC_PROG_GCC_TRADITIONAL}
7508 @defmac AC_PROG_GCC_TRADITIONAL
7509 @acindex{PROG_GCC_TRADITIONAL}
7511 Add @option{-traditional} to output variable @code{CC} if using the
7512 GNU C compiler and @code{ioctl} does not work properly without
7513 @option{-traditional}. That usually happens when the fixed header files
7514 have not been installed on an old system.
7516 This macro is obsolescent, since current versions of the GNU C
7517 compiler fix the header files automatically when installed.
7522 @subsection C++ Compiler Characteristics
7525 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7531 Determine a C++ compiler to use. Check whether the environment variable
7532 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7533 variable @code{CXX} to its value.
7535 Otherwise, if the macro is invoked without an argument, then search for
7536 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7537 then other names). If none of those checks succeed, then as a last
7538 resort set @code{CXX} to @code{g++}.
7540 This macro may, however, be invoked with an optional first argument
7541 which, if specified, must be a blank-separated list of C++ compilers to
7542 search for. This just gives the user an opportunity to specify an
7543 alternative search list for the C++ compiler. For example, if you
7544 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7548 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7551 If using the GNU C++ compiler, set shell variable @code{GXX} to
7552 @samp{yes}. If output variable @code{CXXFLAGS} was not already set, set
7553 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7554 systems where G++ does not accept @option{-g}), or @option{-g} for other
7555 compilers. If your package does not like this default, then it is
7556 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7557 and before @code{AC_PROG_CXX} to select an empty default instead.
7561 @defmac AC_PROG_CXXCPP
7562 @acindex{PROG_CXXCPP}
7565 Set output variable @code{CXXCPP} to a command that runs the C++
7566 preprocessor. If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7567 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7568 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7570 Some preprocessors don't indicate missing include files by the error
7571 status. For such preprocessors an internal variable is set that causes
7572 other macros to check the standard error from the preprocessor and
7573 consider the test failed if any warnings have been reported. However,
7574 it is not known whether such broken preprocessors exist for C++.
7577 @defmac AC_PROG_CXX_C_O
7578 @acindex{PROG_CXX_C_O}
7579 @cvindex CXX_NO_MINUS_C_MINUS_O
7580 Test whether the C++ compiler accepts the options @option{-c} and
7581 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7586 @node Objective C Compiler
7587 @subsection Objective C Compiler Characteristics
7590 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7596 Determine an Objective C compiler to use. If @code{OBJC} is not already
7597 set in the environment, check for Objective C compilers. Set output
7598 variable @code{OBJC} to the name of the compiler found.
7600 This macro may, however, be invoked with an optional first argument
7601 which, if specified, must be a blank-separated list of Objective C compilers to
7602 search for. This just gives the user an opportunity to specify an
7603 alternative search list for the Objective C compiler. For example, if you
7604 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7608 AC_PROG_OBJC([gcc objcc objc])
7611 If using the GNU Objective C compiler, set shell variable
7612 @code{GOBJC} to @samp{yes}. If output variable @code{OBJCFLAGS} was not
7613 already set, set it to @option{-g -O2} for the GNU Objective C
7614 compiler (@option{-O2} on systems where @command{gcc} does not accept
7615 @option{-g}), or @option{-g} for other compilers.
7618 @defmac AC_PROG_OBJCPP
7619 @acindex{PROG_OBJCPP}
7622 Set output variable @code{OBJCPP} to a command that runs the Objective C
7623 preprocessor. If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7627 @node Objective C++ Compiler
7628 @subsection Objective C++ Compiler Characteristics
7631 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7632 @acindex{PROG_OBJCXX}
7634 @evindex OBJCXXFLAGS
7636 @ovindex OBJCXXFLAGS
7637 Determine an Objective C++ compiler to use. If @code{OBJCXX} is not already
7638 set in the environment, check for Objective C++ compilers. Set output
7639 variable @code{OBJCXX} to the name of the compiler found.
7641 This macro may, however, be invoked with an optional first argument
7642 which, if specified, must be a blank-separated list of Objective C++ compilers
7643 to search for. This just gives the user an opportunity to specify an
7644 alternative search list for the Objective C++ compiler. For example, if you
7645 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7649 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7652 If using the GNU Objective C++ compiler, set shell variable
7653 @code{GOBJCXX} to @samp{yes}. If output variable @code{OBJCXXFLAGS} was not
7654 already set, set it to @option{-g -O2} for the GNU Objective C++
7655 compiler (@option{-O2} on systems where @command{gcc} does not accept
7656 @option{-g}), or @option{-g} for other compilers.
7659 @defmac AC_PROG_OBJCXXCPP
7660 @acindex{PROG_OBJCXXCPP}
7663 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7664 preprocessor. If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7668 @node Erlang Compiler and Interpreter
7669 @subsection Erlang Compiler and Interpreter Characteristics
7672 Autoconf defines the following macros for determining paths to the essential
7673 Erlang/OTP programs:
7675 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7676 @acindex{ERLANG_PATH_ERLC}
7681 Determine an Erlang compiler to use. If @code{ERLC} is not already set in the
7682 environment, check for @command{erlc}. Set output variable @code{ERLC} to the
7683 complete path of the compiler command found. In addition, if @code{ERLCFLAGS}
7684 is not set in the environment, set it to an empty value.
7686 The two optional arguments have the same meaning as the two last arguments of
7687 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program. For
7688 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7692 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7696 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7697 @acindex{ERLANG_NEED_ERLC}
7698 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7699 error message and exits the @command{configure} script if the @command{erlc}
7700 program is not found.
7703 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7704 @acindex{ERLANG_PATH_ERL}
7707 Determine an Erlang interpreter to use. If @code{ERL} is not already
7709 environment, check for @command{erl}. Set output variable @code{ERL} to the
7710 complete path of the interpreter command found.
7712 The two optional arguments have the same meaning as the two last arguments of
7713 macro @code{AC_PROG_PATH} for looking for the @command{erl} program. For
7714 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7718 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7722 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7723 @acindex{ERLANG_NEED_ERL}
7724 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7725 error message and exits the @command{configure} script if the @command{erl}
7726 program is not found.
7730 @node Fortran Compiler
7731 @subsection Fortran Compiler Characteristics
7735 The Autoconf Fortran support is divided into two categories: legacy
7736 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7737 The former are intended for traditional Fortran 77 code, and have output
7738 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}. The latter
7739 are for newer programs that can (or must) compile under the newer
7740 Fortran standards, and have output variables like @code{FC},
7741 @code{FCFLAGS}, and @code{FCLIBS}.
7743 Except for two new macros @code{AC_FC_SRCEXT} and
7744 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7745 behave almost identically, and so they are documented together in this
7749 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7755 Determine a Fortran 77 compiler to use. If @code{F77} is not already
7756 set in the environment, then check for @code{g77} and @code{f77}, and
7757 then some other names. Set the output variable @code{F77} to the name
7758 of the compiler found.
7760 This macro may, however, be invoked with an optional first argument
7761 which, if specified, must be a blank-separated list of Fortran 77
7762 compilers to search for. This just gives the user an opportunity to
7763 specify an alternative search list for the Fortran 77 compiler. For
7764 example, if you didn't like the default order, then you could invoke
7765 @code{AC_PROG_F77} like this:
7768 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7771 If using @code{g77} (the GNU Fortran 77 compiler), then
7772 set the shell variable @code{G77} to @samp{yes}.
7773 If the output variable @code{FFLAGS} was not already set in the
7774 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7775 where @code{g77} does not accept @option{-g}). Otherwise, set
7776 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7779 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7785 Determine a Fortran compiler to use. If @code{FC} is not already set in
7786 the environment, then @code{dialect} is a hint to indicate what Fortran
7787 dialect to search for; the default is to search for the newest available
7788 dialect. Set the output variable @code{FC} to the name of the compiler
7791 By default, newer dialects are preferred over older dialects, but if
7792 @code{dialect} is specified then older dialects are preferred starting
7793 with the specified dialect. @code{dialect} can currently be one of
7794 Fortran 77, Fortran 90, or Fortran 95. However, this is only a hint of
7795 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7796 and no attempt is made to guarantee that a particular language standard
7797 is actually supported. Thus, it is preferable that you avoid the
7798 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7799 the latest Fortran standard.
7801 This macro may, alternatively, be invoked with an optional first argument
7802 which, if specified, must be a blank-separated list of Fortran
7803 compilers to search for, just as in @code{AC_PROG_F77}.
7805 If the output variable @code{FCFLAGS} was not already set in the
7806 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7807 @option{-O2} where @code{g77} does not accept @option{-g}). Otherwise,
7808 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7811 @defmac AC_PROG_F77_C_O
7812 @defmacx AC_PROG_FC_C_O
7813 @acindex{PROG_F77_C_O}
7814 @acindex{PROG_FC_C_O}
7815 @cvindex F77_NO_MINUS_C_MINUS_O
7816 @cvindex FC_NO_MINUS_C_MINUS_O
7817 Test whether the Fortran compiler accepts the options @option{-c} and
7818 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7819 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7822 The following macros check for Fortran compiler characteristics.
7823 To check for characteristics not listed here, use
7824 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7825 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7826 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7827 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7830 @defmac AC_F77_LIBRARY_LDFLAGS
7831 @defmacx AC_FC_LIBRARY_LDFLAGS
7832 @acindex{F77_LIBRARY_LDFLAGS}
7834 @acindex{FC_LIBRARY_LDFLAGS}
7836 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7837 @dfn{Fortran intrinsic and runtime libraries} that are required to
7838 successfully link a Fortran program or shared library. The output
7839 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7840 should be included after @code{LIBS} when linking).
7842 This macro is intended to be used in those situations when it is
7843 necessary to mix, e.g., C++ and Fortran source code in a single
7844 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7845 automake, GNU Automake}).
7847 For example, if object files from a C++ and Fortran compiler must be
7848 linked together, then the C++ compiler/linker must be used for linking
7849 (since special C++-ish things need to happen at link time like calling
7850 global constructors, instantiating templates, enabling exception
7853 However, the Fortran intrinsic and runtime libraries must be linked in
7854 as well, but the C++ compiler/linker doesn't know by default how to add
7855 these Fortran 77 libraries. Hence, this macro was created to determine
7856 these Fortran libraries.
7858 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7859 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7860 link C/C++ with Fortran; see below.
7863 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7864 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7865 @acindex{F77_DUMMY_MAIN}
7866 @cvindex F77_DUMMY_MAIN
7867 With many compilers, the Fortran libraries detected by
7868 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7869 their own @code{main} entry function that initializes things like
7870 Fortran I/O, and which then calls a user-provided entry function named
7871 (say) @code{MAIN__} to run the user's program. The
7872 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7873 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7876 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7877 one prefers to provide one's own @code{main} and skip the Fortran
7878 library initializations. In this case, however, one may still need to
7879 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7880 on some systems. @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7881 detects whether any such routine is @emph{required} for linking, and
7882 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7883 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7884 was found, and @code{none} when no such dummy main is needed.
7886 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7887 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7888 @emph{if} it is required. @var{action-if-not-found} defaults to
7889 exiting with an error.
7891 In order to link with Fortran routines, the user's C/C++ program should
7892 then include the following code to define the dummy main if it is
7896 #ifdef F77_DUMMY_MAIN
7900 int F77_DUMMY_MAIN() @{ return 1; @}
7904 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7906 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7907 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7908 explicitly unless one wants to change the default actions.
7917 As discussed above, many Fortran libraries allow you to provide an entry
7918 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7919 is then called by a @code{main} function in the Fortran libraries that
7920 initializes things like Fortran I/O@. The
7921 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7922 @emph{possible} to utilize such an alternate main function, and defines
7923 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function. (If no
7924 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7925 simply defined to @code{main}.)
7927 Thus, when calling Fortran routines from C that perform things like I/O,
7928 one should use this macro and declare the "main" function like so:
7934 int F77_MAIN(int argc, char *argv[]);
7937 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7940 @defmac AC_F77_WRAPPERS
7941 @defmacx AC_FC_WRAPPERS
7942 @acindex{F77_WRAPPERS}
7945 @acindex{FC_WRAPPERS}
7948 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7949 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7950 mangle the names of C/C++ identifiers, and identifiers with underscores,
7951 respectively, so that they match the name-mangling scheme used by the
7954 Fortran is case-insensitive, and in order to achieve this the Fortran
7955 compiler converts all identifiers into a canonical case and format. To
7956 call a Fortran subroutine from C or to write a C function that is
7957 callable from Fortran, the C program must explicitly use identifiers in
7958 the format expected by the Fortran compiler. In order to do this, one
7959 simply wraps all C identifiers in one of the macros provided by
7960 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}. For example, suppose
7961 you have the following Fortran 77 subroutine:
7964 subroutine foobar (x, y)
7965 double precision x, y
7971 You would then declare its prototype in C or C++ as:
7974 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7976 extern "C" /* prevent C++ name mangling */
7978 void FOOBAR_F77(double *x, double *y);
7981 Note that we pass both the lowercase and uppercase versions of the
7982 function name to @code{F77_FUNC} so that it can select the right one.
7983 Note also that all parameters to Fortran 77 routines are passed as
7984 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
7987 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7989 Although Autoconf tries to be intelligent about detecting the
7990 name-mangling scheme of the Fortran compiler, there may be Fortran
7991 compilers that it doesn't support yet. In this case, the above code
7992 generates a compile-time error, but some other behavior
7993 (e.g., disabling Fortran-related features) can be induced by checking
7994 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7996 Now, to call that routine from a C program, we would do something like:
8000 double x = 2.7183, y;
8001 FOOBAR_F77 (&x, &y);
8005 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8006 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8007 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments). This is
8008 because some Fortran compilers mangle names differently if they contain
8012 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8013 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8016 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8017 hold the mangled version @var{name} according to the rules of the
8018 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8019 @code{AC_FC_WRAPPERS}). @var{shellvar} is optional; if it is not
8020 supplied, the shell variable is simply @var{name}. The purpose of
8021 this macro is to give the caller a way to access the name-mangling
8022 information other than through the C preprocessor as above, for example,
8023 to call Fortran routines from some language other than C/C++.
8026 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8027 @ovar{action-if-failure})
8029 By default, the @code{FC} macros perform their tests using a @file{.f}
8030 extension for source-code files. Some compilers, however, only enable
8031 newer language features for appropriately named files, e.g., Fortran 90
8032 features only for @file{.f90} files. On the other hand, some other
8033 compilers expect all source files to end in @file{.f} and require
8034 special flags to support other file name extensions. The
8035 @code{AC_FC_SRCEXT} macro deals with both of these issues.
8037 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
8038 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
8039 contain the dot). If any special compiler flags are needed for this, it
8040 stores them in the output variable @code{FCFLAGS_}@var{ext}. This
8041 extension and these flags are then used for all subsequent @code{FC} tests
8042 (until @code{AC_FC_SRCEXT} is called again).
8044 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8045 @file{.f90} extension in future tests, and it would set the
8046 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8047 to compile such files.
8049 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
8050 @code{FCFLAGS}, for two reasons based on the limitations of some
8051 compilers. First, only one @code{FCFLAGS_}@var{ext} can be used at a
8052 time, so files with different extensions must be compiled separately.
8053 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
8054 the source-code file name when compiling. So, continuing the example
8055 above, you might compile a @file{foo.f90} file in your makefile with the
8060 $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8063 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
8064 extension, it calls @var{action-if-success} (defaults to nothing). If
8065 it fails, and cannot find a way to make the @code{FC} compiler accept such
8066 files, it calls @var{action-if-failure} (defaults to exiting with an
8071 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8072 @acindex{FC_FREEFORM}
8074 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
8075 (@code{$FC}) allows free-format source code (as opposed to the older
8076 fixed-format style from Fortran 77). If necessary, it may add some
8077 additional flags to @code{FCFLAGS}.
8079 This macro is most important if you are using the default @file{.f}
8080 extension, since many compilers interpret this extension as indicating
8081 fixed-format source unless an additional flag is supplied. If you
8082 specify a different extension with @code{AC_FC_SRCEXT}, such as
8083 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
8084 succeeds without modifying @code{FCFLAGS}.
8086 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8087 calls @var{action-if-success} (defaults to nothing). If it fails, it
8088 calls @var{action-if-failure} (defaults to exiting with an error
8092 @node System Services
8093 @section System Services
8095 The following macros check for operating system services or capabilities.
8101 @cindex X Window System
8102 Try to locate the X Window System include files and libraries. If the
8103 user gave the command line options @option{--x-includes=@var{dir}} and
8104 @option{--x-libraries=@var{dir}}, use those directories.
8106 If either or both were not given, get the missing values by running
8107 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8108 environment variable) on a trivial @file{Imakefile} and examining the
8109 makefile that it produces. Setting @code{XMKMF} to @samp{false}
8110 disables this method.
8112 If this method fails to find the X Window System, @command{configure}
8113 looks for the files in several directories where they often reside.
8114 If either method is successful, set the shell variables
8115 @code{x_includes} and @code{x_libraries} to their locations, unless they
8116 are in directories the compiler searches by default.
8118 If both methods fail, or the user gave the command line option
8119 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8120 otherwise set it to the empty string.
8123 @anchor{AC_PATH_XTRA}
8124 @defmac AC_PATH_XTRA
8128 @ovindex X_EXTRA_LIBS
8130 @cvindex X_DISPLAY_MISSING
8131 An enhanced version of @code{AC_PATH_X}. It adds the C compiler flags
8132 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8133 to @code{X_LIBS}. Define @code{X_DISPLAY_MISSING} if X is not
8136 This macro also checks for special libraries that some systems need in
8137 order to compile X programs. It adds any that the system needs to
8138 output variable @code{X_EXTRA_LIBS}. And it checks for special X11R6
8139 libraries that need to be linked with before @option{-lX11}, and adds
8140 any found to the output variable @code{X_PRE_LIBS}.
8142 @c This is an incomplete kludge. Make a real way to do it.
8143 @c If you need to check for other X functions or libraries yourself, then
8144 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8145 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8148 @anchor{AC_SYS_INTERPRETER}
8149 @defmac AC_SYS_INTERPRETER
8150 @acindex{SYS_INTERPRETER}
8151 Check whether the system supports starting scripts with a line of the
8152 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8153 After running this macro, shell code in @file{configure.ac} can check
8154 the shell variable @code{interpval}; it is set to @samp{yes}
8155 if the system supports @samp{#!}, @samp{no} if not.
8158 @defmac AC_SYS_LARGEFILE
8159 @acindex{SYS_LARGEFILE}
8160 @cvindex _FILE_OFFSET_BITS
8161 @cvindex _LARGE_FILES
8163 @cindex Large file support
8165 Arrange for 64-bit file offsets, known as
8166 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8167 large-file support}. On some hosts, one must use special compiler
8168 options to build programs that can access large files. Append any such
8169 options to the output variable @code{CC}. Define
8170 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8172 Large-file support can be disabled by configuring with the
8173 @option{--disable-largefile} option.
8175 If you use this macro, check that your program works even when
8176 @code{off_t} is wider than @code{long int}, since this is common when
8177 large-file support is enabled. For example, it is not correct to print
8178 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8181 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8182 replace their C counterparts @code{fseek} and @code{ftell} that do not
8183 use @code{off_t}. Take care to use @code{AC_FUNC_FSEEKO} to make their
8184 prototypes available when using them and large-file support is
8188 @anchor{AC_SYS_LONG_FILE_NAMES}
8189 @defmac AC_SYS_LONG_FILE_NAMES
8190 @acindex{SYS_LONG_FILE_NAMES}
8191 @cvindex HAVE_LONG_FILE_NAMES
8192 If the system supports file names longer than 14 characters, define
8193 @code{HAVE_LONG_FILE_NAMES}.
8196 @defmac AC_SYS_POSIX_TERMIOS
8197 @acindex{SYS_POSIX_TERMIOS}
8198 @cindex Posix termios headers
8199 @cindex termios Posix headers
8200 @caindex sys_posix_termios
8201 Check to see if the Posix termios headers and functions are available on the
8202 system. If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8203 @samp{yes}. If not, set the variable to @samp{no}.
8206 @node Posix Variants
8207 @section Posix Variants
8209 The following macro makes it possible to use features of Posix that are
8210 extensions to C, as well as platform extensions not defined by Posix.
8212 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8213 @defmac AC_USE_SYSTEM_EXTENSIONS
8214 @acindex{USE_SYSTEM_EXTENSIONS}
8215 @cvindex _ALL_SOURCE
8216 @cvindex _GNU_SOURCE
8218 @cvindex _POSIX_1_SOURCE
8219 @cvindex _POSIX_PTHREAD_SEMANTICS
8220 @cvindex _POSIX_SOURCE
8221 @cvindex _TANDEM_SOURCE
8222 @cvindex __EXTENSIONS__
8223 This macro was introduced in Autoconf 2.60. If possible, enable
8224 extensions to C or Posix on hosts that normally disable the extensions,
8225 typically due to standards-conformance namespace issues. This should be
8226 called before any macros that run the C compiler. The following
8227 preprocessor macros are defined where appropriate:
8231 Enable extensions on GNU/Linux.
8232 @item __EXTENSIONS__
8233 Enable general extensions on Solaris.
8234 @item _POSIX_PTHREAD_SEMANTICS
8235 Enable threading extensions on Solaris.
8236 @item _TANDEM_SOURCE
8237 Enable extensions for the HP NonStop platform.
8239 Enable extensions for AIX 3, and for Interix.
8241 Enable Posix functions for Minix.
8242 @item _POSIX_1_SOURCE
8243 Enable additional Posix functions for Minix.
8245 Identify Minix platform. This particular preprocessor macro is
8246 obsolescent, and may be removed in a future release of Autoconf.
8251 @node Erlang Libraries
8252 @section Erlang Libraries
8253 @cindex Erlang, Library, checking
8255 The following macros check for an installation of Erlang/OTP, and for the
8256 presence of certain Erlang libraries. All those macros require the
8257 configuration of an Erlang interpreter and an Erlang compiler
8258 (@pxref{Erlang Compiler and Interpreter}).
8260 @defmac AC_ERLANG_SUBST_ERTS_VER
8261 @acindex{ERLANG_SUBST_ERTS_VER}
8262 @ovindex ERLANG_ERTS_VER
8263 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8264 Erlang runtime system (as returned by Erlang's
8265 @code{erlang:system_info(version)} function). The result of this test
8266 is cached if caching is enabled when running @command{configure}. The
8267 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8268 for features of specific ERTS versions, but to be used for substituting
8269 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8270 files), as shown below.
8273 @defmac AC_ERLANG_SUBST_ROOT_DIR
8274 @acindex{ERLANG_SUBST_ROOT_DIR}
8275 @ovindex ERLANG_ROOT_DIR
8276 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8277 directory in which Erlang/OTP is installed (as returned by Erlang's
8278 @code{code:root_dir/0} function). The result of this test is cached if
8279 caching is enabled when running @command{configure}.
8282 @defmac AC_ERLANG_SUBST_LIB_DIR
8283 @acindex{ERLANG_SUBST_LIB_DIR}
8284 @ovindex ERLANG_LIB_DIR
8285 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8286 directory of Erlang/OTP (as returned by Erlang's
8287 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8288 Erlang/OTP library. The result of this test is cached if caching is enabled
8289 when running @command{configure}.
8292 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8293 @ovar{action-if-not-found})
8294 @acindex{ERLANG_CHECK_LIB}
8295 @ovindex ERLANG_LIB_DIR_@var{library}
8296 @ovindex ERLANG_LIB_VER_@var{library}
8297 Test whether the Erlang/OTP library @var{library} is installed by
8298 calling Erlang's @code{code:lib_dir/1} function. The result of this
8299 test is cached if caching is enabled when running @command{configure}.
8300 @var{action-if-found} is a list of shell commands to run if the library
8301 is installed; @var{action-if-not-found} is a list of shell commands to
8302 run if it is not. Additionally, if the library is installed, the output
8303 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8304 library installation directory, and the output variable
8305 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8306 part of the subdirectory name, if it is in the standard form
8307 (@code{@var{library}-@var{version}}). If the directory name does not
8308 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8309 empty string. If the library is not installed,
8310 @samp{ERLANG_LIB_DIR_@var{library}} and
8311 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}. For
8312 example, to check if library @code{stdlib} is installed:
8315 AC_ERLANG_CHECK_LIB([stdlib],
8316 [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8317 echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8318 [AC_MSG_ERROR([stdlib was not found!])])
8321 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8322 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8323 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8324 testing for features of specific versions of libraries or of the Erlang
8325 runtime system. Those variables are intended to be substituted in
8326 Erlang release resource files (@code{.rel} files). For instance, to
8327 generate a @file{example.rel} file for an application depending on the
8328 @code{stdlib} library, @file{configure.ac} could contain:
8331 AC_ERLANG_SUBST_ERTS_VER
8332 AC_ERLANG_CHECK_LIB([stdlib],
8334 [AC_MSG_ERROR([stdlib was not found!])])
8335 AC_CONFIG_FILES([example.rel])
8339 The @file{example.rel.in} file used to generate @file{example.rel}
8344 @{"@@PACKAGE@@", "@@VERSION@@"@},
8345 @{erts, "@@ERLANG_ERTS_VER@@"@},
8346 [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8347 @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8351 In addition to the above macros, which test installed Erlang libraries, the
8352 following macros determine the paths to the directories into which newly built
8353 Erlang libraries are to be installed:
8355 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8356 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8357 @ovindex ERLANG_INSTALL_LIB_DIR
8359 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8360 which every built Erlang library should be installed in a separate
8362 If this variable is not set in the environment when @command{configure} runs,
8363 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
8364 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
8367 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8368 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8369 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8371 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8372 directory into which the built Erlang library @var{library} version
8373 @var{version} should be installed. If this variable is not set in the
8374 environment when @command{configure} runs, its default value is
8375 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8376 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8377 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8384 @c ========================================================= Writing Tests
8387 @chapter Writing Tests
8389 If the existing feature tests don't do something you need, you have to
8390 write new ones. These macros are the building blocks. They provide
8391 ways for other macros to check whether various kinds of features are
8392 available and report the results.
8394 This chapter contains some suggestions and some of the reasons why the
8395 existing tests are written the way they are. You can also learn a lot
8396 about how to write Autoconf tests by looking at the existing ones. If
8397 something goes wrong in one or more of the Autoconf tests, this
8398 information can help you understand the assumptions behind them, which
8399 might help you figure out how to best solve the problem.
8401 These macros check the output of the compiler system of the current
8402 language (@pxref{Language Choice}). They do not cache the results of
8403 their tests for future use (@pxref{Caching Results}), because they don't
8404 know enough about the information they are checking for to generate a
8405 cache variable name. They also do not print any messages, for the same
8406 reason. The checks for particular kinds of features call these macros
8407 and do cache their results and print messages about what they're
8410 When you write a feature test that could be applicable to more than one
8411 software package, the best thing to do is encapsulate it in a new macro.
8412 @xref{Writing Autoconf Macros}, for how to do that.
8415 * Language Choice:: Selecting which language to use for testing
8416 * Writing Test Programs:: Forging source files for compilers
8417 * Running the Preprocessor:: Detecting preprocessor symbols
8418 * Running the Compiler:: Detecting language or header features
8419 * Running the Linker:: Detecting library features
8420 * Runtime:: Testing for runtime features
8421 * Systemology:: A zoology of operating systems
8422 * Multiple Cases:: Tests for several possible values
8425 @node Language Choice
8426 @section Language Choice
8429 Autoconf-generated @command{configure} scripts check for the C compiler and
8430 its features by default. Packages that use other programming languages
8431 (maybe more than one, e.g., C and C++) need to test features of the
8432 compilers for the respective languages. The following macros determine
8433 which programming language is used in the subsequent tests in
8434 @file{configure.ac}.
8437 @defmac AC_LANG (@var{language})
8438 Do compilation tests using the compiler, preprocessor, and file
8439 extensions for the specified @var{language}.
8441 Supported languages are:
8445 Do compilation tests using @code{CC} and @code{CPP} and use extension
8446 @file{.c} for test programs. Use compilation flags: @code{CPPFLAGS} with
8447 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8450 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8451 extension @file{.C} for test programs. Use compilation flags:
8452 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8453 @code{CXXFLAGS} with @code{CXX}.
8456 Do compilation tests using @code{F77} and use extension @file{.f} for
8457 test programs. Use compilation flags: @code{FFLAGS}.
8460 Do compilation tests using @code{FC} and use extension @file{.f} (or
8461 whatever has been set by @code{AC_FC_SRCEXT}) for test programs. Use
8462 compilation flags: @code{FCFLAGS}.
8468 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8469 @file{.erl} for test Erlang modules. Use compilation flags: @code{ERLCFLAGS}.
8472 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8473 extension @file{.m} for test programs. Use compilation flags:
8474 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8475 @code{OBJCFLAGS} with @code{OBJC}.
8478 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8479 extension @file{.mm} for test programs. Use compilation flags:
8480 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8481 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8485 @anchor{AC_LANG_PUSH}
8486 @defmac AC_LANG_PUSH (@var{language})
8488 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8489 then select the @var{language}. Use this macro and @code{AC_LANG_POP}
8490 in macros that need to temporarily switch to a particular language.
8493 @defmac AC_LANG_POP (@ovar{language})
8495 Select the language that is saved on the top of the stack, as set by
8496 @code{AC_LANG_PUSH}, and remove it from the stack.
8498 If given, @var{language} specifies the language we just @emph{quit}. It
8499 is a good idea to specify it when it's known (which should be the
8500 case@dots{}), since Autoconf detects inconsistencies.
8503 AC_LANG_PUSH([Fortran 77])
8504 # Perform some tests on Fortran 77.
8506 AC_LANG_POP([Fortran 77])
8510 @defmac AC_LANG_ASSERT (@var{language})
8511 @acindex{LANG_ASSERT} Check statically that the current language is
8512 @var{language}. You should use this in your language specific macros
8513 to avoid that they be called with an inappropriate language.
8515 This macro runs only at @command{autoconf} time, and incurs no cost at
8516 @command{configure} time. Sadly enough and because Autoconf is a two
8517 layer language @footnote{Because M4 is not aware of Sh code,
8518 especially conditionals, some optimizations that look nice statically
8519 may produce incorrect results at runtime.}, the macros
8520 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8521 therefore as much as possible you ought to avoid using them to wrap
8522 your code, rather, require from the user to run the macro with a
8523 correct current language, and check it with @code{AC_LANG_ASSERT}.
8524 And anyway, that may help the user understand she is running a Fortran
8525 macro while expecting a result about her Fortran 77 compiler@enddots{}
8529 @defmac AC_REQUIRE_CPP
8530 @acindex{REQUIRE_CPP}
8531 Ensure that whichever preprocessor would currently be used for tests has
8532 been found. Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8533 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8534 depending on which language is current.
8538 @node Writing Test Programs
8539 @section Writing Test Programs
8541 Autoconf tests follow a common scheme: feed some program with some
8542 input, and most of the time, feed a compiler with some source file.
8543 This section is dedicated to these source samples.
8546 * Guidelines:: General rules for writing test programs
8547 * Test Functions:: Avoiding pitfalls in test programs
8548 * Generating Sources:: Source program boilerplate
8552 @subsection Guidelines for Test Programs
8554 The most important rule to follow when writing testing samples is:
8556 @center @emph{Look for realism.}
8558 This motto means that testing samples must be written with the same
8559 strictness as real programs are written. In particular, you should
8560 avoid ``shortcuts'' and simplifications.
8562 Don't just play with the preprocessor if you want to prepare a
8563 compilation. For instance, using @command{cpp} to check whether a header is
8564 functional might let your @command{configure} accept a header which
8565 causes some @emph{compiler} error. Do not hesitate to check a header with
8566 other headers included before, especially required headers.
8568 Make sure the symbols you use are properly defined, i.e., refrain from
8569 simply declaring a function yourself instead of including the proper
8572 Test programs should not write to standard output. They
8573 should exit with status 0 if the test succeeds, and with status 1
8574 otherwise, so that success
8575 can be distinguished easily from a core dump or other failure;
8576 segmentation violations and other failures produce a nonzero exit
8577 status. Unless you arrange for @code{exit} to be declared, test
8578 programs should @code{return}, not @code{exit}, from @code{main},
8579 because on many systems @code{exit} is not declared by default.
8581 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8582 preprocessor macros defined by tests that have already run. For
8583 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8584 @file{configure.ac} you can have a test program that includes
8585 @file{stdbool.h} conditionally:
8589 #ifdef HAVE_STDBOOL_H
8590 # include <stdbool.h>
8595 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8596 work with any standard C compiler. Some developers prefer @code{#if}
8597 because it is easier to read, while others prefer @code{#ifdef} because
8598 it avoids diagnostics with picky compilers like GCC with the
8599 @option{-Wundef} option.
8601 If a test program needs to use or create a data file, give it a name
8602 that starts with @file{conftest}, such as @file{conftest.data}. The
8603 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8604 after running test programs and if the script is interrupted.
8606 @node Test Functions
8607 @subsection Test Functions
8609 These days it's safe to assume support for function prototypes
8610 (introduced in C89).
8612 Functions that test programs declare should also be conditionalized for
8613 C++, which requires @samp{extern "C"} prototypes. Make sure to not
8614 include any header files containing clashing prototypes.
8620 void *valloc (size_t);
8623 If a test program calls a function with invalid parameters (just to see
8624 whether it exists), organize the program to ensure that it never invokes
8625 that function. You can do this by calling it in another function that is
8626 never invoked. You can't do it by putting it after a call to
8627 @code{exit}, because GCC version 2 knows that @code{exit}
8629 and optimizes out any code that follows it in the same block.
8631 If you include any header files, be sure to call the functions
8632 relevant to them with the correct number of arguments, even if they are
8633 just 0, to avoid compilation errors due to prototypes. GCC
8635 has internal prototypes for several functions that it automatically
8636 inlines; for example, @code{memcpy}. To avoid errors when checking for
8637 them, either pass them the correct number of arguments or redeclare them
8638 with a different return type (such as @code{char}).
8641 @node Generating Sources
8642 @subsection Generating Sources
8644 Autoconf provides a set of macros that can be used to generate test
8645 source files. They are written to be language generic, i.e., they
8646 actually depend on the current language (@pxref{Language Choice}) to
8647 ``format'' the output properly.
8650 @defmac AC_LANG_CONFTEST (@var{source})
8651 @acindex{LANG_CONFTEST}
8652 Save the @var{source} text in the current test source file:
8653 @file{conftest.@var{extension}} where the @var{extension} depends on the
8654 current language. As of Autoconf 2.63b, the source file also contains
8655 the results of all of the @code{AC_DEFINE} performed so far.
8657 Note that the @var{source} is evaluated exactly once, like regular
8658 Autoconf macro arguments, and therefore (i) you may pass a macro
8659 invocation, (ii) if not, be sure to double quote if needed.
8662 @defmac AC_LANG_SOURCE (@var{source})
8663 @acindex{LANG_SOURCE}
8664 Expands into the @var{source}, with the definition of
8665 all the @code{AC_DEFINE} performed so far.
8668 For instance executing (observe the double quotation!):
8671 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8672 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8673 [Greetings string.])
8676 [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8677 gcc -E -dD -o - conftest.c
8687 #define PACKAGE_NAME "Hello"
8688 #define PACKAGE_TARNAME "hello"
8689 #define PACKAGE_VERSION "1.0"
8690 #define PACKAGE_STRING "Hello 1.0"
8691 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8692 #define HELLO_WORLD "Hello, World\n"
8694 const char hw[] = "Hello, World\n";
8697 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8698 are not automatically translated into constants in the source code by this
8701 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8702 @acindex{LANG_PROGRAM}
8703 Expands into a source file which consists of the @var{prologue}, and
8704 then @var{body} as body of the main function (e.g., @code{main} in
8705 C). Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8712 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8713 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8714 [Greetings string.])
8716 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8717 [[fputs (hw, stdout);]])])
8718 gcc -E -dD -o - conftest.c
8728 #define PACKAGE_NAME "Hello"
8729 #define PACKAGE_TARNAME "hello"
8730 #define PACKAGE_VERSION "1.0"
8731 #define PACKAGE_STRING "Hello 1.0"
8732 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8733 #define HELLO_WORLD "Hello, World\n"
8735 const char hw[] = "Hello, World\n";
8745 In Erlang tests, the created source file is that of an Erlang module called
8746 @code{conftest} (@file{conftest.erl}). This module defines and exports
8748 one @code{start/0} function, which is called to perform the test. The
8749 @var{prologue} is optional code that is inserted between the module header and
8750 the @code{start/0} function definition. @var{body} is the body of the
8751 @code{start/0} function without the final period (@pxref{Runtime}, about
8752 constraints on this function's behavior).
8757 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8760 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8761 [[io:format("~s~n", [?HELLO_WORLD])]])])
8771 -define(HELLO_WORLD, "Hello, world!").
8773 io:format("~s~n", [?HELLO_WORLD])
8777 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8779 Expands into a source file which consists of the @var{prologue}, and
8780 then a call to the @var{function} as body of the main function (e.g.,
8781 @code{main} in C). Since it uses @code{AC_LANG_PROGRAM}, the feature
8782 of the latter are available.
8784 This function will probably be replaced in the future by a version
8785 which would enable specifying the arguments. The use of this macro is
8786 not encouraged, as it violates strongly the typing system.
8788 This macro cannot be used for Erlang tests.
8791 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8792 @acindex{LANG_FUNC_LINK_TRY}
8793 Expands into a source file which uses the @var{function} in the body of
8794 the main function (e.g., @code{main} in C). Since it uses
8795 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8797 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8798 It is considered to be severely broken, and in the future will be
8799 removed in favor of actual function calls (with properly typed
8802 This macro cannot be used for Erlang tests.
8805 @node Running the Preprocessor
8806 @section Running the Preprocessor
8808 Sometimes one might need to run the preprocessor on some source file.
8809 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8810 your project, not merely run the preprocessor on it; therefore you
8811 certainly want to run the compiler, not the preprocessor. Resist the
8812 temptation of following the easiest path.
8814 Nevertheless, if you need to run the preprocessor, then use
8815 @code{AC_PREPROC_IFELSE}.
8817 The macros described in this section cannot be used for tests in Erlang or
8818 Fortran, since those languages require no preprocessor.
8820 @anchor{AC_PREPROC_IFELSE}
8821 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8822 @ovar{action-if-false})
8823 @acindex{PREPROC_IFELSE}
8824 Run the preprocessor of the current language (@pxref{Language Choice})
8825 on the @var{input}, run the shell commands @var{action-if-true} on
8826 success, @var{action-if-false} otherwise. The @var{input} can be made
8827 by @code{AC_LANG_PROGRAM} and friends.
8829 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8830 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8833 It is customary to report unexpected failures with
8834 @code{AC_MSG_FAILURE}.
8840 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8841 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8842 [Greetings string.])
8844 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8845 [[fputs (hw, stdout);]])],
8846 [AC_MSG_RESULT([OK])],
8847 [AC_MSG_FAILURE([unexpected preprocessor failure])])
8854 checking for gcc... gcc
8855 checking for C compiler default output file name... a.out
8856 checking whether the C compiler works... yes
8857 checking whether we are cross compiling... no
8858 checking for suffix of executables...
8859 checking for suffix of object files... o
8860 checking whether we are using the GNU C compiler... yes
8861 checking whether gcc accepts -g... yes
8862 checking for gcc option to accept ISO C89... none needed
8863 checking how to run the C preprocessor... gcc -E
8869 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8870 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8871 it impossible to use it to elaborate sources. You are encouraged to
8872 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8873 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8874 to run the @emph{preprocessor} and not the compiler?
8876 @anchor{AC_EGREP_HEADER}
8877 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8878 @var{action-if-found}, @ovar{action-if-not-found})
8879 @acindex{EGREP_HEADER}
8880 If the output of running the preprocessor on the system header file
8881 @var{header-file} matches the extended regular expression
8882 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8883 execute @var{action-if-not-found}.
8886 @anchor{AC_EGREP_CPP}
8887 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8888 @ovar{action-if-found}, @ovar{action-if-not-found})
8890 @var{program} is the text of a C or C++ program, on which shell
8891 variable, back quote, and backslash substitutions are performed. If the
8892 output of running the preprocessor on @var{program} matches the
8893 extended regular expression @var{pattern}, execute shell commands
8894 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8899 @node Running the Compiler
8900 @section Running the Compiler
8902 To check for a syntax feature of the current language's (@pxref{Language
8903 Choice}) compiler, such as whether it recognizes a certain keyword, or
8904 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8905 to compile a small program that uses that feature.
8907 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8908 @ovar{action-if-false})
8909 @acindex{COMPILE_IFELSE}
8910 Run the compiler and compilation flags of the current language
8911 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8912 @var{action-if-true} on success, @var{action-if-false} otherwise. The
8913 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8915 It is customary to report unexpected failures with
8916 @code{AC_MSG_FAILURE}. This macro does not try to link; use
8917 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8918 Linker}). If needed, @var{action-if-true} can further access the
8919 just-linked object file @file{conftest.$ac_object}.
8921 This macro uses @code{AC_REQUIRE} for the compiler associated with the
8922 current language, which means that if the compiler has not yet been
8923 determined, the compiler determination will be made prior to the body of
8924 the outermust @code{AC_DEFUN} macro that triggered this macro to
8925 expand (@pxref{Expanded Before Required}).
8929 For tests in Erlang, the @var{input} must be the source code of a module named
8930 @code{conftest}. @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8931 file that can be interpreted by the Erlang virtual machine (@code{ERL}). It is
8932 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8933 to ensure that the Erlang module has the right name.
8935 @node Running the Linker
8936 @section Running the Linker
8938 To check for a library, a function, or a global variable, Autoconf
8939 @command{configure} scripts try to compile and link a small program that
8940 uses it. This is unlike Metaconfig, which by default uses @code{nm} or
8941 @code{ar} on the C library to try to figure out which functions are
8942 available. Trying to link with the function is usually a more reliable
8943 approach because it avoids dealing with the variations in the options
8944 and output formats of @code{nm} and @code{ar} and in the location of the
8945 standard libraries. It also allows configuring for cross-compilation or
8946 checking a function's runtime behavior if needed. On the other hand,
8947 it can be slower than scanning the libraries once, but accuracy is more
8948 important than speed.
8950 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8951 functions and global variables. It is also used by @code{AC_CHECK_LIB}
8952 to check for libraries (@pxref{Libraries}), by adding the library being
8953 checked for to @code{LIBS} temporarily and trying to link a small
8956 @anchor{AC_LINK_IFELSE}
8957 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8958 @ovar{action-if-false})
8959 @acindex{LINK_IFELSE}
8960 Run the compiler (and compilation flags) and the linker of the current
8961 language (@pxref{Language Choice}) on the @var{input}, run the shell
8962 commands @var{action-if-true} on success, @var{action-if-false}
8963 otherwise. The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8964 friends. If needed, @var{action-if-true} can further access the
8965 just-linked program file @file{conftest$ac_exeext}.
8967 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8968 current compilation flags.
8970 It is customary to report unexpected failures with
8971 @code{AC_MSG_FAILURE}. This macro does not try to execute the program;
8972 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8975 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8976 programs are interpreted and do not require linking.
8981 @section Checking Runtime Behavior
8983 Sometimes you need to find out how a system performs at runtime, such
8984 as whether a given function has a certain capability or bug. If you
8985 can, make such checks when your program runs instead of when it is
8986 configured. You can check for things like the machine's endianness when
8987 your program initializes itself.
8989 If you really need to test for a runtime behavior while configuring,
8990 you can write a test program to determine the result, and compile and
8991 run it using @code{AC_RUN_IFELSE}. Avoid running test programs if
8992 possible, because this prevents people from configuring your package for
8995 @anchor{AC_RUN_IFELSE}
8996 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8997 @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8998 @acindex{RUN_IFELSE}
8999 If @var{program} compiles and links successfully and returns an exit
9000 status of 0 when executed, run shell commands @var{action-if-true}.
9001 Otherwise, run shell commands @var{action-if-false}.
9003 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9004 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9005 compilation flags of the current language (@pxref{Language Choice}).
9006 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9007 for further testing.
9009 If the compiler being used does not produce executables that run on the
9010 system where @command{configure} is being run, then the test program is
9011 not run. If the optional shell commands @var{action-if-cross-compiling}
9012 are given, they are run instead. Otherwise, @command{configure} prints
9013 an error message and exits.
9015 In the @var{action-if-false} section, the failing exit status is
9016 available in the shell variable @samp{$?}. This exit status might be
9017 that of a failed compilation, or it might be that of a failed program
9020 It is customary to report unexpected failures with
9021 @code{AC_MSG_FAILURE}.
9024 Try to provide a pessimistic default value to use when cross-compiling
9025 makes runtime tests impossible. You do this by passing the optional
9026 last argument to @code{AC_RUN_IFELSE}. @command{autoconf} prints a
9027 warning message when creating @command{configure} each time it
9028 encounters a call to @code{AC_RUN_IFELSE} with no
9029 @var{action-if-cross-compiling} argument given. You may ignore the
9030 warning, though users cannot configure your package for
9031 cross-compiling. A few of the macros distributed with Autoconf produce
9032 this warning message.
9034 To configure for cross-compiling you can also choose a value for those
9035 parameters based on the canonical system name (@pxref{Manual
9036 Configuration}). Alternatively, set up a test results cache file with
9037 the correct values for the host system (@pxref{Caching Results}).
9039 @ovindex cross_compiling
9040 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9041 in other macros, including a few of the ones that come with Autoconf,
9042 you can test whether the shell variable @code{cross_compiling} is set to
9043 @samp{yes}, and then use an alternate method to get the results instead
9044 of calling the macros.
9046 It is also permissible to temporarily assign to @code{cross_compiling}
9047 in order to force tests to behave as though they are in a
9048 cross-compilation environment, particularly since this provides a way to
9049 test your @var{action-if-cross-compiling} even when you are not using a
9053 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9054 # to use the slow link-only method
9055 save_cross_compiling=$cross_compiling
9057 AC_COMPUTE_INT([@dots{}])
9058 cross_compiling=$save_cross_compiling
9061 A C or C++ runtime test should be portable.
9062 @xref{Portable C and C++}.
9064 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9065 function: the given status code is used to determine the success of the test
9066 (status is @code{0}) or its failure (status is different than @code{0}), as
9067 explained above. It must be noted that data output through the standard output
9068 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9069 Therefore, if a test must output configuration information, it is recommended
9070 to create and to output data into the temporary file named @file{conftest.out},
9071 using the functions of module @code{file}. The @code{conftest.out} file is
9072 automatically deleted by the @code{AC_RUN_IFELSE} macro. For instance, a
9073 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9077 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9081 [AC_LANG_PROGRAM([], [dnl
9082 file:write_file("conftest.out", code:lib_dir()),
9084 [echo "code:lib_dir() returned: `cat conftest.out`"],
9085 [AC_MSG_FAILURE([test Erlang program execution failed])])
9090 @section Systemology
9093 This section aims at presenting some systems and pointers to
9094 documentation. It may help you addressing particular problems reported
9097 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9098 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9101 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9102 contains a table correlating the features of various Posix-conforming
9103 systems. @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9104 simplified diagram of how many Unix systems were derived from each
9107 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9108 provides some variants of traditional implementations of Unix utilities.
9113 Darwin is also known as Mac OS X@. Beware that the file system @emph{can} be
9114 case-preserving, but case insensitive. This can cause nasty problems,
9115 since for instance the installation attempt for a package having an
9116 @file{INSTALL} file can result in @samp{make install} report that
9117 nothing was to be done!
9119 That's all dependent on whether the file system is a UFS (case
9120 sensitive) or HFS+ (case preserving). By default Apple wants you to
9121 install the OS on HFS+. Unfortunately, there are some pieces of
9122 software which really need to be built on UFS@. We may want to rebuild
9123 Darwin to have both UFS and HFS+ available (and put the /local/build
9128 @c FIXME: Please, if you feel like writing something more precise,
9129 @c it'd be great. In particular, I can't understand the difference with
9131 QNX is a realtime operating system running on Intel architecture
9132 meant to be scalable from the small embedded systems to the hundred
9133 processor super-computer. It claims to be Posix certified. More
9134 information is available on the
9135 @uref{http://@/www.qnx.com/, QNX home page}.
9139 @uref{http://@/h30097.www3.hp.com/@/docs/,
9140 Documentation of several versions of Tru64} is available in different
9143 @item Unix version 7
9144 @cindex Unix version 7
9146 Officially this was called the ``Seventh Edition'' of ``the UNIX
9147 time-sharing system'' but we use the more-common name ``Unix version 7''.
9148 Documentation is available in the
9149 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9150 Previous versions of Unix are called ``Unix version 6'', etc., but
9151 they were not as widely used.
9155 @node Multiple Cases
9156 @section Multiple Cases
9158 Some operations are accomplished in several possible ways, depending on
9159 the OS variant. Checking for them essentially requires a ``case
9160 statement''. Autoconf does not directly provide one; however, it is
9161 easy to simulate by using a shell variable to keep track of whether a
9162 way to perform the operation has been found yet.
9164 Here is an example that uses the shell variable @code{fstype} to keep
9165 track of whether the remaining cases need to be checked. Note that
9166 since the value of @code{fstype} is under our control, we don't have to
9167 use the longer @samp{test "x$fstype" = xno}.
9171 AC_MSG_CHECKING([how to get file system type])
9173 # The order of these tests is important.
9174 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9175 #include <sys/fstyp.h>]])],
9176 [AC_DEFINE([FSTYPE_STATVFS], [1],
9177 [Define if statvfs exists.])
9179 if test $fstype = no; then
9180 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9181 #include <sys/fstyp.h>]])],
9182 [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9183 [Define if USG statfs.])
9186 if test $fstype = no; then
9187 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9188 #include <sys/vmount.h>]])]),
9189 [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9190 [Define if AIX statfs.])
9193 # (more cases omitted here)
9194 AC_MSG_RESULT([$fstype])
9198 @c ====================================================== Results of Tests.
9201 @chapter Results of Tests
9203 Once @command{configure} has determined whether a feature exists, what can
9204 it do to record that information? There are four sorts of things it can
9205 do: define a C preprocessor symbol, set a variable in the output files,
9206 save the result in a cache file for future @command{configure} runs, and
9207 print a message letting the user know the result of the test.
9210 * Defining Symbols:: Defining C preprocessor symbols
9211 * Setting Output Variables:: Replacing variables in output files
9212 * Special Chars in Variables:: Characters to beware of in variables
9213 * Caching Results:: Speeding up subsequent @command{configure} runs
9214 * Printing Messages:: Notifying @command{configure} users
9217 @node Defining Symbols
9218 @section Defining C Preprocessor Symbols
9220 A common action to take in response to a feature test is to define a C
9221 preprocessor symbol indicating the results of the test. That is done by
9222 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9224 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9225 into the output variable @code{DEFS}, which contains an option
9226 @option{-D@var{symbol}=@var{value}} for each symbol defined. Unlike in
9227 Autoconf version 1, there is no variable @code{DEFS} defined while
9228 @command{configure} is running. To check whether Autoconf macros have
9229 already defined a certain C preprocessor symbol, test the value of the
9230 appropriate cache variable, as in this example:
9233 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9234 [Define if vprintf exists.])])
9235 if test "x$ac_cv_func_vprintf" != xyes; then
9236 AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9237 [Define if _doprnt exists.])])
9241 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9242 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9243 correct values into @code{#define} statements in a template file.
9244 @xref{Configuration Headers}, for more information about this kind of
9247 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9248 @defmacx AC_DEFINE (@var{variable})
9249 @cvindex @var{variable}
9251 Define @var{variable} to @var{value} (verbatim), by defining a C
9252 preprocessor macro for @var{variable}. @var{variable} should be a C
9253 identifier, optionally suffixed by a parenthesized argument list to
9254 define a C preprocessor macro with arguments. The macro argument list,
9255 if present, should be a comma-separated list of C identifiers, possibly
9256 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9257 @var{variable} should not contain comments, white space, trigraphs,
9258 backslash-newlines, universal character names, or non-ASCII
9261 @var{value} may contain backslash-escaped newlines, which will be
9262 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9263 via @code{@@DEFS@@} (with no effect on the compilation, since the
9264 preprocessor sees only one line in the first place). @var{value} should
9265 not contain raw newlines. If you are not using
9266 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9267 characters, as @command{make} tends to eat them. To use a shell
9268 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9270 @var{description} is only useful if you are using
9271 @code{AC_CONFIG_HEADERS}. In this case, @var{description} is put into
9272 the generated @file{config.h.in} as the comment before the macro define.
9273 The following example defines the C preprocessor variable
9274 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9277 AC_DEFINE([EQUATION], ["$a > $b"],
9281 If neither @var{value} nor @var{description} are given, then
9282 @var{value} defaults to 1 instead of to the empty string. This is for
9283 backwards compatibility with older versions of Autoconf, but this usage
9284 is obsolescent and may be withdrawn in future versions of Autoconf.
9286 If the @var{variable} is a literal string, it is passed to
9287 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9289 If multiple @code{AC_DEFINE} statements are executed for the same
9290 @var{variable} name (not counting any parenthesized argument list),
9294 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9295 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9296 @acindex{DEFINE_UNQUOTED}
9297 @cvindex @var{variable}
9298 Like @code{AC_DEFINE}, but three shell expansions are
9299 performed---once---on @var{variable} and @var{value}: variable expansion
9300 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9301 (@samp{\}), as if in an unquoted here-document. Single and double quote
9302 characters in the value have no
9303 special meaning. Use this macro instead of @code{AC_DEFINE} when
9304 @var{variable} or @var{value} is a shell variable. Examples:
9307 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9308 [Configuration machine file.])
9309 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9310 [getgroups return type.])
9311 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9312 [Translated header name.])
9316 Due to a syntactical bizarreness of the Bourne shell, do not use
9317 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9318 calls from other macro calls or shell code; that can cause syntax errors
9319 in the resulting @command{configure} script. Use either blanks or
9320 newlines. That is, do this:
9323 AC_CHECK_HEADER([elf.h],
9324 [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9331 AC_CHECK_HEADER([elf.h],
9332 [AC_DEFINE([SVR4], [1], [System V Release 4])
9333 LIBS="-lelf $LIBS"])
9340 AC_CHECK_HEADER([elf.h],
9341 [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9344 @node Setting Output Variables
9345 @section Setting Output Variables
9346 @cindex Output variables
9348 Another way to record the results of tests is to set @dfn{output
9349 variables}, which are shell variables whose values are substituted into
9350 files that @command{configure} outputs. The two macros below create new
9351 output variables. @xref{Preset Output Variables}, for a list of output
9352 variables that are always available.
9354 @defmac AC_SUBST (@var{variable}, @ovar{value})
9356 Create an output variable from a shell variable. Make @code{AC_OUTPUT}
9357 substitute the variable @var{variable} into output files (typically one
9358 or more makefiles). This means that @code{AC_OUTPUT}
9359 replaces instances of @samp{@@@var{variable}@@} in input files with the
9360 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9361 is called. The value can contain any non-@code{NUL} character, including
9362 newline. If you are using Automake 1.11 or newer, for newlines in values
9363 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9364 @command{automake} from adding a line @code{@var{variable} =
9365 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9366 Automake, automake, Other things Automake recognizes}).
9368 Variable occurrences should not overlap: e.g., an input file should
9369 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9371 The substituted value is not rescanned for more output variables;
9372 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9373 literally into the output file. (The algorithm uses the special marker
9374 @code{|#_!!_#|} internally, so neither the substituted value nor the
9375 output file may contain @code{|#_!!_#|}.)
9377 If @var{value} is given, in addition assign it to @var{variable}.
9379 The string @var{variable} is passed to @code{m4_pattern_allow}
9380 (@pxref{Forbidden Patterns}).
9383 @defmac AC_SUBST_FILE (@var{variable})
9384 @acindex{SUBST_FILE}
9385 Another way to create an output variable from a shell variable. Make
9386 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9387 named by shell variable @var{variable} into output files. This means
9388 that @code{AC_OUTPUT} replaces instances of
9389 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9390 with the contents of the file that the shell variable @var{variable}
9391 names when @code{AC_OUTPUT} is called. Set the variable to
9392 @file{/dev/null} for cases that do not have a file to insert.
9393 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9394 line by itself, optionally surrounded by spaces and tabs. The
9395 substitution replaces the whole line, including the spaces, tabs, and
9396 the terminating newline.
9398 This macro is useful for inserting makefile fragments containing
9399 special dependencies or other @command{make} directives for particular host
9400 or target types into makefiles. For example, @file{configure.ac}
9404 AC_SUBST_FILE([host_frag])
9405 host_frag=$srcdir/conf/sun4.mh
9409 and then a @file{Makefile.in} could contain:
9415 The string @var{variable} is passed to @code{m4_pattern_allow}
9416 (@pxref{Forbidden Patterns}).
9419 @cindex Precious Variable
9420 @cindex Variable, Precious
9421 Running @command{configure} in varying environments can be extremely
9422 dangerous. If for instance the user runs @samp{CC=bizarre-cc
9423 ./configure}, then the cache, @file{config.h}, and many other output
9424 files depend upon @command{bizarre-cc} being the C compiler. If
9425 for some reason the user runs @command{./configure} again, or if it is
9426 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9427 and @pxref{config.status Invocation}), then the configuration can be
9428 inconsistent, composed of results depending upon two different
9431 Environment variables that affect this situation, such as @samp{CC}
9432 above, are called @dfn{precious variables}, and can be declared as such
9433 by @code{AC_ARG_VAR}.
9435 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9437 Declare @var{variable} is a precious variable, and include its
9438 @var{description} in the variable section of @samp{./configure --help}.
9440 Being precious means that
9443 @var{variable} is substituted via @code{AC_SUBST}.
9446 The value of @var{variable} when @command{configure} was launched is
9447 saved in the cache, including if it was not specified on the command
9448 line but via the environment. Indeed, while @command{configure} can
9449 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9450 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9451 which, unfortunately, is what most users do.
9453 We emphasize that it is the @emph{initial} value of @var{variable} which
9454 is saved, not that found during the execution of @command{configure}.
9455 Indeed, specifying @samp{./configure FOO=foo} and letting
9456 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9460 @var{variable} is checked for consistency between two
9461 @command{configure} runs. For instance:
9464 $ @kbd{./configure --silent --config-cache}
9465 $ @kbd{CC=cc ./configure --silent --config-cache}
9466 configure: error: `CC' was not set in the previous run
9467 configure: error: changes in the environment can compromise \
9469 configure: error: run `make distclean' and/or \
9470 `rm config.cache' and start over
9474 and similarly if the variable is unset, or if its content is changed.
9475 If the content has white space changes only, then the error is degraded
9476 to a warning only, but the old value is reused.
9479 @var{variable} is kept during automatic reconfiguration
9480 (@pxref{config.status Invocation}) as if it had been passed as a command
9481 line argument, including when no cache is used:
9484 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9485 $ @kbd{./config.status --recheck}
9486 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9487 CC=/usr/bin/cc --no-create --no-recursion
9492 @node Special Chars in Variables
9493 @section Special Characters in Output Variables
9494 @cindex Output variables, special characters in
9496 Many output variables are intended to be evaluated both by
9497 @command{make} and by the shell. Some characters are expanded
9498 differently in these two contexts, so to avoid confusion these
9499 variables' values should not contain any of the following characters:
9502 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9505 Also, these variables' values should neither contain newlines, nor start
9506 with @samp{~}, nor contain white space or @samp{:} immediately followed
9507 by @samp{~}. The values can contain nonempty sequences of white space
9508 characters like tabs and spaces, but each such sequence might
9509 arbitrarily be replaced by a single space during substitution.
9511 These restrictions apply both to the values that @command{configure}
9512 computes, and to the values set directly by the user. For example, the
9513 following invocations of @command{configure} are problematic, since they
9514 attempt to use special characters within @code{CPPFLAGS} and white space
9515 within @code{$(srcdir)}:
9518 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9520 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9523 @node Caching Results
9524 @section Caching Results
9527 To avoid checking for the same features repeatedly in various
9528 @command{configure} scripts (or in repeated runs of one script),
9529 @command{configure} can optionally save the results of many checks in a
9530 @dfn{cache file} (@pxref{Cache Files}). If a @command{configure} script
9531 runs with caching enabled and finds a cache file, it reads the results
9532 of previous runs from the cache and avoids rerunning those checks. As a
9533 result, @command{configure} can then run much faster than if it had to
9534 perform all of the checks every time.
9536 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
9538 Ensure that the results of the check identified by @var{cache-id} are
9539 available. If the results of the check were in the cache file that was
9540 read, and @command{configure} was not given the @option{--quiet} or
9541 @option{--silent} option, print a message saying that the result was
9542 cached; otherwise, run the shell commands @var{commands-to-set-it}. If
9543 the shell commands are run to determine the value, the value is
9544 saved in the cache file just before @command{configure} creates its output
9545 files. @xref{Cache Variable Names}, for how to choose the name of the
9546 @var{cache-id} variable.
9548 The @var{commands-to-set-it} @emph{must have no side effects} except for
9549 setting the variable @var{cache-id}, see below.
9552 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
9553 @var{commands-to-set-it})
9554 @acindex{CACHE_CHECK}
9555 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9556 messages. This macro provides a convenient shorthand for the most
9557 common way to use these macros. It calls @code{AC_MSG_CHECKING} for
9558 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9559 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9561 The @var{commands-to-set-it} @emph{must have no side effects} except for
9562 setting the variable @var{cache-id}, see below.
9565 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9566 @code{AC_CACHE_CHECK}, because people are tempted to call
9567 @code{AC_DEFINE} in the @var{commands-to-set-it}. Instead, the code that
9568 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9569 @code{AC_DEFINE}, by examining the value of the cache variable. For
9570 instance, the following macro is broken:
9574 AC_DEFUN([AC_SHELL_TRUE],
9575 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9576 [my_cv_shell_true_works=no
9577 (true) 2>/dev/null && my_cv_shell_true_works=yes
9578 if test "x$my_cv_shell_true_works" = xyes; then
9579 AC_DEFINE([TRUE_WORKS], [1],
9580 [Define if `true(1)' works properly.])
9587 This fails if the cache is enabled: the second time this macro is run,
9588 @code{TRUE_WORKS} @emph{will not be defined}. The proper implementation
9593 AC_DEFUN([AC_SHELL_TRUE],
9594 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9595 [my_cv_shell_true_works=no
9596 (true) 2>/dev/null && my_cv_shell_true_works=yes])
9597 if test "x$my_cv_shell_true_works" = xyes; then
9598 AC_DEFINE([TRUE_WORKS], [1],
9599 [Define if `true(1)' works properly.])
9605 Also, @var{commands-to-set-it} should not print any messages, for
9606 example with @code{AC_MSG_CHECKING}; do that before calling
9607 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9608 the results of the check are retrieved from the cache or determined by
9609 running the shell commands.
9612 * Cache Variable Names:: Shell variables used in caches
9613 * Cache Files:: Files @command{configure} uses for caching
9614 * Cache Checkpointing:: Loading and saving the cache file
9617 @node Cache Variable Names
9618 @subsection Cache Variable Names
9619 @cindex Cache variable
9621 The names of cache variables should have the following format:
9624 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9628 for example, @samp{ac_cv_header_stat_broken} or
9629 @samp{ac_cv_prog_gcc_traditional}. The parts of the variable name are:
9632 @item @var{package-prefix}
9633 An abbreviation for your package or organization; the same prefix you
9634 begin local Autoconf macros with, except lowercase by convention.
9635 For cache values used by the distributed Autoconf macros, this value is
9639 Indicates that this shell variable is a cache value. This string
9640 @emph{must} be present in the variable name, including the leading
9643 @item @var{value-type}
9644 A convention for classifying cache values, to produce a rational naming
9645 system. The values used in Autoconf are listed in @ref{Macro Names}.
9647 @item @var{specific-value}
9648 Which member of the class of cache values this test applies to.
9649 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9650 output variable (@samp{INSTALL}).
9652 @item @var{additional-options}
9653 Any particular behavior of the specific member that this test applies to.
9654 For example, @samp{broken} or @samp{set}. This part of the name may
9655 be omitted if it does not apply.
9658 The values assigned to cache variables may not contain newlines.
9659 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9660 names of files or functions; so this is not an important restriction.
9661 @ref{Cache Variable Index} for an index of cache variables with
9662 documented semantics.
9666 @subsection Cache Files
9668 A cache file is a shell script that caches the results of configure
9669 tests run on one system so they can be shared between configure scripts
9670 and configure runs. It is not useful on other systems. If its contents
9671 are invalid for some reason, the user may delete or edit it.
9673 By default, @command{configure} uses no cache file,
9674 to avoid problems caused by accidental
9675 use of stale cache files.
9677 To enable caching, @command{configure} accepts @option{--config-cache} (or
9678 @option{-C}) to cache results in the file @file{config.cache}.
9679 Alternatively, @option{--cache-file=@var{file}} specifies that
9680 @var{file} be the cache file. The cache file is created if it does not
9681 exist already. When @command{configure} calls @command{configure} scripts in
9682 subdirectories, it uses the @option{--cache-file} argument so that they
9683 share the same cache. @xref{Subdirectories}, for information on
9684 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9686 @file{config.status} only pays attention to the cache file if it is
9687 given the @option{--recheck} option, which makes it rerun
9688 @command{configure}.
9690 It is wrong to try to distribute cache files for particular system types.
9691 There is too much room for error in doing that, and too much
9692 administrative overhead in maintaining them. For any features that
9693 can't be guessed automatically, use the standard method of the canonical
9694 system type and linking files (@pxref{Manual Configuration}).
9696 The site initialization script can specify a site-wide cache file to
9697 use, instead of the usual per-program cache. In this case, the cache
9698 file gradually accumulates information whenever someone runs a new
9699 @command{configure} script. (Running @command{configure} merges the new cache
9700 results with the existing cache file.) This may cause problems,
9701 however, if the system configuration (e.g., the installed libraries or
9702 compilers) changes and the stale cache file is not deleted.
9704 @node Cache Checkpointing
9705 @subsection Cache Checkpointing
9707 If your configure script, or a macro called from @file{configure.ac}, happens
9708 to abort the configure process, it may be useful to checkpoint the cache
9709 a few times at key points using @code{AC_CACHE_SAVE}. Doing so
9710 reduces the amount of time it takes to rerun the configure script with
9711 (hopefully) the error that caused the previous abort corrected.
9713 @c FIXME: Do we really want to document this guy?
9714 @defmac AC_CACHE_LOAD
9715 @acindex{CACHE_LOAD}
9716 Loads values from existing cache file, or creates a new cache file if a
9717 cache file is not found. Called automatically from @code{AC_INIT}.
9720 @defmac AC_CACHE_SAVE
9721 @acindex{CACHE_SAVE}
9722 Flushes all cached values to the cache file. Called automatically from
9723 @code{AC_OUTPUT}, but it can be quite useful to call
9724 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9730 @r{ @dots{} AC_INIT, etc. @dots{}}
9732 # Checks for programs.
9735 @r{ @dots{} more program checks @dots{}}
9740 # Checks for libraries.
9741 AC_CHECK_LIB([nsl], [gethostbyname])
9742 AC_CHECK_LIB([socket], [connect])
9743 @r{ @dots{} more lib checks @dots{}}
9748 # Might abort@dots{}
9749 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9750 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9752 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9755 @node Printing Messages
9756 @section Printing Messages
9757 @cindex Messages, from @command{configure}
9759 @command{configure} scripts need to give users running them several kinds
9760 of information. The following macros print messages in ways appropriate
9761 for each kind. The arguments to all of them get enclosed in shell
9762 double quotes, so the shell performs variable and back-quote
9763 substitution on them.
9765 These macros are all wrappers around the @command{echo} shell command.
9766 They direct output to the appropriate file descriptor (@pxref{File
9767 Descriptor Macros}).
9768 @command{configure} scripts should rarely need to run @command{echo} directly
9769 to print messages for the user. Using these macros makes it easy to
9770 change how and when each kind of message is printed; such changes need
9771 only be made to the macro definitions and all the callers change
9774 To diagnose static issues, i.e., when @command{autoconf} is run, see
9775 @ref{Diagnostic Macros}.
9777 @defmac AC_MSG_CHECKING (@var{feature-description})
9778 @acindex{MSG_CHECKING}
9779 Notify the user that @command{configure} is checking for a particular
9780 feature. This macro prints a message that starts with @samp{checking }
9781 and ends with @samp{...} and no newline. It must be followed by a call
9782 to @code{AC_MSG_RESULT} to print the result of the check and the
9783 newline. The @var{feature-description} should be something like
9784 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9787 This macro prints nothing if @command{configure} is run with the
9788 @option{--quiet} or @option{--silent} option.
9791 @anchor{AC_MSG_RESULT}
9792 @defmac AC_MSG_RESULT (@var{result-description})
9793 @acindex{MSG_RESULT}
9794 Notify the user of the results of a check. @var{result-description} is
9795 almost always the value of the cache variable for the check, typically
9796 @samp{yes}, @samp{no}, or a file name. This macro should follow a call
9797 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9798 the completion of the message printed by the call to
9799 @code{AC_MSG_CHECKING}.
9801 This macro prints nothing if @command{configure} is run with the
9802 @option{--quiet} or @option{--silent} option.
9805 @anchor{AC_MSG_NOTICE}
9806 @defmac AC_MSG_NOTICE (@var{message})
9807 @acindex{MSG_NOTICE}
9808 Deliver the @var{message} to the user. It is useful mainly to print a
9809 general description of the overall purpose of a group of feature checks,
9813 AC_MSG_NOTICE([checking if stack overflow is detectable])
9816 This macro prints nothing if @command{configure} is run with the
9817 @option{--quiet} or @option{--silent} option.
9820 @anchor{AC_MSG_ERROR}
9821 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9823 Notify the user of an error that prevents @command{configure} from
9824 completing. This macro prints an error message to the standard error
9825 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9826 by default, except that @samp{0} is converted to @samp{1}).
9827 @var{error-description} should be something like @samp{invalid value
9830 The @var{error-description} should start with a lower-case letter, and
9831 ``cannot'' is preferred to ``can't''.
9834 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9835 @acindex{MSG_FAILURE}
9836 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9837 prevents @command{configure} from completing @emph{and} that additional
9838 details are provided in @file{config.log}. This is typically used when
9839 abnormal results are found during a compilation.
9842 @anchor{AC_MSG_WARN}
9843 @defmac AC_MSG_WARN (@var{problem-description})
9845 Notify the @command{configure} user of a possible problem. This macro
9846 prints the message to the standard error output; @command{configure}
9847 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9848 provide a default (back-up) behavior for the situations they warn about.
9849 @var{problem-description} should be something like @samp{ln -s seems to
9855 @c ====================================================== Programming in M4.
9857 @node Programming in M4
9858 @chapter Programming in M4
9861 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9862 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9863 provides macros dedicated to shell script generation.
9865 As of this version of Autoconf, these two layers still contain
9866 experimental macros, whose interface might change in the future. As a
9867 matter of fact, @emph{anything that is not documented must not be used}.
9870 * M4 Quotation:: Protecting macros from unwanted expansion
9871 * Using autom4te:: The Autoconf executables backbone
9872 * Programming in M4sugar:: Convenient pure M4 macros
9873 * Debugging via autom4te:: Figuring out what M4 was doing
9877 @section M4 Quotation
9878 @cindex M4 quotation
9881 The most common problem with existing macros is an improper quotation.
9882 This section, which users of Autoconf can skip, but which macro writers
9883 @emph{must} read, first justifies the quotation scheme that was chosen
9884 for Autoconf and then ends with a rule of thumb. Understanding the
9885 former helps one to follow the latter.
9888 * Active Characters:: Characters that change the behavior of M4
9889 * One Macro Call:: Quotation and one macro call
9890 * Quoting and Parameters:: M4 vs. shell parameters
9891 * Quotation and Nested Macros:: Macros calling macros
9892 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
9893 * Quadrigraphs:: Another way to escape special characters
9894 * Balancing Parentheses:: Dealing with unbalanced parentheses
9895 * Quotation Rule Of Thumb:: One parenthesis, one quote
9898 @node Active Characters
9899 @subsection Active Characters
9901 To fully understand where proper quotation is important, you first need
9902 to know what the special characters are in Autoconf: @samp{#} introduces
9903 a comment inside which no macro expansion is performed, @samp{,}
9904 separates arguments, @samp{[} and @samp{]} are the quotes
9905 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
9906 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
9907 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9908 @samp{$} inside a macro definition.
9910 In order to understand the delicate case of macro calls, we first have
9911 to present some obvious failures. Below they are ``obvious-ified'',
9912 but when you find them in real life, they are usually in disguise.
9914 Comments, introduced by a hash and running up to the newline, are opaque
9915 tokens to the top level: active characters are turned off, and there is
9919 # define([def], ine)
9920 @result{}# define([def], ine)
9923 Each time there can be a macro expansion, there is a quotation
9924 expansion, i.e., one level of quotes is stripped:
9930 @result{}int tab[10];
9933 Without this in mind, the reader might try hopelessly to use her macro
9937 define([array], [int tab[10];])
9945 How can you correctly output the intended results@footnote{Using
9949 @node One Macro Call
9950 @subsection One Macro Call
9952 Let's proceed on the interaction between active characters and macros
9953 with this small macro, which just returns its first argument:
9960 The two pairs of quotes above are not part of the arguments of
9961 @code{define}; rather, they are understood by the top level when it
9962 tries to find the arguments of @code{define}. Therefore, assuming
9963 @code{car} is not already defined, it is equivalent to write:
9970 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9971 quotes, it is bad practice for Autoconf macros which must both be more
9972 robust and also advocate perfect style.
9974 At the top level, there are only two possibilities: either you
9980 [car(foo, bar, baz)]
9981 @result{}car(foo, bar, baz)
9984 Let's pay attention to the special characters:
9988 @error{}EOF in argument list
9991 The closing parenthesis is hidden in the comment; with a hypothetical
9992 quoting, the top level understood it this way:
9999 Proper quotation, of course, fixes the problem:
10006 Here are more examples:
10014 @result{}(foo, bar)
10015 car([(foo], [bar)])
10029 @node Quoting and Parameters
10030 @subsection Quoting and Parameters
10032 When M4 encounters @samp{$} within a macro definition, followed
10033 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10034 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10035 expansion. This happens regardless of how many layers of quotes the
10036 parameter expansion is nested within, or even if it occurs in text that
10037 will be rescanned as a comment.
10040 define([none], [$1])
10042 define([one], [[$1]])
10044 define([two], [[[$1]]])
10046 define([comment], [# $1])
10048 define([active], [ACTIVE])
10060 On the other hand, since autoconf generates shell code, you often want
10061 to output shell variable expansion, rather than performing M4 parameter
10062 expansion. To do this, you must use M4 quoting to separate the @samp{$}
10063 from the next character in the definition of your macro. If the macro
10064 definition occurs in single-quoted text, then insert another level of
10065 quoting; if the usage is already inside a double-quoted string, then
10066 split it into concatenated strings.
10069 define([single], [a single-quoted $[]1 definition])
10071 define([double], [[a double-quoted $][1 definition]])
10074 @result{}a single-quoted $1 definition
10076 @result{}a double-quoted $1 definition
10079 Posix states that M4 implementations are free to provide implementation
10080 extensions when @samp{$@{} is encountered in a macro definition.
10081 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10082 extensions that will be available in the future GNU M4 2.0,
10083 but guarantees that all other instances of @samp{$@{} will be output
10084 literally. Therefore, this idiom can also be used to output shell code
10085 parameter references:
10088 define([first], [$@{1@}])first
10092 Posix also states that @samp{$11} should expand to the first parameter
10093 concatenated with a literal @samp{1}, although some versions of
10094 GNU M4 expand the eleventh parameter instead. For
10095 portability, you should only use single-digit M4 parameter expansion.
10097 With this in mind, we can explore the cases where macros invoke
10100 @node Quotation and Nested Macros
10101 @subsection Quotation and Nested Macros
10103 The examples below use the following macros:
10106 define([car], [$1])
10107 define([active], [ACT, IVE])
10108 define([array], [int tab[10]])
10111 Each additional embedded macro call introduces other possible
10112 interesting quotations:
10123 In the first case, the top level looks for the arguments of @code{car},
10124 and finds @samp{active}. Because M4 evaluates its arguments
10125 before applying the macro, @samp{active} is expanded, which results in:
10133 In the second case, the top level gives @samp{active} as first and only
10134 argument of @code{car}, which results in:
10142 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10143 In the third case, @code{car} receives @samp{[active]}, which results in:
10151 exactly as we already saw above.
10153 The example above, applied to a more realistic example, gives:
10157 @result{}int tab10;
10158 car([int tab[10];])
10159 @result{}int tab10;
10160 car([[int tab[10];]])
10161 @result{}int tab[10];
10165 Huh? The first case is easily understood, but why is the second wrong,
10166 and the third right? To understand that, you must know that after
10167 M4 expands a macro, the resulting text is immediately subjected
10168 to macro expansion and quote removal. This means that the quote removal
10169 occurs twice---first before the argument is passed to the @code{car}
10170 macro, and second after the @code{car} macro expands to the first
10173 As the author of the Autoconf macro @code{car}, you then consider it to
10174 be incorrect that your users have to double-quote the arguments of
10175 @code{car}, so you ``fix'' your macro. Let's call it @code{qar} for
10179 define([qar], [[$1]])
10183 and check that @code{qar} is properly fixed:
10186 qar([int tab[10];])
10187 @result{}int tab[10];
10191 Ahhh! That's much better.
10193 But note what you've done: now that the result of @code{qar} is always
10194 a literal string, the only time a user can use nested macros is if she
10195 relies on an @emph{unquoted} macro call:
10205 leaving no way for her to reproduce what she used to do with @code{car}:
10213 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10217 define([my_includes], [#include <stdio.h>])
10219 @result{}#include <stdio.h>
10221 @error{}EOF in argument list
10224 This macro, @code{qar}, because it double quotes its arguments, forces
10225 its users to leave their macro calls unquoted, which is dangerous.
10226 Commas and other active symbols are interpreted by M4 before
10227 they are given to the macro, often not in the way the users expect.
10228 Also, because @code{qar} behaves differently from the other macros,
10229 it's an exception that should be avoided in Autoconf.
10231 @node Changequote is Evil
10232 @subsection @code{changequote} is Evil
10233 @cindex @code{changequote}
10235 The temptation is often high to bypass proper quotation, in particular
10236 when it's late at night. Then, many experienced Autoconf hackers
10237 finally surrender to the dark side of the force and use the ultimate
10238 weapon: @code{changequote}.
10240 The M4 builtin @code{changequote} belongs to a set of primitives that
10241 allow one to adjust the syntax of the language to adjust it to one's
10242 needs. For instance, by default M4 uses @samp{`} and @samp{'} as
10243 quotes, but in the context of shell programming (and actually of most
10244 programming languages), that's about the worst choice one can make:
10245 because of strings and back-quoted expressions in shell code (such as
10246 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10247 programming languages (as in @samp{'0'}), there are many unbalanced
10248 @samp{`} and @samp{'}. Proper M4 quotation then becomes a nightmare, if
10249 not impossible. In order to make M4 useful in such a context, its
10250 designers have equipped it with @code{changequote}, which makes it
10251 possible to choose another pair of quotes. M4sugar, M4sh, Autoconf, and
10252 Autotest all have chosen to use @samp{[} and @samp{]}. Not especially
10253 because they are unlikely characters, but @emph{because they are
10254 characters unlikely to be unbalanced}.
10256 There are other magic primitives, such as @code{changecom} to specify
10257 what syntactic forms are comments (it is common to see
10258 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10259 @code{changeword} and @code{changesyntax} to change other syntactic
10260 details (such as the character to denote the @var{n}th argument, @samp{$} by
10261 default, the parentheses around arguments, etc.).
10263 These primitives are really meant to make M4 more useful for specific
10264 domains: they should be considered like command line options:
10265 @option{--quotes}, @option{--comments}, @option{--words}, and
10266 @option{--syntax}. Nevertheless, they are implemented as M4 builtins, as
10267 it makes M4 libraries self contained (no need for additional options).
10269 There lies the problem@enddots{}
10273 The problem is that it is then tempting to use them in the middle of an
10274 M4 script, as opposed to its initialization. This, if not carefully
10275 thought out, can lead to disastrous effects: @emph{you are changing the
10276 language in the middle of the execution}. Changing and restoring the
10277 syntax is often not enough: if you happened to invoke macros in between,
10278 these macros are lost, as the current syntax is probably not
10279 the one they were implemented with.
10281 @c FIXME: I've been looking for a short, real case example, but I
10282 @c lost them all :(
10286 @subsection Quadrigraphs
10287 @cindex quadrigraphs
10288 @cindex @samp{@@S|@@}
10289 @cindex @samp{@@&t@@}
10290 @c Info cannot handle `:' in index entries.
10292 @cindex @samp{@@<:@@}
10293 @cindex @samp{@@:>@@}
10294 @cindex @samp{@@%:@@}
10295 @cindex @samp{@@@{:@@}
10296 @cindex @samp{@@:@}@@}
10299 When writing an Autoconf macro you may occasionally need to generate
10300 special characters that are difficult to express with the standard
10301 Autoconf quoting rules. For example, you may need to output the regular
10302 expression @samp{[^[]}, which matches any character other than @samp{[}.
10303 This expression contains unbalanced brackets so it cannot be put easily
10306 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10307 and @code{m4_expand}) which internally use special markers in addition
10308 to the regular quoting characters. If the arguments to these macros
10309 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10310 might behave incorrectly.
10312 You can work around these problems by using one of the following
10313 @dfn{quadrigraphs}:
10329 Expands to nothing.
10332 Quadrigraphs are replaced at a late stage of the translation process,
10333 after @command{m4} is run, so they do not get in the way of M4 quoting.
10334 For example, the string @samp{^@@<:@@}, independently of its quotation,
10335 appears as @samp{^[} in the output.
10337 The empty quadrigraph can be used:
10340 @item to mark trailing spaces explicitly
10342 Trailing spaces are smashed by @command{autom4te}. This is a feature.
10344 @item to produce quadrigraphs and other strings reserved by m4sugar
10346 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}. For a more
10350 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10351 m4_split([a )@}>=- b -=<@{( c])
10352 @result{}[a], [], [B], [], [c]
10353 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10354 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10357 @item to escape @emph{occurrences} of forbidden patterns
10359 For instance you might want to mention @code{AC_FOO} in a comment, while
10360 still being sure that @command{autom4te} still catches unexpanded
10361 @samp{AC_*}. Then write @samp{AC@@&t@@_FOO}.
10364 The name @samp{@@&t@@} was suggested by Paul Eggert:
10367 I should give some credit to the @samp{@@&t@@} pun. The @samp{&} is my
10368 own invention, but the @samp{t} came from the source code of the
10369 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10370 and which used @samp{mt} to denote the empty string. In C, it would
10371 have looked like something like:
10374 char const mt[] = "";
10378 but of course the source code was written in Algol 68.
10380 I don't know where he got @samp{mt} from: it could have been his own
10381 invention, and I suppose it could have been a common pun around the
10382 Cambridge University computer lab at the time.
10386 @node Balancing Parentheses
10387 @subsection Dealing with unbalanced parentheses
10388 @cindex balancing parentheses
10389 @cindex parentheses, balancing
10390 @cindex unbalanced parentheses, managing
10392 One of the pitfalls of portable shell programming is that @command{case}
10393 statements require unbalanced parentheses (@pxref{case, , Limitations of
10394 Shell Builtins}). With syntax highlighting
10395 editors, the presence of unbalanced @samp{)} can interfere with editors
10396 that perform syntax highlighting of macro contents based on finding the
10397 matching @samp{(}. Another concern is how much editing must be done
10398 when transferring code snippets between shell scripts and macro
10399 definitions. But most importantly, the presence of unbalanced
10400 parentheses can introduce expansion bugs.
10402 For an example, here is an underquoted attempt to use the macro
10403 @code{my_case}, which happens to expand to a portable @command{case}
10407 AC_DEFUN([my_case],
10408 [case $file_name in
10409 *.c) echo "C source code";;
10415 In the above example, the @code{AS_IF} call underquotes its arguments.
10416 As a result, the unbalanced @samp{)} generated by the premature
10417 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10418 truncated parameter, and the expansion is syntactically invalid:
10424 fi echo "C source code";;
10428 If nothing else, this should emphasize the importance of the quoting
10429 arguments to macro calls. On the other hand, there are several
10430 variations for defining @code{my_case} to be more robust, even when used
10431 without proper quoting, each with some benefits and some drawbacks.
10434 @item Creative literal shell comment
10436 AC_DEFUN([my_case],
10437 [case $file_name in #(
10438 *.c) echo "C source code";;
10442 This version provides balanced parentheses to several editors, and can
10443 be copied and pasted into a terminal as is. Unfortunately, it is still
10444 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10445 that masks the normal properties of @samp{(}.
10447 @item Quadrigraph shell comment
10449 AC_DEFUN([my_case],
10450 [case $file_name in @@%:@@(
10451 *.c) echo "C source code";;
10455 This version provides balanced parentheses to even more editors, and can
10456 be used as a balanced Autoconf argument. Unfortunately, it requires
10457 some editing before it can be copied and pasted into a terminal, and the
10458 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10460 @item Quoting just the parenthesis
10462 AC_DEFUN([my_case],
10463 [case $file_name in
10464 *.c[)] echo "C source code";;
10468 This version quotes the @samp{)}, so that it can be used as a balanced
10469 Autoconf argument. As written, this is not balanced to an editor, but
10470 it can be coupled with @samp{[#(]} to meet that need, too. However, it
10471 still requires some edits before it can be copied and pasted into a
10474 @item Double-quoting the entire statement
10476 AC_DEFUN([my_case],
10477 [[case $file_name in #(
10478 *.c) echo "C source code";;
10482 Since the entire macro is double-quoted, there is no problem with using
10483 this as an Autoconf argument; and since the double-quoting is over the
10484 entire statement, this code can be easily copied and pasted into a
10485 terminal. However, the double quoting prevents the expansion of any
10486 macros inside the case statement, which may cause its own set of
10489 @item Using @code{AS_CASE}
10491 AC_DEFUN([my_case],
10492 [AS_CASE([$file_name],
10493 [*.c], [echo "C source code"])])
10496 This version avoids the balancing issue altogether, by relying on
10497 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10498 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10499 statement, rather than within a branch of the case statement that might
10500 not be taken. However, the abstraction comes with a penalty that it is
10501 no longer a quick copy, paste, and edit to get back to shell code.
10505 @node Quotation Rule Of Thumb
10506 @subsection Quotation Rule Of Thumb
10508 To conclude, the quotation rule of thumb is:
10510 @center @emph{One pair of quotes per pair of parentheses.}
10512 Never over-quote, never under-quote, in particular in the definition of
10513 macros. In the few places where the macros need to use brackets
10514 (usually in C program text or regular expressions), properly quote
10515 @emph{the arguments}!
10517 It is common to read Autoconf programs with snippets like:
10521 changequote(<<, >>)dnl
10522 <<#include <time.h>
10523 #ifndef tzname /* For SGI. */
10524 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
10526 changequote([, ])dnl
10527 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
10531 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
10532 double quoting, so you just need:
10537 #ifndef tzname /* For SGI. */
10538 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
10541 [ac_cv_var_tzname=yes],
10542 [ac_cv_var_tzname=no])
10546 The M4-fluent reader might note that these two examples are rigorously
10547 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
10548 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
10549 quotes are not part of the arguments!
10551 Simplified, the example above is just doing this:
10554 changequote(<<, >>)dnl
10556 changequote([, ])dnl
10566 With macros that do not double quote their arguments (which is the
10567 rule), double-quote the (risky) literals:
10570 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10571 [[#include <time.h>
10572 #ifndef tzname /* For SGI. */
10573 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
10575 [atoi (*tzname);])],
10576 [ac_cv_var_tzname=yes],
10577 [ac_cv_var_tzname=no])
10580 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10581 should be using @code{AC_LINK_IFELSE} instead.
10583 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10584 where quoting does not suffice.
10586 When you create a @command{configure} script using newly written macros,
10587 examine it carefully to check whether you need to add more quotes in
10588 your macros. If one or more words have disappeared in the M4
10589 output, you need more quotes. When in doubt, quote.
10591 However, it's also possible to put on too many layers of quotes. If
10592 this happens, the resulting @command{configure} script may contain
10593 unexpanded macros. The @command{autoconf} program checks for this problem
10594 by looking for the string @samp{AC_} in @file{configure}. However, this
10595 heuristic does not work in general: for example, it does not catch
10596 overquoting in @code{AC_DEFINE} descriptions.
10599 @c ---------------------------------------- Using autom4te
10601 @node Using autom4te
10602 @section Using @command{autom4te}
10604 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10605 to Autoconf per se, heavily rely on M4. All these different uses
10606 revealed common needs factored into a layer over M4:
10607 @command{autom4te}@footnote{
10609 Yet another great name from Lars J. Aas.
10613 @command{autom4te} is a preprocessor that is like @command{m4}.
10614 It supports M4 extensions designed for use in tools like Autoconf.
10617 * autom4te Invocation:: A GNU M4 wrapper
10618 * Customizing autom4te:: Customizing the Autoconf package
10621 @node autom4te Invocation
10622 @subsection Invoking @command{autom4te}
10624 The command line arguments are modeled after M4's:
10627 autom4te @var{options} @var{files}
10632 where the @var{files} are directly passed to @command{m4}. By default,
10633 GNU M4 is found during configuration, but the environment
10635 @env{M4} can be set to tell @command{autom4te} where to look. In addition
10636 to the regular expansion, it handles the replacement of the quadrigraphs
10637 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10638 output. It supports an extended syntax for the @var{files}:
10641 @item @var{file}.m4f
10642 This file is an M4 frozen file. Note that @emph{all the previous files
10643 are ignored}. See the option @option{--melt} for the rationale.
10646 If found in the library path, the @var{file} is included for expansion,
10647 otherwise it is ignored instead of triggering a failure.
10652 Of course, it supports the Autoconf common subset of options:
10657 Print a summary of the command line options and exit.
10661 Print the version number of Autoconf and exit.
10665 Report processing steps.
10669 Don't remove the temporary files and be even more verbose.
10671 @item --include=@var{dir}
10672 @itemx -I @var{dir}
10673 Also look for input files in @var{dir}. Multiple invocations
10676 @item --output=@var{file}
10677 @itemx -o @var{file}
10678 Save output (script or trace) to @var{file}. The file @option{-} stands
10679 for the standard output.
10684 As an extension of @command{m4}, it includes the following options:
10687 @item --warnings=@var{category}
10688 @itemx -W @var{category}
10690 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10691 Report the warnings related to @var{category} (which can actually be a
10692 comma separated list). @xref{Reporting Messages}, macro
10693 @code{AC_DIAGNOSE}, for a comprehensive list of categories. Special
10698 report all the warnings
10704 treats warnings as errors
10706 @item no-@var{category}
10707 disable warnings falling into @var{category}
10710 Warnings about @samp{syntax} are enabled by default, and the environment
10711 variable @env{WARNINGS}, a comma separated list of categories, is
10712 honored. @samp{autom4te -W @var{category}} actually
10713 behaves as if you had run:
10716 autom4te --warnings=syntax,$WARNINGS,@var{category}
10720 For example, if you want to disable defaults and @env{WARNINGS}
10721 of @command{autom4te}, but enable the warnings about obsolete
10722 constructs, you would use @option{-W none,obsolete}.
10725 @cindex Macro invocation stack
10726 @command{autom4te} displays a back trace for errors, but not for
10727 warnings; if you want them, just pass @option{-W error}.
10731 Do not use frozen files. Any argument @code{@var{file}.m4f} is
10732 replaced by @code{@var{file}.m4}. This helps tracing the macros which
10733 are executed only when the files are frozen, typically
10734 @code{m4_define}. For instance, running:
10737 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10741 is roughly equivalent to running:
10744 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10751 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10758 m4 --reload-state=4.m4f input.m4
10763 Produce a frozen state file. @command{autom4te} freezing is stricter
10764 than M4's: it must produce no warnings, and no output other than empty
10765 lines (a line with white space is @emph{not} empty) and comments
10766 (starting with @samp{#}). Unlike @command{m4}'s similarly-named option,
10767 this option takes no argument:
10770 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10777 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10780 @item --mode=@var{octal-mode}
10781 @itemx -m @var{octal-mode}
10782 Set the mode of the non-traces output to @var{octal-mode}; by default
10788 @cindex @file{autom4te.cache}
10789 As another additional feature over @command{m4}, @command{autom4te}
10790 caches its results. GNU M4 is able to produce a regular
10791 output and traces at the same time. Traces are heavily used in the
10792 GNU Build System: @command{autoheader} uses them to build
10793 @file{config.h.in}, @command{autoreconf} to determine what
10794 GNU Build System components are used, @command{automake} to
10795 ``parse'' @file{configure.ac} etc. To avoid recomputation,
10796 traces are cached while performing regular expansion,
10797 and conversely. This cache is (actually, the caches are) stored in
10798 the directory @file{autom4te.cache}. @emph{It can safely be removed}
10799 at any moment (especially if for some reason @command{autom4te}
10800 considers it trashed).
10803 @item --cache=@var{directory}
10804 @itemx -C @var{directory}
10805 Specify the name of the directory where the result should be cached.
10806 Passing an empty value disables caching. Be sure to pass a relative
10807 file name, as for the time being, global caches are not supported.
10810 Don't cache the results.
10814 If a cache is used, consider it obsolete (but update it anyway).
10819 Because traces are so important to the GNU Build System,
10820 @command{autom4te} provides high level tracing features as compared to
10821 M4, and helps exploiting the cache:
10824 @item --trace=@var{macro}[:@var{format}]
10825 @itemx -t @var{macro}[:@var{format}]
10826 Trace the invocations of @var{macro} according to the @var{format}.
10827 Multiple @option{--trace} arguments can be used to list several macros.
10828 Multiple @option{--trace} arguments for a single macro are not
10829 cumulative; instead, you should just make @var{format} as long as
10832 The @var{format} is a regular string, with newlines if desired, and
10833 several special escape codes. It defaults to @samp{$f:$l:$n:$%}. It can
10834 use the following special escapes:
10838 The character @samp{$}.
10841 The file name from which @var{macro} is called.
10844 The line number from which @var{macro} is called.
10847 The depth of the @var{macro} call. This is an M4 technical detail that
10848 you probably don't want to know about.
10851 The name of the @var{macro}.
10854 The @var{num}th argument of the call to @var{macro}.
10857 @itemx $@var{sep}@@
10858 @itemx $@{@var{separator}@}@@
10859 All the arguments passed to @var{macro}, separated by the character
10860 @var{sep} or the string @var{separator} (@samp{,} by default). Each
10861 argument is quoted, i.e., enclosed in a pair of square brackets.
10865 @itemx $@{@var{separator}@}*
10866 As above, but the arguments are not quoted.
10870 @itemx $@{@var{separator}@}%
10871 As above, but the arguments are not quoted, all new line characters in
10872 the arguments are smashed, and the default separator is @samp{:}.
10874 The escape @samp{$%} produces single-line trace outputs (unless you put
10875 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10879 @xref{autoconf Invocation}, for examples of trace uses.
10881 @item --preselect=@var{macro}
10882 @itemx -p @var{macro}
10883 Cache the traces of @var{macro}, but do not enable traces. This is
10884 especially important to save CPU cycles in the future. For instance,
10885 when invoked, @command{autoconf} preselects all the macros that
10886 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10887 trace, so that running @command{m4} is not needed to trace them: the
10888 cache suffices. This results in a huge speed-up.
10893 @cindex Autom4te Library
10894 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10895 libraries}. They consists in a powerful yet extremely simple feature:
10896 sets of combined command line arguments:
10899 @item --language=@var{language}
10900 @itemx -l @var{language}
10901 Use the @var{language} Autom4te library. Current languages include:
10905 create M4sugar output.
10908 create M4sh executable shell scripts.
10911 create Autotest executable test suites.
10913 @item Autoconf-without-aclocal-m4
10914 create Autoconf executable configure scripts without
10915 reading @file{aclocal.m4}.
10918 create Autoconf executable configure scripts. This language inherits
10919 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10920 additionally reads @file{aclocal.m4}.
10923 @item --prepend-include=@var{dir}
10924 @itemx -B @var{dir}
10925 Prepend directory @var{dir} to the search path. This is used to include
10926 the language-specific files before any third-party macros.
10930 @cindex @file{autom4te.cfg}
10931 As an example, if Autoconf is installed in its default location,
10932 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10933 strictly equivalent to the command:
10936 autom4te --prepend-include /usr/local/share/autoconf \
10937 m4sugar/m4sugar.m4f --warnings syntax foo.m4
10941 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10942 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10946 autom4te --prepend-include /usr/local/share/autoconf \
10947 m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10951 The definition of the languages is stored in @file{autom4te.cfg}.
10953 @node Customizing autom4te
10954 @subsection Customizing @command{autom4te}
10956 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10957 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10958 as found in the directory from which @command{autom4te} is run). The
10959 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10960 then @file{./.autom4te.cfg}, and finally the command line arguments.
10962 In these text files, comments are introduced with @code{#}, and empty
10963 lines are ignored. Customization is performed on a per-language basis,
10964 wrapped in between a @samp{begin-language: "@var{language}"},
10965 @samp{end-language: "@var{language}"} pair.
10967 Customizing a language stands for appending options (@pxref{autom4te
10968 Invocation}) to the current definition of the language. Options, and
10969 more generally arguments, are introduced by @samp{args:
10970 @var{arguments}}. You may use the traditional shell syntax to quote the
10973 As an example, to disable Autoconf caches (@file{autom4te.cache})
10974 globally, include the following lines in @file{~/.autom4te.cfg}:
10977 ## ------------------ ##
10978 ## User Preferences. ##
10979 ## ------------------ ##
10981 begin-language: "Autoconf-without-aclocal-m4"
10983 end-language: "Autoconf-without-aclocal-m4"
10987 @node Programming in M4sugar
10988 @section Programming in M4sugar
10991 M4 by itself provides only a small, but sufficient, set of all-purpose
10992 macros. M4sugar introduces additional generic macros. Its name was
10993 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10996 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10997 the macro namespace @samp{^m4_} for M4sugar macros. You should not
10998 define your own macros into these namespaces.
11001 * Redefined M4 Macros:: M4 builtins changed in M4sugar
11002 * Diagnostic Macros:: Diagnostic messages from M4sugar
11003 * Diversion support:: Diversions in M4sugar
11004 * Conditional constructs:: Conditions in M4
11005 * Looping constructs:: Iteration in M4
11006 * Evaluation Macros:: More quotation and evaluation control
11007 * Text processing Macros:: String manipulation in M4
11008 * Number processing Macros:: Arithmetic computation in M4
11009 * Set manipulation Macros:: Set manipulation in M4
11010 * Forbidden Patterns:: Catching unexpanded macros
11013 @node Redefined M4 Macros
11014 @subsection Redefined M4 Macros
11017 @msindex{changecom}
11018 @msindex{changequote}
11019 @msindex{debugfile}
11020 @msindex{debugmode}
11041 With a few exceptions, all the M4 native macros are moved in the
11042 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11043 @code{m4_define} etc.
11045 The list of macros unchanged from M4, except for their name, is:
11049 @item m4_changequote
11074 Some M4 macros are redefined, and are slightly incompatible with their
11081 All M4 macros starting with @samp{__} retain their original name: for
11082 example, no @code{m4__file__} is defined.
11087 This is not technically a macro, but a feature of Autom4te. The
11088 sequence @code{__oline__} can be used similarly to the other m4sugar
11089 location macros, but rather than expanding to the location of the input
11090 file, it is translated to the line number where it appears in the output
11091 file after all other M4 expansions.
11096 This macro kept its original name: no @code{m4_dnl} is defined.
11099 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11100 @msindex{bpatsubst}
11101 This macro corresponds to @code{patsubst}. The name @code{m4_patsubst}
11102 is kept for future versions of M4sugar, once GNU M4 2.0 is
11103 released and supports extended regular expression syntax.
11106 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11108 This macro corresponds to @code{regexp}. The name @code{m4_regexp}
11109 is kept for future versions of M4sugar, once GNU M4 2.0 is
11110 released and supports extended regular expression syntax.
11113 @defmac m4_copy (@var{source}, @var{dest})
11114 @defmacx m4_copy_force (@var{source}, @var{dest})
11115 @defmacx m4_rename (@var{source}, @var{dest})
11116 @defmacx m4_rename_force (@var{source}, @var{dest})
11118 @msindex{copy_force}
11120 @msindex{rename_force}
11121 These macros aren't directly builtins, but are closely related to
11122 @code{m4_pushdef} and @code{m4_defn}. @code{m4_copy} and
11123 @code{m4_rename} ensure that @var{dest} is undefined, while
11124 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11125 definition. All four macros then proceed to copy the entire pushdef
11126 stack of definitions of @var{source} over to @var{dest}. @code{m4_copy}
11127 and @code{m4_copy_force} preserve the source (including in the special
11128 case where @var{source} is undefined), while @code{m4_rename} and
11129 @code{m4_rename_force} undefine the original macro name (making it an
11130 error to rename an undefined @var{source}).
11132 Note that attempting to invoke a renamed macro might not work, since the
11133 macro may have a dependence on helper macros accessed via composition of
11134 @samp{$0} but that were not also renamed; likewise, other macros may
11135 have a hard-coded dependence on @var{source} and could break if
11136 @var{source} has been deleted. On the other hand, it is always safe to
11137 rename a macro to temporarily move it out of the way, then rename it
11138 back later to restore original semantics.
11141 @defmac m4_defn (@var{macro}@dots{})
11143 This macro fails if @var{macro} is not defined, even when using older
11144 versions of M4 that did not warn. See @code{m4_undefine}.
11145 Unfortunately, in order to support these older versions of M4, there are
11146 some situations involving unbalanced quotes where concatenating multiple
11147 macros together will work in newer M4 but not in m4sugar; use
11148 quadrigraphs to work around this.
11151 @defmac m4_divert (@var{diversion})
11153 M4sugar relies heavily on diversions, so rather than behaving as a
11154 primitive, @code{m4_divert} behaves like:
11156 m4_divert_pop()m4_divert_push([@var{diversion}])
11159 @xref{Diversion support}, for more details about the use of the
11160 diversion stack. In particular, this implies that @var{diversion}
11161 should be a named diversion rather than a raw number. But be aware that
11162 it is seldom necessary to explicitly change the diversion stack, and
11163 that when done incorrectly, it can lead to syntactically invalid
11167 @defmac m4_dumpdef (@var{name}@dots{})
11168 @defmacx m4_dumpdefs (@var{name}@dots{})
11171 @code{m4_dumpdef} is like the M4 builtin, except that this version
11172 requires at least one argument, output always goes to standard error
11173 rather than the current debug file, no sorting is done on multiple
11174 arguments, and an error is issued if any
11175 @var{name} is undefined. @code{m4_dumpdefs} is a convenience macro that
11176 calls @code{m4_dumpdef} for all of the
11177 @code{m4_pushdef} stack of definitions, starting with the current, and
11178 silently does nothing if @var{name} is undefined.
11180 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11181 builtin is output as the empty string. This behavior is rectified by
11182 using M4 1.6 or newer. However, this behavior difference means that
11183 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11184 and never in the final published form of a macro.
11187 @defmac m4_esyscmd_s (@var{command})
11188 @msindex{esyscmd_s}
11189 Like @code{m4_esyscmd}, this macro expands to the result of running
11190 @var{command} in a shell. The difference is that any trailing newlines
11191 are removed, so that the output behaves more like shell command
11195 @defmac m4_exit (@var{exit-status})
11197 This macro corresponds to @code{m4exit}.
11200 @defmac m4_if (@var{comment})
11201 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11202 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11203 @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11205 This macro corresponds to @code{ifelse}. @var{string-1} and
11206 @var{string-2} are compared literally, so usually one of the two
11207 arguments is passed unquoted. @xref{Conditional constructs}, for more
11208 conditional idioms.
11211 @defmac m4_include (@var{file})
11212 @defmacx m4_sinclude (@var{file})
11215 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11218 @defmac m4_mkstemp (@var{template})
11219 @defmacx m4_maketemp (@var{template})
11222 Posix requires @code{maketemp} to replace the trailing @samp{X}
11223 characters in @var{template} with the process id, without regards to the
11224 existence of a file by that name, but this a security hole. When this
11225 was pointed out to the Posix folks, they agreed to invent a new macro
11226 @code{mkstemp} that always creates a uniquely named file, but not all
11227 versions of GNU M4 support the new macro. In M4sugar,
11228 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11229 and both have the secure semantics regardless of which macro the
11230 underlying M4 provides.
11233 @defmac m4_popdef (@var{macro}@dots{})
11235 This macro fails if @var{macro} is not defined, even when using older
11236 versions of M4 that did not warn. See @code{m4_undefine}.
11239 @defmac m4_undefine (@var{macro}@dots{})
11241 This macro fails if @var{macro} is not defined, even when using older
11242 versions of M4 that did not warn. Use
11245 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11249 if you are not sure whether @var{macro} is defined.
11252 @defmac m4_undivert (@var{diversion}@dots{})
11254 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11255 Also, since the M4sugar diversion stack prefers named
11256 diversions, the use of @code{m4_undivert} to include files is risky.
11257 @xref{Diversion support}, for more details about the use of the
11258 diversion stack. But be aware that it is seldom necessary to explicitly
11259 change the diversion stack, and that when done incorrectly, it can lead
11260 to syntactically invalid scripts.
11263 @defmac m4_wrap (@var{text})
11264 @defmacx m4_wrap_lifo (@var{text})
11266 @msindex{wrap_lifo}
11267 These macros correspond to @code{m4wrap}. Posix requires arguments of
11268 multiple wrap calls to be reprocessed at EOF in the same order
11269 as the original calls (first-in, first-out). GNU M4 versions
11270 through 1.4.10, however, reprocess them in reverse order (last-in,
11271 first-out). Both orders are useful, therefore, you can rely on
11272 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11273 LIFO semantics, regardless of the underlying GNU M4 version.
11275 Unlike the GNU M4 builtin, these macros only recognize one
11276 argument, and avoid token pasting between consecutive invocations. On
11277 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11278 work just as in the builtin.
11282 @node Diagnostic Macros
11283 @subsection Diagnostic messages from M4sugar
11284 @cindex Messages, from @command{M4sugar}
11286 When macros statically diagnose abnormal situations, benign or fatal,
11287 they should report them using these macros. For issuing dynamic issues,
11288 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11290 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11292 Assert that the arithmetic @var{expression} evaluates to non-zero.
11293 Otherwise, issue a fatal error, and exit @command{autom4te} with
11297 @defmac m4_errprintn (@var{message})
11298 @msindex{errprintn}
11299 Similar to the builtin @code{m4_errprint}, except that a newline is
11300 guaranteed after @var{message}.
11304 @defmac m4_fatal (@var{message})
11306 Report a severe error @var{message} prefixed with the current location,
11307 and have @command{autom4te} die.
11310 @defmac m4_location
11312 Useful as a prefix in a message line. Short for:
11319 @defmac m4_warn (@var{category}, @var{message})
11321 Report @var{message} as a warning (or as an error if requested by the
11322 user) if warnings of the @var{category} are turned on. If the message
11323 is emitted, it is prefixed with the current location, and followed by a
11324 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11325 current expansion. You are encouraged to use standard categories, which
11330 messages that don't fall into one of the following categories. Use of an
11331 empty @var{category} is equivalent.
11334 related to cross compilation issues.
11337 use of an obsolete construct.
11340 dubious syntactic constructs, incorrectly ordered macro calls.
11345 @node Diversion support
11346 @subsection Diversion support
11348 M4sugar makes heavy use of diversions under the hood, because it is
11349 often the case that
11350 text that must appear early in the output is not discovered until late
11351 in the input. Additionally, some of the topological sorting algorithms
11352 used in resolving macro dependencies use diversions. However, most
11353 macros should not need to change diversions directly, but rather rely on
11354 higher-level M4sugar macros to manage diversions transparently. If you
11355 change diversions improperly, you risk generating a syntactically
11356 invalid script, because an incorrect diversion will violate assumptions
11357 made by many macros about whether prerequisite text has been previously
11358 output. In short, if you manually change the diversion, you should not
11359 expect any macros provided by the Autoconf package to work until you
11360 have restored the diversion stack back to its original state.
11362 In the rare case that it is necessary to write a macro that explicitly
11363 outputs text to a different diversion, it is important to be aware of an
11364 M4 limitation regarding diversions: text only goes to a diversion if it
11365 is not part of argument collection. Therefore, any macro that changes
11366 the current diversion cannot be used as an unquoted argument to another
11367 macro, but must be expanded at the top level. The macro
11368 @code{m4_expand} will diagnose any attempt to change diversions, since
11369 it is generally useful only as an argument to another macro. The
11370 following example shows what happens when diversion manipulation is
11371 attempted within macro arguments:
11374 m4_do([normal text]
11375 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11376 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11377 @result{}normal text
11382 Notice that the unquoted text @code{unwanted} is output, even though it
11383 was processed while the current diversion was @code{KILL}, because it
11384 was collected as part of the argument to @code{m4_do}. However, the
11385 text @code{discarded} disappeared as desired, because the diversion
11386 changes were single-quoted, and were not expanded until the top-level
11387 rescan of the output of @code{m4_do}.
11389 To make diversion management easier, M4sugar uses the concept of named
11390 diversions. Rather than using diversion numbers directly, it is nicer
11391 to associate a name with each diversion. The diversion number associated
11392 with a particular diversion name is an implementation detail, and a
11393 syntax warning is issued if a diversion number is used instead of a
11394 name. In general, you should not output text
11395 to a named diversion until after calling the appropriate initialization
11396 routine for your language (@code{m4_init}, @code{AS_INIT},
11397 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11400 M4sugar defines two named diversions.
11403 Text written to this diversion is discarded. This is the default
11404 diversion once M4sugar is initialized.
11406 This diversion is used behind the scenes by topological sorting macros,
11407 such as @code{AC_REQUIRE}.
11410 M4sh adds several more named diversions.
11413 This diversion is reserved for the @samp{#!} interpreter line.
11414 @item HEADER-REVISION
11415 This diversion holds text from @code{AC_REVISION}.
11416 @item HEADER-COMMENT
11417 This diversion holds comments about the purpose of a file.
11418 @item HEADER-COPYRIGHT
11419 This diversion is managed by @code{AC_COPYRIGHT}.
11420 @item M4SH-SANITIZE
11421 This diversion contains M4sh sanitization code, used to ensure M4sh is
11422 executing in a reasonable shell environment.
11424 This diversion contains M4sh initialization code, initializing variables
11425 that are required by other M4sh macros.
11427 This diversion contains the body of the shell code, and is the default
11428 diversion once M4sh is initialized.
11431 Autotest inherits diversions from M4sh, and changes the default
11432 diversion from @code{BODY} back to @code{KILL}. It also adds several
11433 more named diversions, with the following subset designed for developer
11436 @item PREPARE_TESTS
11437 This diversion contains initialization sequences which are executed
11438 after @file{atconfig} and @file{atlocal}, and after all command line
11439 arguments have been parsed, but prior to running any tests. It can be
11440 used to set up state that is required across all tests. This diversion
11441 will work even before @code{AT_INIT}.
11444 Autoconf inherits diversions from M4sh, and adds the following named
11445 diversions which developers can utilize.
11448 This diversion contains shell variable assignments to set defaults that
11449 must be in place before arguments are parsed. This diversion is placed
11450 early enough in @file{configure} that it is unsafe to expand any
11451 autoconf macros into this diversion.
11453 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11454 diversion will be included as part of a quoted here-doc providing all of
11455 the @option{--help} output of @file{configure} related to options
11456 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11458 This diversion occurs after all command line options have been parsed,
11459 but prior to the main body of the @file{configure} script. This
11460 diversion is the last chance to insert shell code such as variable
11461 assignments or shell function declarations that will used by the
11462 expansion of other macros.
11465 For now, the remaining named diversions of Autoconf, Autoheader, and
11466 Autotest are not documented. In other words,
11467 intentionally outputting text into an undocumented diversion is subject
11468 to breakage in a future release of Autoconf.
11470 @defmac m4_cleardivert (@var{diversion}@dots{})
11471 @msindex{cleardivert}
11472 Permanently discard any text that has been diverted into
11476 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11477 @msindex{divert_once}
11478 Similar to @code{m4_divert_text}, except that @var{content} is only
11479 output to @var{diversion} if this is the first time that
11480 @code{m4_divert_once} has been called with its particular arguments.
11483 @defmac m4_divert_pop (@ovar{diversion})
11484 @msindex{divert_pop}
11485 If provided, check that the current diversion is indeed @var{diversion}.
11486 Then change to the diversion located earlier on the stack, giving an
11487 error if an attempt is made to pop beyond the initial m4sugar diversion
11491 @defmac m4_divert_push (@var{diversion})
11492 @msindex{divert_push}
11493 Remember the former diversion on the diversion stack, and output
11494 subsequent text into @var{diversion}. M4sugar maintains a diversion
11495 stack, and issues an error if there is not a matching pop for every
11499 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11500 @msindex{divert_text}
11501 Output @var{content} and a newline into @var{diversion}, without
11502 affecting the current diversion. Shorthand for:
11504 m4_divert_push([@var{diversion}])@var{content}
11505 m4_divert_pop([@var{diversion}])dnl
11508 One use of @code{m4_divert_text} is to develop two related macros, where
11509 macro @samp{MY_A} does the work, but adjusts what work is performed
11510 based on whether the optional macro @samp{MY_B} has also been expanded.
11511 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11512 require that @samp{MY_B} occurs first, if it occurs at all. But this
11513 imposes an ordering restriction on the user; it would be nicer if macros
11514 @samp{MY_A} and @samp{MY_B} can be invoked in either order. The trick
11515 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
11516 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
11522 if test -n "$b_was_used"; then
11526 [AC_REQUIRE([MY_A])dnl
11527 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
11534 Initialize the M4sugar environment, setting up the default named
11535 diversion to be @code{KILL}.
11538 @node Conditional constructs
11539 @subsection Conditional constructs
11541 The following macros provide additional conditional constructs as
11542 convenience wrappers around @code{m4_if}.
11544 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
11545 @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
11547 The string @var{string} is repeatedly compared against a series of
11548 @var{regex} arguments; if a match is found, the expansion is the
11549 corresponding @var{value}, otherwise, the macro moves on to the next
11550 @var{regex}. If no @var{regex} match, then the result is the optional
11551 @var{default}, or nothing.
11554 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
11555 @ovar{regex-2}, @ovar{subst-2}, @dots{})
11556 @msindex{bpatsubsts}
11557 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
11560 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
11564 The result of the substitution is then passed through the next set of
11565 @var{regex} and @var{subst}, and so forth. An empty @var{subst} implies
11566 deletion of any matched portions in the current string. Note that this
11567 macro over-quotes @var{string}; this behavior is intentional, so that
11568 the result of each step of the recursion remains as a quoted string.
11569 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
11570 will line up with the extra quotations, and not the characters of the
11571 original string. The overquoting is removed after the final
11575 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
11576 @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11578 Test @var{string} against multiple @var{value} possibilities, resulting
11579 in the first @var{if-value} for a match, or in the optional
11580 @var{default}. This is shorthand for:
11582 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
11583 [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
11588 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
11589 @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11591 This macro was introduced in Autoconf 2.62. Similar to @code{m4_if},
11592 except that each @var{test} is expanded only when it is encountered.
11593 This is useful for short-circuiting expensive tests; while @code{m4_if}
11594 requires all its strings to be expanded up front before doing
11595 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
11598 For an example, these two sequences give the same result, but in the
11599 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
11600 version only expands @code{m4_index} once, instead of five times, for
11601 faster computation if this is a common case for @samp{$1}. Notice that
11602 every third argument is unquoted for @code{m4_if}, and quoted for
11606 m4_if(m4_index([$1], [\]), [-1], [$2],
11607 m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
11608 m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
11609 m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
11610 m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
11612 m4_cond([m4_index([$1], [\])], [-1], [$2],
11613 [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
11614 [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
11615 [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
11616 [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
11621 @defmac m4_default (@var{expr-1}, @var{expr-2})
11622 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
11623 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
11624 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
11626 @msindex{default_quoted}
11627 @msindex{default_nblank}
11628 @msindex{default_nblank_quoted}
11629 If @var{expr-1} contains text, use it. Otherwise, select @var{expr-2}.
11630 @code{m4_default} expands the result, while @code{m4_default_quoted}
11631 does not. Useful for providing a fixed default if the expression that
11632 results in @var{expr-1} would otherwise be empty. The difference
11633 between @code{m4_default} and @code{m4_default_nblank} is whether an
11634 argument consisting of just blanks (space, tab, newline) is
11635 significant. When using the expanding versions, note that an argument
11636 may contain text but still expand to an empty string.
11639 m4_define([active], [ACTIVE])dnl
11640 m4_define([empty], [])dnl
11641 m4_define([demo1], [m4_default([$1], [$2])])dnl
11642 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11643 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
11644 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
11645 demo1([active], [default])
11647 demo1([], [active])
11649 demo1([empty], [text])
11651 -demo1([ ], [active])-
11653 demo2([active], [default])
11655 demo2([], [active])
11657 demo2([empty], [text])
11659 -demo2([ ], [active])-
11661 demo3([active], [default])
11663 demo3([], [active])
11665 demo3([empty], [text])
11667 -demo3([ ], [active])-
11669 demo4([active], [default])
11671 demo4([], [active])
11673 demo4([empty], [text])
11675 -demo4([ ], [active])-
11680 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
11681 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
11684 If @var{cond} is empty or consists only of blanks (space, tab, newline),
11685 then expand @var{if-blank}; otherwise, expand @var{if-text}. Two
11686 variants exist, in order to make it easier to select the correct logical
11687 sense when using only two parameters. Note that this is more efficient
11688 than the equivalent behavior of:
11690 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
11694 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11696 This is shorthand for:
11698 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11702 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11704 If @var{macro} is undefined, or is defined as the empty string, expand
11705 to @var{if-false}. Otherwise, expands to @var{if-true}. Similar to:
11707 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11710 except that it is not an error if @var{macro} is undefined.
11713 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11715 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11716 @var{if-false}. This is shorthand for:
11718 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11722 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11724 Similar to @code{m4_ifval}, except guarantee that a newline is present
11725 after any non-empty expansion. Often followed by @code{dnl}.
11728 @defmac m4_n (@var{text})
11730 Expand to @var{text}, and add a newline if @var{text} is not empty.
11731 Often followed by @code{dnl}.
11735 @node Looping constructs
11736 @subsection Looping constructs
11738 The following macros are useful in implementing recursive algorithms in
11739 M4, including loop operations. An M4 list is formed by quoting a list
11740 of quoted elements; generally the lists are comma-separated, although
11741 @code{m4_foreach_w} is whitespace-separated. For example, the list
11742 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11743 It is common to see lists with unquoted elements when those elements are
11744 not likely to be macro names, as in @samp{[fputc_unlocked,
11747 Although not generally recommended, it is possible for quoted lists to
11748 have side effects; all side effects are expanded only once, and prior to
11749 visiting any list element. On the other hand, the fact that unquoted
11750 macros are expanded exactly once means that macros without side effects
11751 can be used to generate lists. For example,
11754 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11757 m4_define([list], [[1], [2], [3]])
11759 m4_foreach([i], [list], [i])
11763 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
11765 Extracts argument @var{n} (larger than 0) from the remaining arguments.
11766 If there are too few arguments, the empty string is used. For any
11767 @var{n} besides 1, this is more efficient than the similar
11768 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
11771 @defmac m4_car (@var{arg}@dots{})
11773 Expands to the quoted first @var{arg}. Can be used with @code{m4_cdr}
11774 to recursively iterate
11775 through a list. Generally, when using quoted lists of quoted elements,
11776 @code{m4_car} should be called without any extra quotes.
11779 @defmac m4_cdr (@var{arg}@dots{})
11781 Expands to a quoted list of all but the first @var{arg}, or the empty
11782 string if there was only one argument. Generally, when using quoted
11783 lists of quoted elements, @code{m4_cdr} should be called without any
11786 For example, this is a simple implementation of @code{m4_map}; note how
11787 each iteration checks for the end of recursion, then merely applies the
11788 first argument to the first element of the list, then repeats with the
11789 rest of the list. (The actual implementation in M4sugar is a bit more
11790 involved, to gain some speed and share code with @code{m4_map_sep}, and
11791 also to avoid expanding side effects in @samp{$2} twice).
11793 m4_define([m4_map], [m4_ifval([$2],
11794 [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11795 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11800 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11803 Loop over the numeric values between @var{first} and @var{last}
11804 including bounds by increments of @var{step}. For each iteration,
11805 expand @var{expression} with the numeric value assigned to @var{var}.
11806 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11807 on the order of the limits. If given, @var{step} has to match this
11808 order. The number of iterations is determined independently from
11809 definition of @var{var}; iteration cannot be short-circuited or
11810 lengthened by modifying @var{var} from within @var{expression}.
11813 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11815 Loop over the comma-separated M4 list @var{list}, assigning each value
11816 to @var{var}, and expand @var{expression}. The following example
11820 m4_foreach([myvar], [[foo], [bar, baz]],
11824 @result{}echo bar, baz
11827 Note that for some forms of @var{expression}, it may be faster to use
11828 @code{m4_map_args}.
11831 @anchor{m4_foreach_w}
11832 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11833 @msindex{foreach_w}
11834 Loop over the white-space-separated list @var{list}, assigning each value
11835 to @var{var}, and expand @var{expression}. If @var{var} is only
11836 referenced once in @var{expression}, it is more efficient to use
11837 @code{m4_map_args_w}.
11839 The deprecated macro @code{AC_FOREACH} is an alias of
11840 @code{m4_foreach_w}.
11843 @defmac m4_map (@var{macro}, @var{list})
11844 @defmacx m4_mapall (@var{macro}, @var{list})
11845 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
11846 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
11850 @msindex{mapall_sep}
11851 Loop over the comma separated quoted list of argument descriptions in
11852 @var{list}, and invoke @var{macro} with the arguments. An argument
11853 description is in turn a comma-separated quoted list of quoted elements,
11854 suitable for @code{m4_apply}. The macros @code{m4_map} and
11855 @code{m4_map_sep} ignore empty argument descriptions, while
11856 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
11857 arguments. The macros @code{m4_map_sep} and @code{m4_mapall_sep}
11858 additionally expand @var{separator} between invocations of @var{macro}.
11860 Note that @var{separator} is expanded, unlike in @code{m4_join}. When
11861 separating output with commas, this means that the map result can be
11862 used as a series of arguments, by using a single-quoted comma as
11863 @var{separator}, or as a single string, by using a double-quoted comma.
11866 m4_map([m4_count], [])
11868 m4_map([ m4_count], [[],
11872 m4_mapall([ m4_count], [[],
11876 m4_map_sep([m4_eval], [,], [[[1+2]],
11879 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
11881 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
11883 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
11885 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
11890 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
11892 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
11893 argument. In the following example, three solutions are presented with
11894 the same expansion; the solution using @code{m4_map_args} is the most
11897 m4_define([active], [ACTIVE])dnl
11898 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
11899 @result{} plain active
11900 m4_map([ m4_echo], [[[plain]], [[active]]])
11901 @result{} plain active
11902 m4_map_args([ m4_echo], [plain], [active])
11903 @result{} plain active
11906 In cases where it is useful to operate on additional parameters besides
11907 the list elements, the macro @code{m4_curry} can be used in @var{macro}
11908 to supply the argument currying necessary to generate the desired
11909 argument list. In the following example, @code{list_add_n} is more
11910 efficient than @code{list_add_x}. On the other hand, using
11911 @code{m4_map_args_sep} can be even more efficient.
11914 m4_define([list], [[1], [2], [3]])dnl
11915 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
11916 dnl list_add_n(N, ARG...)
11917 dnl Output a list consisting of each ARG added to N
11918 m4_define([list_add_n],
11919 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
11920 list_add_n([1], list)
11922 list_add_n([2], list)
11924 m4_define([list_add_x],
11925 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
11926 [,add([$1],m4_defn([var]))]))])dnl
11927 list_add_x([1], list)
11932 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
11934 @msindex{map_args_pair}
11935 For every pair of arguments @var{arg}, invoke @var{macro} with two
11936 arguments. If there is an odd number of arguments, invoke
11937 @var{macro-end}, which defaults to @var{macro}, with the remaining
11941 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
11943 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
11944 @result{}, 2, 1, [3]
11945 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
11946 @result{}, 2, 1, 4, 3
11950 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
11951 @msindex{map_args_sep}
11952 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
11953 argument, additionally expanding @var{sep} between arguments. One
11954 common use of this macro is constructing a macro call, where the opening
11955 and closing parentheses are split between @var{pre} and @var{post}; in
11956 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
11957 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}. This
11958 macro provides the most efficient means for iterating over an arbitrary
11959 list of arguments, particularly when repeatedly constructing a macro
11960 call with more arguments than @var{arg}.
11963 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
11964 @msindex{map_args_w}
11965 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
11966 the whitespace-separated @var{string}, additionally expanding @var{sep}
11967 between words. This macro provides the most efficient means for
11968 iterating over a whitespace-separated string. In particular,
11969 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
11970 efficient than @code{m4_foreach_w([var], [@var{string}],
11971 [@var{action}(m4_defn([var]))])}.
11974 @defmac m4_shiftn (@var{count}, @dots{})
11975 @defmacx m4_shift2 (@dots{})
11976 @defmacx m4_shift3 (@dots{})
11980 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
11981 along with validation that enough arguments were passed in to match the
11982 shift count, and that the count is positive. @code{m4_shift2} and
11983 @code{m4_shift3} are specializations
11984 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
11985 for two and three shifts, respectively.
11988 @defmac m4_stack_foreach (@var{macro}, @var{action})
11989 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
11990 @msindex{stack_foreach}
11991 @msindex{stack_foreach_lifo}
11992 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
11993 @var{action} with the single argument of a definition of @var{macro}.
11994 @code{m4_stack_foreach} starts with the oldest definition, while
11995 @code{m4_stack_foreach_lifo} starts with the current definition.
11996 @var{action} should not push or pop definitions of @var{macro}, nor is
11997 there any guarantee that the current definition of @var{macro} matches
11998 the argument that was passed to @var{action}. The macro @code{m4_curry}
11999 can be used if @var{action} needs more than one argument, although in
12000 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12002 Due to technical limitations, there are a few low-level m4sugar
12003 functions, such as @code{m4_pushdef}, that cannot be used as the
12004 @var{macro} argument.
12007 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12008 m4_stack_foreach([a], [ m4_incr])
12010 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12015 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12016 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12018 @msindex{stack_foreach_sep}
12019 @msindex{stack_foreach_sep_lifo}
12020 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12021 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12022 @var{sep} between definitions. @code{m4_stack_foreach_sep} visits the
12023 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12024 the current definition first. This macro provides the most efficient
12025 means for iterating over a pushdef stack. In particular,
12026 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12027 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12030 @node Evaluation Macros
12031 @subsection Evaluation Macros
12033 The following macros give some control over the order of the evaluation
12034 by adding or removing levels of quotes.
12036 @defmac m4_apply (@var{macro}, @var{list})
12038 Apply the elements of the quoted, comma-separated @var{list} as the
12039 arguments to @var{macro}. If @var{list} is empty, invoke @var{macro}
12040 without arguments. Note the difference between @code{m4_indir}, which
12041 expects its first argument to be a macro name but can use names that are
12042 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12043 other text, but must end in a valid macro name.
12045 m4_apply([m4_count], [])
12047 m4_apply([m4_count], [[]])
12049 m4_apply([m4_count], [[1], [2]])
12051 m4_apply([m4_join], [[|], [1], [2]])
12056 @defmac m4_count (@var{arg}, @dots{})
12058 This macro returns the decimal count of the number of arguments it was
12062 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12064 This macro performs argument currying. The expansion of this macro is
12065 another macro name that expects exactly one argument; that argument is
12066 then appended to the @var{arg} list, and then @var{macro} is expanded
12067 with the resulting argument list.
12070 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12074 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12075 pass the definition of a builtin macro as the argument to the output of
12076 @code{m4_curry}; the empty string is used instead of the builtin token.
12077 This behavior is rectified by using M4 1.6 or newer.
12080 @defmac m4_do (@var{arg}, @dots{})
12082 This macro loops over its arguments and expands each @var{arg} in
12083 sequence. Its main use is for readability; it allows the use of
12084 indentation and fewer @code{dnl} to result in the same expansion. This
12085 macro guarantees that no expansion will be concatenated with subsequent
12086 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12087 @var{arg@dots{}}))}.
12090 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12093 m4_unquote(m4_join([],[a],[b]))c
12095 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12096 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12099 m4_unquote(m4_join([],[a],[b]))c
12104 @defmac m4_dquote (@var{arg}, @dots{})
12106 Return the arguments as a quoted list of quoted arguments.
12107 Conveniently, if there is just one @var{arg}, this effectively adds a
12111 @defmac m4_dquote_elt (@var{arg}, @dots{})
12112 @msindex{dquote_elt}
12113 Return the arguments as a series of double-quoted arguments. Whereas
12114 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12115 as many arguments as it was passed.
12118 @defmac m4_echo (@var{arg}, @dots{})
12120 Return the arguments, with the same level of quoting. Other than
12121 discarding whitespace after unquoted commas, this macro is a no-op.
12124 @defmac m4_expand (@var{arg})
12126 Return the expansion of @var{arg} as a quoted string. Whereas
12127 @code{m4_quote} is designed to collect expanded text into a single
12128 argument, @code{m4_expand} is designed to perform one level of expansion
12129 on quoted text. One distinction is in the treatment of whitespace
12130 following a comma in the original @var{arg}. Any time multiple
12131 arguments are collected into one with @code{m4_quote}, the M4 argument
12132 collection rules discard the whitespace. However, with @code{m4_expand},
12133 whitespace is preserved, even after the expansion of macros contained in
12134 @var{arg}. Additionally, @code{m4_expand} is able to expand text that
12135 would involve an unterminated comment, whereas expanding that same text
12136 as the argument to @code{m4_quote} runs into difficulty in finding the
12137 end of the argument. Since manipulating diversions during argument
12138 collection is inherently unsafe, @code{m4_expand} issues an error if
12139 @var{arg} attempts to change the current diversion (@pxref{Diversion
12143 m4_define([active], [ACT, IVE])dnl
12144 m4_define([active2], [[ACT, IVE]])dnl
12145 m4_quote(active, active)
12146 @result{}ACT,IVE,ACT,IVE
12147 m4_expand([active, active])
12148 @result{}ACT, IVE, ACT, IVE
12149 m4_quote(active2, active2)
12150 @result{}ACT, IVE,ACT, IVE
12151 m4_expand([active2, active2])
12152 @result{}ACT, IVE, ACT, IVE
12153 m4_expand([# m4_echo])
12155 m4_quote(# m4_echo)
12157 @result{}# m4_echo)
12161 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12162 literal unbalanced quotes, but that quadrigraphs can be used when
12163 unbalanced output is necessary. Likewise, unbalanced parentheses should
12164 be supplied with double quoting or a quadrigraph.
12167 m4_define([pattern], [[!@@<:@@]])dnl
12168 m4_define([bar], [BAR])dnl
12169 m4_expand([case $foo in
12170 m4_defn([pattern])@@:@}@@ bar ;;
12173 @result{}case $foo in
12174 @result{} [![]) BAR ;;
12175 @result{} *) blah ;;
12180 @defmac m4_ignore (@dots{})
12182 This macro was introduced in Autoconf 2.62. Expands to nothing,
12183 ignoring all of its arguments. By itself, this isn't very useful.
12184 However, it can be used to conditionally ignore an arbitrary number of
12185 arguments, by deciding which macro name to apply to a list of arguments.
12187 dnl foo outputs a message only if [debug] is defined.
12189 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12192 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12193 serve the same purpose, although it is less readable.
12196 @defmac m4_make_list (@var{arg}, @dots{})
12197 @msindex{make_list}
12198 This macro exists to aid debugging of M4sugar algorithms. Its net
12199 effect is similar to @code{m4_dquote}---it produces a quoted list of
12200 quoted arguments, for each @var{arg}. The difference is that this
12201 version uses a comma-newline separator instead of just comma, to improve
12202 readability of the list; with the result that it is less efficient than
12205 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12206 m4_dquote(zero, [one], [[two]])
12207 @result{}[0],[one],[[two]]
12208 m4_make_list(zero, [one], [[two]])
12212 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12214 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12219 @c m4_noquote is too dangerous to document - it invokes macros that
12220 @c probably rely on @samp{[]} nested quoting for proper operation. The
12221 @c user should generally prefer m4_unquote instead.
12223 @defmac m4_quote (@var{arg}, @dots{})
12225 Return the arguments as a single entity, i.e., wrap them into a pair of
12226 quotes. This effectively collapses multiple arguments into one,
12227 although it loses whitespace after unquoted commas in the process.
12230 @defmac m4_reverse (@var{arg}, @dots{})
12232 Outputs each argument with the same level of quoting, but in reverse
12233 order, and with space following each comma for readability.
12236 m4_define([active], [ACT,IVE])
12238 m4_reverse(active, [active])
12239 @result{}active, IVE, ACT
12243 @defmac m4_unquote (@var{arg}, @dots{})
12245 This macro was introduced in Autoconf 2.62. Expand each argument,
12246 separated by commas. For a single @var{arg}, this effectively removes a
12247 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12248 than the equivalent @code{m4_do([@var{arg}])}. For multiple arguments,
12249 this results in an unquoted list of expansions. This is commonly used
12250 with @code{m4_split}, in order to convert a single quoted list into a
12251 series of quoted elements.
12254 The following example aims at emphasizing the difference between several
12255 scenarios: not using these macros, using @code{m4_defn}, using
12256 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12259 $ @kbd{cat example.m4}
12260 dnl Overquote, so that quotes are visible.
12261 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12262 m4_define([a], [A])
12263 m4_define([mkargs], [1, 2[,] 3])
12264 m4_define([arg1], [[$1]])
12268 show(m4_quote(a, b))
12269 show(m4_dquote(a, b))
12270 show(m4_expand([a, b]))
12274 arg1(m4_defn([mkargs]))
12275 arg1(m4_quote(mkargs))
12276 arg1(m4_dquote(mkargs))
12277 arg1(m4_expand([mkargs]))
12278 $ @kbd{autom4te -l m4sugar example.m4}
12279 $1 = A, $@@ = [A],[b]
12280 $1 = a, b, $@@ = [a, b]
12281 $1 = A,b, $@@ = [A,b]
12282 $1 = [A],[b], $@@ = [[A],[b]]
12283 $1 = A, b, $@@ = [A, b]
12294 @node Text processing Macros
12295 @subsection String manipulation in M4
12297 The following macros may be used to manipulate strings in M4. Many of
12298 the macros in this section intentionally result in quoted strings as
12299 output, rather than subjecting the arguments to further expansions. As
12300 a result, if you are manipulating text that contains active M4
12301 characters, the arguments are passed with single quoting rather than
12304 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12305 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12306 @ovar{if-uniq}, @ovar{if-duplicate})
12308 @msindex{append_uniq}
12309 Redefine @var{macro-name} to its former contents with @var{separator}
12310 and @var{string} added at the end. If @var{macro-name} was undefined
12311 before (but not if it was defined but empty), then no @var{separator} is
12312 added. As of Autoconf 2.62, neither @var{string} nor @var{separator}
12313 are expanded during this macro; instead, they are expanded when
12314 @var{macro-name} is invoked.
12316 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12317 to grow strings without duplicating substrings. Additionally,
12318 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12319 @var{if-uniq} is expanded if @var{string} was appended, and
12320 @var{if-duplicate} is expanded if @var{string} was already present.
12321 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12322 occurs within @var{string}, since that can lead to duplicates.
12324 Note that @code{m4_append} can scale linearly in the length of the final
12325 string, depending on the quality of the underlying M4 implementation,
12326 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12327 If an algorithm can tolerate duplicates in the final string, use the
12328 former for speed. If duplicates must be avoided, consider using
12329 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12332 m4_define([active], [ACTIVE])dnl
12333 m4_append([sentence], [This is an])dnl
12334 m4_append([sentence], [ active ])dnl
12335 m4_append([sentence], [symbol.])dnl
12337 @result{}This is an ACTIVE symbol.
12338 m4_undefine([active])dnl
12339 @result{}This is an active symbol.
12340 m4_append_uniq([list], [one], [, ], [new], [existing])
12342 m4_append_uniq([list], [one], [, ], [new], [existing])
12344 m4_append_uniq([list], [two], [, ], [new], [existing])
12346 m4_append_uniq([list], [three], [, ], [new], [existing])
12348 m4_append_uniq([list], [two], [, ], [new], [existing])
12351 @result{}one, two, three
12353 @result{}[one],[two],[three]
12354 m4_append([list2], [one], [[, ]])dnl
12355 m4_append_uniq([list2], [two], [[, ]])dnl
12356 m4_append([list2], [three], [[, ]])dnl
12358 @result{}one, two, three
12360 @result{}[one, two, three]
12364 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12365 @msindex{append_uniq_w}
12366 This macro was introduced in Autoconf 2.62. It is similar to
12367 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12368 separated list of words to append, and only appends unique words.
12369 @var{macro-name} is updated with a single space between new words.
12371 m4_append_uniq_w([numbers], [1 1 2])dnl
12372 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12378 @defmac m4_chomp (@var{string})
12379 @defmacx m4_chomp_all (@var{string})
12381 @msindex{chomp_all}
12382 Output @var{string} in quotes, but without a trailing newline. The
12383 macro @code{m4_chomp} is slightly faster, and removes at most one
12384 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12385 newlines. Unlike @code{m4_flatten}, embedded newlines are left intact,
12386 and backslash does not influence the result.
12389 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12390 @var{suffix-1}, @ovar{suffix-2}, @dots{})
12392 This macro produces a quoted string containing the pairwise combination
12393 of every element of the quoted, comma-separated @var{prefix-list}, and
12394 every element from the @var{suffix} arguments. Each pairwise
12395 combination is joined with @var{infix} in the middle, and successive
12396 pairs are joined by @var{separator}. No expansion occurs on any of the
12397 arguments. No output occurs if either the @var{prefix} or @var{suffix}
12398 list is empty, but the lists can contain empty elements.
12400 m4_define([a], [oops])dnl
12401 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12402 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12403 m4_combine([, ], [[a], [b]], [-])
12405 m4_combine([, ], [[a], [b]], [-], [])
12407 m4_combine([, ], [], [-], [1], [2])
12409 m4_combine([, ], [[]], [-], [1], [2])
12414 @defmac m4_escape (@var{string})
12416 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12417 within @var{string} into their respective quadrigraphs. The result is
12418 still a quoted string.
12421 @defmac m4_flatten (@var{string})
12423 Flatten @var{string} into a single line. Delete all backslash-newline
12424 pairs, and replace all remaining newlines with a space. The result is
12425 still a quoted string.
12428 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12429 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12432 Concatenate each @var{arg}, separated by @var{separator}.
12433 @code{joinall} uses every argument, while @code{join} omits empty
12434 arguments so that there are no back-to-back separators in the output.
12435 The result is a quoted string.
12437 m4_define([active], [ACTIVE])dnl
12438 m4_join([|], [one], [], [active], [two])
12439 @result{}one|active|two
12440 m4_joinall([|], [one], [], [active], [two])
12441 @result{}one||active|two
12444 Note that if all you intend to do is join @var{args} with commas between
12445 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12446 efficient to use @code{m4_dquote}.
12449 @defmac m4_newline (@ovar{text})
12451 This macro was introduced in Autoconf 2.62, and expands to a newline,
12452 followed by any @var{text}.
12453 It is primarily useful for maintaining macro formatting, and ensuring
12454 that M4 does not discard leading whitespace during argument collection.
12457 @defmac m4_normalize (@var{string})
12458 @msindex{normalize}
12459 Remove leading and trailing spaces and tabs, sequences of
12460 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12461 with a single space. This is a combination of @code{m4_flatten} and
12462 @code{m4_strip}. To determine if @var{string} consists only of bytes
12463 that would be removed by @code{m4_normalize}, you can use
12467 @defmac m4_re_escape (@var{string})
12468 @msindex{re_escape}
12469 Backslash-escape all characters in @var{string} that are active in
12473 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
12475 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12476 @samp{]}, while keeping white space at the beginning and at the end.
12477 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12478 If @var{string} is empty, the result is an empty list.
12481 @defmac m4_strip (@var{string})
12483 Strip whitespace from @var{string}. Sequences of spaces and tabs are
12484 reduced to a single space, then leading and trailing spaces are removed.
12485 The result is still a quoted string. Note that this does not interfere
12486 with newlines; if you want newlines stripped as well, consider
12487 @code{m4_flatten}, or do it all at once with @code{m4_normalize}. To
12488 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12491 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12493 Add a text box around @var{message}, using @var{frame} as the border
12494 character above and below the message. The frame correctly accounts for
12495 the subsequent expansion of @var{message}. For example:
12497 m4_define([macro], [abc])dnl
12498 m4_text_box([macro])
12504 The @var{message} must contain balanced quotes and parentheses, although
12505 quadrigraphs can be used to work around this.
12508 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
12509 @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
12510 @msindex{text_wrap}
12511 Break @var{string} into a series of whitespace-separated words, then
12512 output those words separated by spaces, and wrapping lines any time the
12513 output would exceed @var{width} columns. If given, @var{prefix1} begins
12514 the first line, and @var{prefix} begins all wrapped lines. If
12515 @var{prefix1} is longer than @var{prefix}, then the first line consists
12516 of just @var{prefix1}. If @var{prefix} is longer than @var{prefix1},
12517 padding is inserted so that the first word of @var{string} begins at the
12518 same indentation as all wrapped lines. Note that using literal tab
12519 characters in any of the arguments will interfere with the calculation
12520 of width. No expansions occur on @var{prefix}, @var{prefix1}, or the
12521 words of @var{string}, although quadrigraphs are recognized.
12525 m4_text_wrap([Short string */], [ ], [/* ], [20])
12526 @result{}/* Short string */
12527 m4_text_wrap([Much longer string */], [ ], [/* ], [20])
12528 @result{}/* Much longer
12529 @result{} string */
12530 m4_text_wrap([Short doc.], [ ], [ --short ], [30])
12531 @result{} --short Short doc.
12532 m4_text_wrap([Short doc.], [ ], [ --too-wide ], [30])
12533 @result{} --too-wide
12534 @result{} Short doc.
12535 m4_text_wrap([Super long documentation.], [ ],
12536 [ --too-wide ], 30)
12537 @result{} --too-wide
12538 @result{} Super long
12539 @result{} documentation.
12543 @defmac m4_tolower (@var{string})
12544 @defmacx m4_toupper (@var{string})
12547 Return @var{string} with letters converted to upper or lower case,
12551 @node Number processing Macros
12552 @subsection Arithmetic computation in M4
12554 The following macros facilitate integer arithmetic operations.
12555 Where a parameter is documented as taking an arithmetic expression, you
12556 can use anything that can be parsed by @code{m4_eval}.
12558 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
12560 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
12561 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
12562 equal, and @samp{1} if @var{expr-1} is larger.
12565 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
12567 Compare the two M4 lists consisting of comma-separated arithmetic
12568 expressions, left to right. Expand to @samp{-1} for the first element
12569 pairing where the value from @var{list-1} is smaller, @samp{1} where the
12570 value from @var{list-2} is smaller, or @samp{0} if both lists have the
12571 same values. If one list is shorter than the other, the remaining
12572 elements of the longer list are compared against zero.
12574 m4_list_cmp([1, 0], [1])
12576 m4_list_cmp([1, [1 * 0]], [1, 0])
12578 m4_list_cmp([1, 2], [1, 0])
12580 m4_list_cmp([1, [1+1], 3],[1, 2])
12582 m4_list_cmp([1, 2, -3], [1, 2])
12584 m4_list_cmp([1, 0], [1, 2])
12586 m4_list_cmp([1], [1, 2])
12591 @defmac m4_max (@var{arg}, @dots{})
12593 This macro was introduced in Autoconf 2.62. Expand to the decimal value
12594 of the maximum arithmetic expression among all the arguments.
12597 @defmac m4_min (@var{arg}, @dots{})
12599 This macro was introduced in Autoconf 2.62. Expand to the decimal value
12600 of the minimum arithmetic expression among all the arguments.
12603 @defmac m4_sign (@var{expr})
12605 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
12606 @samp{1} if it is positive, and @samp{0} if it is zero.
12609 @anchor{m4_version_compare}
12610 @defmac m4_version_compare (@var{version-1}, @var{version-2})
12611 @msindex{version_compare}
12612 This macro was introduced in Autoconf 2.53, but had a number of
12613 usability limitations that were not lifted until Autoconf 2.62. Compare
12614 the version strings @var{version-1} and @var{version-2}, and expand to
12615 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
12616 or @samp{1} @var{version-2} is smaller. Version strings must be a list
12617 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
12618 element is a number along with optional case-insensitive letters
12619 designating beta releases. The comparison stops at the leftmost element
12620 that contains a difference, although a 0 element compares equal to a
12623 It is permissible to include commit identifiers in @var{version}, such
12624 as an abbreviated SHA1 of the commit, provided there is still a
12625 monotonically increasing prefix to allow for accurate version-based
12626 comparisons. For example, this paragraph was written when the
12627 development snapshot of autoconf claimed to be at version
12628 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
12629 abbreviated commit identification of @samp{dc51}.
12632 m4_version_compare([1.1], [2.0])
12634 m4_version_compare([2.0b], [2.0a])
12636 m4_version_compare([1.1.1], [1.1.1a])
12638 m4_version_compare([1.2], [1.1.1a])
12640 m4_version_compare([1.0], [1])
12642 m4_version_compare([1.1pre], [1.1PRE])
12644 m4_version_compare([1.1a], [1,10])
12646 m4_version_compare([2.61a], [2.61a-248-dc51])
12648 m4_version_compare([2.61b], [2.61a-248-dc51])
12653 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
12654 @dvar{if-old, m4_fatal})
12655 @msindex{version_prereq}
12656 Compares @var{version} against the version of Autoconf currently
12657 running. If the running version is at @var{version} or newer, expand
12658 @var{if-new-enough}, but if @var{version} is larger than the version
12659 currently executing, expand @var{if-old}, which defaults to printing an
12660 error message and exiting m4sugar with status 63. When given only one
12661 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
12662 Remember that the autoconf philosophy favors feature checks over version
12666 @node Set manipulation Macros
12667 @subsection Set manipulation in M4
12668 @cindex Set manipulation
12669 @cindex Data structure, set
12670 @cindex Unordered set manipulation
12672 Sometimes, it is necessary to track a set of data, where the order does
12673 not matter and where there are no duplicates in the set. The following
12674 macros facilitate set manipulations. Each set is an opaque object,
12675 which can only be accessed via these basic operations. The underlying
12676 implementation guarantees linear scaling for set creation, which is more
12677 efficient than using the quadratic @code{m4_append_uniq}. Both set
12678 names and values can be arbitrary strings, except for unbalanced quotes.
12679 This implementation ties up memory for removed elements until the next
12680 operation that must traverse all the elements of a set; and although
12681 that may slow down some operations until the memory for removed elements
12682 is pruned, it still guarantees linear performance.
12684 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
12686 Adds the string @var{value} as a member of set @var{set}. Expand
12687 @var{if-uniq} if the element was added, or @var{if-dup} if it was
12688 previously in the set. Operates in amortized constant time, so that set
12689 creation scales linearly.
12692 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
12693 @msindex{set_add_all}
12694 Adds each @var{value} to the set @var{set}. This is slightly more
12695 efficient than repeatedly invoking @code{m4_set_add}.
12698 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
12700 @msindex{set_contains}
12701 Expands @var{if-present} if the string @var{value} is a member of
12702 @var{set}, otherwise @var{if-absent}.
12705 m4_set_contains([a], [1], [yes], [no])
12707 m4_set_add([a], [1], [added], [dup])
12709 m4_set_add([a], [1], [added], [dup])
12711 m4_set_contains([a], [1], [yes], [no])
12713 m4_set_remove([a], [1], [removed], [missing])
12715 m4_set_contains([a], [1], [yes], [no])
12717 m4_set_remove([a], [1], [removed], [missing])
12722 @defmac m4_set_contents (@var{set}, @ovar{sep})
12723 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12724 @msindex{set_contents}
12726 Expands to a single string consisting of all the members of the set
12727 @var{set}, each separated by @var{sep}, which is not expanded.
12728 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12729 memory occupied by removed elements, while @code{m4_set_dump} is a
12730 faster one-shot action that also deletes the set. No provision is made
12731 for disambiguating members that contain a non-empty @var{sep} as a
12732 substring; use @code{m4_set_empty} to distinguish between an empty set
12733 and the set containing only the empty string. The order of the output
12734 is unspecified; in the current implementation, part of the speed of
12735 @code{m4_set_dump} results from using a different output order than
12736 @code{m4_set_contents}. These macros scale linearly in the size of the
12737 set before memory pruning, and @code{m4_set_contents([@var{set}],
12738 [@var{sep}])} is faster than
12739 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12742 m4_set_add_all([a], [1], [2], [3])
12744 m4_set_contents([a], [-])
12746 m4_joinall([-]m4_set_listc([a]))
12748 m4_set_dump([a], [-])
12750 m4_set_contents([a])
12752 m4_set_add([a], [])
12754 m4_set_contents([a], [-])
12759 @defmac m4_set_delete (@var{set})
12760 @msindex{set_delete}
12761 Delete all elements and memory associated with @var{set}. This is
12762 linear in the set size, and faster than removing one element at a time.
12765 @defmac m4_set_difference (@var{seta}, @var{setb})
12766 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12767 @defmacx m4_set_union (@var{seta}, @var{setb})
12768 @msindex{set_difference}
12769 @msindex{set_intersection}
12770 @msindex{set_union}
12771 Compute the relation between @var{seta} and @var{setb}, and output the
12772 result as a list of quoted arguments without duplicates and with a
12773 leading comma. Set difference selects the elements in @var{seta} but
12774 not @var{setb}, intersection selects only elements in both sets, and
12775 union selects elements in either set. These actions are linear in the
12776 sum of the set sizes. The leading comma is necessary to distinguish
12777 between no elements and the empty string as the only element.
12780 m4_set_add_all([a], [1], [2], [3])
12782 m4_set_add_all([b], [3], [], [4])
12784 m4_set_difference([a], [b])
12786 m4_set_difference([b], [a])
12788 m4_set_intersection([a], [b])
12790 m4_set_union([a], [b])
12795 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12796 @msindex{set_empty}
12797 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12798 expand @var{if-elements}. This macro operates in constant time. Using
12799 this macro can help disambiguate output from @code{m4_set_contents} or
12800 @code{m4_set_list}.
12803 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12804 @msindex{set_foreach}
12805 For each element in the set @var{set}, expand @var{action} with the
12806 macro @var{variable} defined as the set element. Behavior is
12807 unspecified if @var{action} recursively lists the contents of @var{set}
12808 (although listing other sets is acceptable), or if it modifies the set
12809 in any way other than removing the element currently contained in
12810 @var{variable}. This macro is faster than the corresponding
12811 @code{m4_foreach([@var{variable}],
12812 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12813 although @code{m4_set_map} might be faster still.
12816 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12818 m4_set_contents([a])
12820 m4_set_foreach([a], [i],
12821 [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12823 m4_set_contents([a])
12828 @defmac m4_set_list (@var{set})
12829 @defmacx m4_set_listc (@var{set})
12831 @msindex{set_listc}
12832 Produce a list of arguments, where each argument is a quoted element
12833 from the set @var{set}. The variant @code{m4_set_listc} is unambiguous,
12834 by adding a leading comma if there are any set elements, whereas the
12835 variant @code{m4_set_list} cannot distinguish between an empty set and a
12836 set containing only the empty string. These can be directly used in
12837 macros that take multiple arguments, such as @code{m4_join} or
12838 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
12839 take a quoted list, such as @code{m4_map} or @code{m4_foreach}. Any
12840 memory occupied by removed elements is reclaimed during these macros.
12843 m4_set_add_all([a], [1], [2], [3])
12851 m4_count(m4_set_list([b]))
12853 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12855 m4_set_add([b], [])
12861 m4_count(m4_set_list([b]))
12863 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12868 @defmac m4_set_map (@var{set}, @var{action})
12870 For each element in the set @var{set}, expand @var{action} with a single
12871 argument of the set element. Behavior is unspecified if @var{action}
12872 recursively lists the contents of @var{set} (although listing other sets
12873 is acceptable), or if it modifies the set in any way other than removing
12874 the element passed as an argument. This macro is faster than either
12875 corresponding counterpart of
12876 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
12877 @code{m4_set_foreach([@var{set}], [var],
12878 [@var{action}(m4_defn([var]))])}. It is possible to use @code{m4_curry}
12879 if more than one argument is needed for @var{action}, although it is
12880 more efficient to use @code{m4_set_map_sep} in that case.
12883 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
12884 @msindex{set_map_sep}
12885 For each element in the set @var{set}, expand
12886 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
12887 between elements. Behavior is unspecified if the expansion recursively
12888 lists the contents of @var{set} (although listing other sets
12889 is acceptable), or if it modifies the set in any way other than removing
12890 the element visited by the expansion. This macro provides the most
12891 efficient means for non-destructively visiting the elements of a set; in
12892 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
12893 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
12896 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
12898 @msindex{set_remove}
12899 If @var{value} is an element in the set @var{set}, then remove it and
12900 expand @var{if-present}. Otherwise expand @var{if-absent}. This macro
12901 operates in constant time so that multiple removals will scale linearly
12902 rather than quadratically; but when used outside of
12903 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
12904 until the set is later
12905 compacted by @code{m4_set_contents} or @code{m4_set_list}. Several
12906 other set operations are then less efficient between the time of element
12907 removal and subsequent memory compaction, but still maintain their
12908 guaranteed scaling performance.
12911 @defmac m4_set_size (@var{set})
12913 Expand to the size of the set @var{set}. This implementation operates
12914 in constant time, and is thus more efficient than
12915 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
12919 @node Forbidden Patterns
12920 @subsection Forbidden Patterns
12921 @cindex Forbidden patterns
12922 @cindex Patterns, forbidden
12924 M4sugar provides a means to define suspicious patterns, patterns
12925 describing tokens which should not be found in the output. For
12926 instance, if an Autoconf @file{configure} script includes tokens such as
12927 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
12928 wrong (typically a macro was not evaluated because of overquotation).
12930 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
12931 Additional layers, such as M4sh and Autoconf, add additional forbidden
12932 patterns to the list.
12934 @defmac m4_pattern_forbid (@var{pattern})
12935 @msindex{pattern_forbid}
12936 Declare that no token matching @var{pattern} must be found in the output.
12937 Comments are not checked; this can be a problem if, for instance, you
12938 have some macro left unexpanded after an @samp{#include}. No consensus
12939 is currently found in the Autoconf community, as some people consider it
12940 should be valid to name macros in comments (which doesn't make sense to
12941 the authors of this documentation: input, such as macros, should be
12942 documented by @samp{dnl} comments; reserving @samp{#}-comments to
12943 document the output).
12946 Of course, you might encounter exceptions to these generic rules, for
12947 instance you might have to refer to @samp{$m4_flags}.
12949 @defmac m4_pattern_allow (@var{pattern})
12950 @msindex{pattern_allow}
12951 Any token matching @var{pattern} is allowed, including if it matches an
12952 @code{m4_pattern_forbid} pattern.
12955 @node Debugging via autom4te
12956 @section Debugging via autom4te
12957 @cindex debugging tips
12958 @cindex autom4te debugging tips
12959 @cindex m4sugar debugging tips
12960 At times, it is desirable to see what was happening inside m4, to see
12961 why output was not matching expectations. However, post-processing done
12962 by @command{autom4te} means that directly using the m4 builtin
12963 @code{m4_traceon} is likely to interfere with operation. Also, frequent
12964 diversion changes and the concept of forbidden tokens make it difficult
12965 to use @code{m4_defn} to generate inline comments in the final output.
12967 There are a couple of tools to help with this. One is the use of the
12968 @option{--trace} option provided by @command{autom4te} (as well as each
12969 of the programs that wrap @command{autom4te}, such as
12970 @command{autoconf}), in order to inspect when a macro is called and with
12971 which arguments. For example, when this paragraph was written, the
12972 autoconf version could be found by:
12975 $ @kbd{autoconf --trace=AC_INIT}
12976 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
12977 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
12978 version is 2.63b.95-3963
12981 Another trick is to print out the expansion of various m4 expressions to
12982 standard error or to an independent file, with no further m4 expansion,
12983 and without interfering with diversion changes or the post-processing
12984 done to standard output. @code{m4_errprintn} shows a given expression
12985 on standard error. For example, if you want to see the expansion of an
12986 autoconf primitive or of one of your autoconf macros, you can do it like
12990 $ @kbd{cat <<\EOF > configure.ac}
12992 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
12993 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
12997 @error{}The definition of AC_DEFINE_UNQUOTED:
12998 @error{}_AC_DEFINE_Q([], $@@)
13001 @node Programming in M4sh
13002 @chapter Programming in M4sh
13004 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13005 scripts. This name was coined by Lars J. Aas, who notes that,
13006 according to the Webster's Revised Unabridged Dictionary (1913):
13009 Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische, mash,
13010 wash, and prob.@: to AS. miscian to mix. See ``Mix''.]
13014 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13018 A mixture of meal or bran and water fed to animals.
13021 A mess; trouble. [Obs.] --Beau.@: & Fl.
13025 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13026 the namespace @samp{^AS_} for M4sh macros. It also reserves the shell
13027 and environment variable namespace @samp{^as_}, and the here-document
13028 delimiter namespace @samp{^_AS[A-Z]} in the output file. You should not
13029 define your own macros or output shell code that conflicts with these
13033 * Common Shell Constructs:: Portability layer for common shell constructs
13034 * Polymorphic Variables:: Support for indirect variable names
13035 * Initialization Macros:: Macros to establish a sane shell environment
13036 * File Descriptor Macros:: File descriptor macros for input and output
13039 @node Common Shell Constructs
13040 @section Common Shell Constructs
13042 M4sh provides portable alternatives for some common shell constructs
13043 that unfortunately are not portable in practice.
13045 @c Deprecated, to be replaced by a better API
13047 @defmac AS_BASENAME (@var{file-name})
13049 Output the non-directory portion of @var{file-name}. For example,
13050 if @code{$file} is @samp{/one/two/three}, the command
13051 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13055 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13056 @dots{}, @ovar{default})
13058 Expand into a shell @samp{case} statement, where @var{word} is matched
13059 against one or more patterns. @var{if-matched} is run if the
13060 corresponding pattern matched @var{word}, else @var{default} is run.
13061 Avoids several portability issues (@pxref{case, , Limitations of Shell
13065 @c Deprecated, to be replaced by a better API
13066 @defmac AS_DIRNAME (@var{file-name})
13068 Output the directory portion of @var{file-name}. For example,
13069 if @code{$file} is @samp{/one/two/three}, the command
13070 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13072 This interface may be improved in the future to avoid forks and losing
13076 @defmac AS_ECHO (@var{word})
13078 Emits @var{word} to the standard output, followed by a newline. @var{word}
13079 must be a single shell word (typically a quoted string). The bytes of
13080 @var{word} are output as-is, even if it starts with "-" or contains "\".
13081 Redirections can be placed outside the macro invocation. This is much
13082 more portable than using @command{echo} (@pxref{echo, , Limitations of
13086 @defmac AS_ECHO_N (@var{word})
13088 Emits @var{word} to the standard output, without a following newline.
13089 @var{word} must be a single shell word (typically a quoted string) and,
13090 for portability, should not include more than one newline. The bytes of
13091 @var{word} are output as-is, even if it starts with "-" or contains "\".
13092 Redirections can be placed outside the macro invocation.
13095 @defmac AS_ESCAPE (@var{string}, @dvar{chars, `\"$})
13097 Expands to @var{string}, with any characters in @var{chars} escaped with
13098 a backslash (@samp{\}). @var{chars} should be at most four bytes long,
13099 and only contain characters from the set @samp{`\"$}; however,
13100 characters may be safely listed more than once in @var{chars} for the
13101 sake of syntax highlighting editors. The current implementation expands
13102 @var{string} after adding escapes; if @var{string} contains macro calls
13103 that in turn expand to text needing shell quoting, you can use
13104 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13106 The default for @var{chars} (@samp{\"$`}) is the set of characters
13107 needing escapes when @var{string} will be used literally within double
13108 quotes. One common variant is the set of characters to protect when
13109 @var{string} will be used literally within back-ticks or an unquoted
13110 here-document (@samp{\$`}). Another common variant is @samp{""}, which can
13111 be used to form a double-quoted string containing the same expansions
13112 that would have occurred if @var{string} were expanded in an unquoted
13113 here-document; however, when using this variant, care must be taken that
13114 @var{string} does not use double quotes within complex variable
13115 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13116 with improper escapes.
13118 This macro is often used with @code{AS_ECHO}. For an example, observe
13119 the output generated by the shell code generated from this snippet:
13123 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13124 @result{}"$foo" = "bar"
13125 m4_define([macro], [a, [\b]])
13126 AS_ECHO(["AS_ESCAPE([[macro]])"])
13128 AS_ECHO(["AS_ESCAPE([macro])"])
13130 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13134 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13135 @comment the case of @var{string} that does not contain '.
13136 To escape a string that will be placed within single quotes, use:
13139 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13143 @defmac AS_EXIT (@dvar{status, $?})
13145 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13147 works around shells that see the exit status of the command prior to
13148 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13149 of Shell Builtins}).
13152 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13154 Run shell code @var{test1}. If @var{test1} exits with a zero status then
13155 run shell code @var{run-if-true1}, else examine further tests. If no test
13156 exits with a zero status, run shell code @var{run-if-false}, with
13157 simplifications if either @var{run-if-true1} or @var{run-if-false}
13158 is empty. For example,
13161 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13162 [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13163 [echo foo not specified])
13167 ensures any required macros of @code{HANDLE_FOO}
13168 are expanded before the first test.
13171 @defmac AS_MKDIR_P (@var{file-name})
13173 Make the directory @var{file-name}, including intervening directories
13174 as necessary. This is equivalent to @samp{mkdir -p -- @var{file-name}},
13175 except that it is portable to older versions of @command{mkdir} that
13176 lack support for the @option{-p} option or for the @option{--}
13177 delimiter (@pxref{mkdir, , Limitations of Usual Tools}). Also,
13179 succeeds if @var{file-name} is a symbolic link to an existing directory,
13180 even though Posix is unclear whether @samp{mkdir -p} should
13181 succeed in that case. If creation of @var{file-name} fails, exit the
13184 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13187 @defmac AS_SET_STATUS (@var{status})
13188 @asindex{SET_STATUS}
13189 Emit shell code to set the value of @samp{$?} to @var{status}, as
13190 efficiently as possible. However, this is not guaranteed to abort a
13191 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13192 Builtins}). This should also be used at the end of a complex shell
13193 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13197 @defmac AS_TR_CPP (@var{expression})
13199 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13203 # This outputs "#define HAVE_CHAR_P 1".
13204 # Notice the m4 quoting around #, to prevent an m4 comment
13206 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13210 @defmac AS_TR_SH (@var{expression})
13212 Transform @var{expression} into shell code that generates a valid shell
13213 variable name. The result is literal when possible at m4 time, but must
13214 be used with @code{eval} if @var{expression} causes shell indirections.
13218 # This outputs "Have it!".
13219 header="sys/some file.h"
13220 eval AS_TR_SH([HAVE_$header])=yes
13221 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13225 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13226 @asindex{SET_CATFILE}
13227 Set the shell variable @var{var} to @var{dir}/@var{file}, but
13228 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13229 @var{file} is absolute, etc.).
13232 @defmac AS_UNSET (@var{var})
13234 Unsets the shell variable @var{var}, working around bugs in older
13235 shells (@pxref{unset, , Limitations of Shell
13236 Builtins}). @var{var} can be a literal or indirect variable name.
13239 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13240 @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13241 @asindex{VERSION_COMPARE}
13242 Compare two strings @var{version-1} and @var{version-2}, possibly
13243 containing shell variables, as version strings, and expand
13244 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13245 depending upon the result.
13246 The algorithm to compare is similar to the one used by strverscmp in
13247 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13248 The GNU C Library}).
13251 @node Polymorphic Variables
13252 @section Support for indirect variable names
13253 @cindex variable name indirection
13254 @cindex polymorphic variable name
13255 @cindex indirection, variable name
13257 Often, it is convenient to write a macro that will emit shell code
13258 operating on a shell variable. The simplest case is when the variable
13259 name is known. But a more powerful idiom is writing shell code that can
13260 work through an indirection, where another variable or command
13261 substitution produces the name of the variable to actually manipulate.
13262 M4sh supports the notion of polymorphic shell variables, making it easy
13263 to write a macro that can deal with either literal or indirect variable
13264 names and output shell code appropriate for both use cases. Behavior is
13265 undefined if expansion of an indirect variable does not result in a
13266 literal variable name.
13268 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not})
13269 @asindex{LITERAL_IF}
13270 If the expansion of @var{expression} is definitely a shell literal,
13271 expand @var{if-literal}. If the expansion of @var{expression} looks
13272 like it might contain shell indirections (such as @code{$var} or
13273 @code{`expr`}), then @var{if-not} is expanded. In order to reduce the
13274 time spent deciding whether an expression is literal, the implementation
13275 is somewhat conservative (for example, @samp{'[$]'} is a single-quoted
13276 shell literal, but causes @var{if-not} to be expanded). While this
13277 macro is often used for recognizing shell variable names, it can also be
13278 used in other contexts.
13281 AC_DEFUN([MY_ACTION],
13282 [AS_LITERAL_IF([$1],
13284 [AS_VAR_COPY([tmp], [$1])
13289 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13290 @asindex{VAR_APPEND}
13291 Emit shell code to append the shell expansion of @var{text} to the end
13292 of the current contents of the polymorphic shell variable @var{var},
13293 taking advantage of shells that provide the @samp{+=} extension for more
13296 For situations where the final contents of @var{var} are relatively
13297 short (less than 256 bytes), it is more efficient to use the simpler
13298 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13299 polymorphic equivalent of @code{AS_VAR_COPY([tmp], [@var{var}])} and
13300 @code{AS_VAR_SET([@var{var}], ["$tmp"@var{text}])}). But in the case
13301 when the script will be repeatedly appending text into @code{var},
13302 issues of scaling start to become apparent. A naive implementation
13303 requires execution time linear to the length of the current contents of
13304 @var{var} as well as the length of @var{text} for a single append, for
13305 an overall quadratic scaling with multiple appends. This macro takes
13306 advantage of shells which provide the extension
13307 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13308 for a single append, for an overall linear scaling with multiple
13309 appends. Note that unlike @code{AS_VAR_SET}, this macro requires that
13310 @var{text} be quoted properly to avoid field splitting and file name
13314 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13315 @asindex{VAR_ARITH}
13316 Emit shell code to compute the arithmetic expansion of @var{expression},
13317 assigning the result as the contents of the polymorphic shell variable
13318 @var{var}. The code takes advantage of shells that provide @samp{$(())}
13319 for fewer forks, but uses @command{expr} as a fallback. Therefore, the
13320 syntax for a valid @var{expression} is rather limited: all operators
13321 must occur as separate shell arguments and with proper quoting, there is
13322 no portable equality operator, all variables containing numeric values
13323 must be expanded prior to the computation, all numeric values must be
13324 provided in decimal without leading zeroes, and the first shell argument
13325 should not be a negative number. In the following example, this snippet
13326 will print @samp{(2+3)*4 == 20}.
13330 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13331 echo "(2+$bar)*4 == $foo"
13335 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13337 Emit shell code to assign the contents of the polymorphic shell variable
13338 @var{source} to the polymorphic shell variable @var{dest}. For example,
13339 executing this M4sh snippet will output @samp{bar hi}:
13343 AS_VAR_COPY([a], [foo])
13344 AS_VAR_COPY([b], [$foo])
13348 When it is necessary to access the contents of an indirect variable
13349 inside a shell double-quoted context, the recommended idiom is to first
13350 copy the contents into a temporary literal shell variable.
13353 for header in stdint_h inttypes_h ; do
13354 AS_VAR_COPY([var], [ac_cv_header_$header])
13355 echo "$header detected: $var"
13360 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13361 @comment trailing newlines uniformly, and forks too much.
13363 @defmac AS_VAR_IF (@var{var}, @ovar{value}, @ovar{if-equal}, @
13364 @ovar{if-not-equal})
13366 Output a shell conditional statement. If the contents of the
13367 polymorphic shell variable @var{var} match the string @var{value},
13368 execute @var{if-equal}; otherwise execute @var{if-not-equal}. Avoids
13369 shell bugs if an interrupt signal arrives while a command substitution
13370 in @var{var} is being expanded.
13373 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13374 @defmacx AS_VAR_POPDEF (@var{m4-name})
13375 @asindex{VAR_PUSHDEF}
13376 @asindex{VAR_POPDEF}
13377 @cindex composing variable names
13378 @cindex variable names, composing
13379 A common M4sh idiom involves composing shell variable names from an m4
13380 argument (for example, writing a macro that uses a cache variable).
13381 @var{value} can be an arbitrary string, which will be transliterated
13382 into a valid shell name by @code{AS_TR_SH}. In order to access the
13383 composed variable name based on @var{value}, it is easier to declare a
13384 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13385 that macro as the argument to subsequent @code{AS_VAR} macros as a
13386 polymorphic variable name, and finally free the temporary macro with
13387 @code{AS_VAR_POPDEF}. These macros are often followed with @code{dnl},
13388 to avoid excess newlines in the output.
13390 Here is an involved example, that shows the power of writing macros that
13391 can handle composed shell variable names:
13394 m4_define([MY_CHECK_HEADER],
13395 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13396 AS_VAR_IF([my_Header], [yes], [echo "header $1 available"])dnl
13397 AS_VAR_POPDEF([my_Header])dnl
13399 MY_CHECK_HEADER([stdint.h])
13400 for header in inttypes.h stdlib.h ; do
13401 MY_CHECK_HEADER([$header])
13406 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13407 variable names. In the first invocation, the m4 argument is
13408 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13409 As a result, the temporary macro @code{my_Header} expands to the literal
13410 shell name @samp{ac_cv_header_stdint_h}. In the second invocation, the
13411 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13412 temporary macro @code{my_Header} expands to the indirect shell name
13413 @samp{$as_my_Header}. During the shell execution of the for loop, when
13414 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13415 contains @samp{ac_cv_header_inttypes_h}. If this script is then run on a
13416 platform where all three headers have been previously detected, the
13417 output of the script will include:
13420 header stdint.h detected
13421 header inttypes.h detected
13422 header stdlib.h detected
13426 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13428 Emit shell code to assign the contents of the polymorphic shell variable
13429 @var{var} to the shell expansion of @var{value}. @var{value} is not
13430 subject to field splitting or file name expansion, so if command
13431 substitution is used, it may be done with @samp{`""`} rather than using
13432 an intermediate variable (@pxref{Shell Substitutions}). However,
13433 @var{value} does undergo rescanning for additional macro names; behavior
13434 is unspecified if late expansion results in any shell meta-characters.
13437 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13438 @asindex{VAR_SET_IF}
13439 Emit a shell conditional statement, which executes @var{if-set} if the
13440 polymorphic shell variable @code{var} is set to any value, and
13441 @var{if-undef} otherwise.
13444 @defmac AS_VAR_TEST_SET (@var{var})
13445 @asindex{VAR_TEST_SET}
13446 Emit a shell statement that results in a successful exit status only if
13447 the polymorphic shell variable @code{var} is set.
13450 @node Initialization Macros
13451 @section Initialization Macros
13453 @defmac AS_BOURNE_COMPATIBLE
13454 @asindex{BOURNE_COMPATIBLE}
13455 Set up the shell to be more compatible with the Bourne shell as
13456 standardized by Posix, if possible. This may involve setting
13457 environment variables, or setting options, or similar
13458 implementation-specific actions. This macro is deprecated, since
13459 @code{AS_INIT} already invokes it.
13466 Initialize the M4sh environment. This macro calls @code{m4_init}, then
13467 outputs the @code{#! /bin/sh} line, a notice about where the output was
13468 generated from, and code to sanitize the environment for the rest of the
13469 script. Among other initializations, this sets @env{SHELL} to the shell
13470 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
13471 ensure the C locale. Finally, it changes the current diversion to
13472 @code{BODY}. @code{AS_INIT} is called automatically by @code{AC_INIT}
13473 and @code{AT_INIT}, so shell code in @file{configure},
13474 @file{config.status}, and @file{testsuite} all benefit from a sanitized
13478 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
13479 @asindex{INIT_GENERATED}
13480 Emit shell code to start the creation of a subsidiary shell script in
13481 @var{file}, including changing @var{file} to be executable. This macro
13482 populates the child script with information learned from the parent
13483 (thus, the emitted code is equivalent in effect, but more efficient,
13484 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
13485 @code{AS_SHELL_SANITIZE}). If present, @var{comment} is output near the
13486 beginning of the child, prior to the shell initialization code, and is
13487 subject to parameter expansion, command substitution, and backslash
13489 parent script should check the exit status after this macro, in case
13490 @var{file} could not be properly created (for example, if the disk was
13491 full). If successfully created, the parent script can then proceed to
13492 append additional M4sh constructs into the child script.
13494 Note that the child script starts life without a log file open, so if
13495 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
13496 must temporarily disable any attempts to use the log file until after
13497 emitting code to open a log within the child. On the other hand, if the
13498 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
13499 @samp{1}, then the child script already has code that copies stdout to
13500 that descriptor. Currently, the suggested
13501 idiom for writing a M4sh shell script from within another script is:
13504 AS_INIT_GENERATED([@var{file}], [[# My child script.
13505 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
13506 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
13507 cat >> "@var{file}" <<\__EOF__
13508 # Code to initialize AS_MESSAGE_LOG_FD
13509 m4_popdef([AS_MESSAGE_LOG_FD])dnl
13514 This, however, may change in the future as the M4sh interface is
13515 stabilized further.
13517 Also, be aware that use of @env{LINENO} within the child script may
13518 report line numbers relative to their location in the parent script,
13519 even when using @code{AS_LINENO_PREPARE}, if the parent script was
13520 unable to locate a shell with working @env{LINENO} support.
13523 @defmac AS_LINENO_PREPARE
13524 @asindex{LINENO_PREPARE}
13526 Find a shell that supports the special variable @env{LINENO}, which
13527 contains the number of the currently executing line. This macro is
13528 automatically invoked by @code{AC_INIT} in configure scripts.
13531 @defmac AS_ME_PREPARE
13532 @asindex{ME_PREPARE}
13533 Set up variable @env{as_me} to be the basename of the currently executing
13534 script. This macro is automatically invoked by @code{AC_INIT} in
13538 @defmac AS_SHELL_SANITIZE
13539 @asindex{SHELL_SANITIZE}
13540 Initialize the shell suitably for @command{configure} scripts. This has
13541 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
13542 environment variables for predictable results from configuration tests.
13543 For example, it sets @env{LC_ALL} to change to the default C locale.
13544 @xref{Special Shell Variables}. This macro is deprecated, since
13545 @code{AS_INIT} already invokes it.
13549 @node File Descriptor Macros
13550 @section File Descriptor Macros
13552 @cindex standard input
13553 @cindex file descriptors
13554 @cindex descriptors
13555 @cindex low-level output
13556 @cindex output, low-level
13558 The following macros define file descriptors used to output messages
13559 (or input values) from @file{configure} scripts.
13563 echo "$wombats found" >&AS_MESSAGE_LOG_FD
13564 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
13565 read kangaroos <&AS_ORIGINAL_STDIN_FD`
13569 However doing so is seldom needed, because Autoconf provides higher
13570 level macros as described below.
13572 @defmac AS_MESSAGE_FD
13573 @asindex{MESSAGE_FD}
13574 The file descriptor for @samp{checking for...} messages and results.
13575 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
13576 clients. However, @code{AC_INIT} shuffles things around to another file
13577 descriptor, in order to allow the @option{-q} option of
13578 @command{configure} to choose whether messages should go to the script's
13579 standard output or be discarded.
13581 If you want to display some messages, consider using one of the printing
13582 macros (@pxref{Printing Messages}) instead. Copies of messages output
13583 via these macros are also recorded in @file{config.log}.
13586 @anchor{AS_MESSAGE_LOG_FD}
13587 @defmac AS_MESSAGE_LOG_FD
13588 @asindex{MESSAGE_LOG_FD}
13589 This must either be empty, or expand to a file descriptor for log
13590 messages. By default, @code{AS_INIT} sets this macro to the empty
13591 string for standalone M4sh clients, thus disabling logging. However,
13592 @code{AC_INIT} shuffles things around so that both @command{configure}
13593 and @command{config.status} use @file{config.log} for log messages.
13594 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
13595 Compiler}), redirect all output to this descriptor. You may want to do
13596 so if you develop such a low-level macro.
13599 @defmac AS_ORIGINAL_STDIN_FD
13600 @asindex{ORIGINAL_STDIN_FD}
13601 This must expand to a file descriptor for the original standard input.
13602 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
13603 M4sh clients. However, @code{AC_INIT} shuffles things around for
13606 When @command{configure} runs, it may accidentally execute an
13607 interactive command that has the same name as the non-interactive meant
13608 to be used or checked. If the standard input was the terminal, such
13609 interactive programs would cause @command{configure} to stop, pending
13610 some user input. Therefore @command{configure} redirects its standard
13611 input from @file{/dev/null} during its initialization. This is not
13612 normally a problem, since @command{configure} normally does not need
13615 In the extreme case where your @file{configure} script really needs to
13616 obtain some values from the original standard input, you can read them
13617 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
13621 @c =================================================== Writing Autoconf Macros.
13623 @node Writing Autoconf Macros
13624 @chapter Writing Autoconf Macros
13626 When you write a feature test that could be applicable to more than one
13627 software package, the best thing to do is encapsulate it in a new macro.
13628 Here are some instructions and guidelines for writing Autoconf macros.
13631 * Macro Definitions:: Basic format of an Autoconf macro
13632 * Macro Names:: What to call your new macros
13633 * Reporting Messages:: Notifying @command{autoconf} users
13634 * Dependencies Between Macros:: What to do when macros depend on other macros
13635 * Obsoleting Macros:: Warning about old ways of doing things
13636 * Coding Style:: Writing Autoconf macros @`a la Autoconf
13639 @node Macro Definitions
13640 @section Macro Definitions
13642 @defmac AC_DEFUN (@var{name}, @ovar{body})
13644 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
13645 similar to the M4 builtin @code{m4_define} macro; this creates a macro
13646 named @var{name} and with @var{body} as its expansion. In addition to
13647 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
13648 constrain the order in which macros are called, while avoiding redundant
13649 output (@pxref{Prerequisite Macros}).
13652 An Autoconf macro definition looks like this:
13655 AC_DEFUN(@var{macro-name}, @var{macro-body})
13658 You can refer to any arguments passed to the macro as @samp{$1},
13659 @samp{$2}, etc. @xref{Definitions, , How to define new macros, m4.info,
13660 GNU M4}, for more complete information on writing M4 macros.
13662 Most macros fall in one of two general categories. The first category
13663 includes macros which take arguments, in order to generate output
13664 parameterized by those arguments. Macros in this category are designed
13665 to be directly expanded, often multiple times, and should not be used as
13666 the argument to @code{AC_REQUIRE}. The other category includes macros
13667 which are shorthand for a fixed block of text, and therefore do not take
13668 arguments. For this category of macros, directly expanding the macro
13669 multiple times results in redundant output, so it is more common to use
13670 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
13671 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
13673 Be sure to properly quote both the @var{macro-body} @emph{and} the
13674 @var{macro-name} to avoid any problems if the macro happens to have
13675 been previously defined.
13677 Each macro should have a header comment that gives its prototype, and a
13678 brief description. When arguments have default values, display them in
13679 the prototype. For example:
13682 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
13683 # --------------------------------------
13684 m4_define([AC_MSG_ERROR],
13685 [@{ AS_MESSAGE([error: $1], [2])
13686 exit m4_default([$2], [1]); @}])
13689 Comments about the macro should be left in the header comment. Most
13690 other comments make their way into @file{configure}, so just keep
13691 using @samp{#} to introduce comments.
13694 If you have some special comments about pure M4 code, comments
13695 that make no sense in @file{configure} and in the header comment, then
13696 use the builtin @code{dnl}: it causes M4 to discard the text
13697 through the next newline.
13699 Keep in mind that @code{dnl} is rarely needed to introduce comments;
13700 @code{dnl} is more useful to get rid of the newlines following macros
13701 that produce no output, such as @code{AC_REQUIRE}.
13703 Public third-party macros need to use @code{AC_DEFUN}, and not
13704 @code{m4_define}, in order to be found by @command{aclocal}
13705 (@pxref{Extending aclocal,,, automake, GNU Automake}).
13706 Additionally, if it is ever determined that a macro should be made
13707 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
13708 in order to have @command{autoupdate} assist the user in choosing a
13709 better alternative, but there is no corresponding way to make
13710 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
13712 There is another subtle, but important, difference between using
13713 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
13714 @code{AC_REQUIRE}. When writing a file, it is always safe to replace a
13715 block of text with a @code{m4_define} macro that will expand to the same
13716 text. But replacing a block of text with an @code{AC_DEFUN} macro with
13717 the same content does not necessarily give the same results, because it
13718 changes the location where any embedded but unsatisfied
13719 @code{AC_REQUIRE} invocations within the block will be expanded. For an
13720 example of this, see @ref{Expanded Before Required}.
13723 @section Macro Names
13725 All of the public Autoconf macros have all-uppercase names in the
13726 namespace @samp{^AC_} to prevent them from accidentally conflicting with
13727 other text; Autoconf also reserves the namespace @samp{^_AC_} for
13728 internal macros. All shell variables that they use for internal
13729 purposes have mostly-lowercase names starting with @samp{ac_}. Autoconf
13730 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}. During
13731 @command{configure}, files produced by Autoconf make heavy use of the
13732 file system namespace @samp{^conf}.
13734 Since Autoconf is built on top of M4sugar (@pxref{Programming in
13735 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
13736 of those namespaces (@samp{^_?\(m4\|AS\)_}). And since
13737 @file{configure.ac} is also designed to be scanned by Autoheader,
13738 Autoscan, Autoupdate, and Automake, you should be aware of the
13739 @samp{^_?A[HNUM]_} namespaces. In general, you @emph{should not use}
13740 the namespace of a package that does not own the macro or shell code you
13743 To ensure that your macros don't conflict with present or future
13744 Autoconf macros, you should prefix your own macro names and any shell
13745 variables they use with some other sequence. Possibilities include your
13746 initials, or an abbreviation for the name of your organization or
13747 software package. Historically, people have not always followed the
13748 rule of using a namespace appropriate for their package, and this has
13749 made it difficult for determining the origin of a macro (and where to
13750 report bugs about that macro), as well as difficult for the true
13751 namespace owner to add new macros without interference from pre-existing
13752 uses of third-party macros. Perhaps the best example of this confusion
13753 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
13756 Most of the Autoconf macros' names follow a structured naming convention
13757 that indicates the kind of feature check by the name. The macro names
13758 consist of several words, separated by underscores, going from most
13759 general to most specific. The names of their cache variables use the
13760 same convention (@pxref{Cache Variable Names}, for more information on
13763 The first word of the name after the namespace initials (such as
13764 @samp{AC_}) usually tells the category
13765 of the feature being tested. Here are the categories used in Autoconf for
13766 specific test macros, the kind of macro that you are more likely to
13767 write. They are also used for cache variables, in all-lowercase. Use
13768 them where applicable; where they're not, invent your own categories.
13772 C language builtin features.
13774 Declarations of C variables in header files.
13776 Functions in libraries.
13778 Posix group owners of files.
13784 The base names of programs.
13786 Members of aggregates.
13788 Operating system features.
13790 C builtin or declared types.
13792 C variables in libraries.
13795 After the category comes the name of the particular feature being
13796 tested. Any further words in the macro name indicate particular aspects
13797 of the feature. For example, @code{AC_PROG_CC_STDC} checks whether the
13798 C compiler supports ISO Standard C.
13800 An internal macro should have a name that starts with an underscore;
13801 Autoconf internals should therefore start with @samp{_AC_}.
13802 Additionally, a macro that is an internal subroutine of another macro
13803 should have a name that starts with an underscore and the name of that
13804 other macro, followed by one or more words saying what the internal
13805 macro does. For example, @code{AC_PATH_X} has internal macros
13806 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
13808 @node Reporting Messages
13809 @section Reporting Messages
13810 @cindex Messages, from @command{autoconf}
13812 When macros statically diagnose abnormal situations, benign or fatal, it
13813 is possible to make @command{autoconf} detect the problem, and refuse to
13814 create @file{configure} in the case of an error. The macros in this
13815 section are considered obsolescent, and new code should use M4sugar
13816 macros for this purpose, see @ref{Diagnostic Macros}.
13818 On the other hand, it is possible to want to detect errors when
13819 @command{configure} is run, which are dependent on the environment of
13820 the user rather than the maintainer. For dynamic diagnostics, see
13821 @ref{Printing Messages}.
13823 @defmac AC_DIAGNOSE (@var{category}, @var{message})
13825 Report @var{message} as a warning (or as an error if requested by the
13826 user) if warnings of the @var{category} are turned on. This macro is
13827 obsolescent; you are encouraged to use:
13829 m4_warn([@var{category}], [@var{message}])
13832 instead. @xref{m4_warn}, for more details, including valid
13833 @var{category} names.
13836 @defmac AC_WARNING (@var{message})
13838 Report @var{message} as a syntax warning. This macro is obsolescent;
13839 you are encouraged to use:
13841 m4_warn([syntax], [@var{message}])
13844 instead. @xref{m4_warn}, for more details, as well as better
13845 finer-grained categories of warnings (not all problems have to do with
13849 @defmac AC_FATAL (@var{message})
13851 Report a severe error @var{message}, and have @command{autoconf} die.
13852 This macro is obsolescent; you are encouraged to use:
13854 m4_fatal([@var{message}])
13857 instead. @xref{m4_fatal}, for more details.
13860 When the user runs @samp{autoconf -W error}, warnings from
13861 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
13862 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
13864 @node Dependencies Between Macros
13865 @section Dependencies Between Macros
13866 @cindex Dependencies between macros
13868 Some Autoconf macros depend on other macros having been called first in
13869 order to work correctly. Autoconf provides a way to ensure that certain
13870 macros are called if needed and a way to warn the user if macros are
13871 called in an order that might cause incorrect operation.
13874 * Prerequisite Macros:: Ensuring required information
13875 * Suggested Ordering:: Warning about possible ordering problems
13876 * One-Shot Macros:: Ensuring a macro is called only once
13879 @node Prerequisite Macros
13880 @subsection Prerequisite Macros
13881 @cindex Prerequisite macros
13882 @cindex Macros, prerequisites
13884 A macro that you write might need to use values that have previously
13885 been computed by other macros. For example, @code{AC_DECL_YYTEXT}
13886 examines the output of @code{flex} or @code{lex}, so it depends on
13887 @code{AC_PROG_LEX} having been called first to set the shell variable
13890 Rather than forcing the user of the macros to keep track of the
13891 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
13892 it automatically. @code{AC_REQUIRE} can ensure that a macro is only
13893 called if it is needed, and only called once.
13895 @defmac AC_REQUIRE (@var{macro-name})
13897 If the M4 macro @var{macro-name} has not already been called, call it
13898 (without any arguments). Make sure to quote @var{macro-name} with
13899 square brackets. @var{macro-name} must have been defined using
13900 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13901 that it has been called.
13903 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
13904 must not be called from the top level. Also, it does not make sense to
13905 require a macro that takes parameters.
13908 @code{AC_REQUIRE} is often misunderstood. It really implements
13909 dependencies between macros in the sense that if one macro depends upon
13910 another, the latter is expanded @emph{before} the body of the
13911 former. To be more precise, the required macro is expanded before
13912 the outermost defined macro in the current expansion stack.
13913 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
13914 @code{FOO}. For instance, this definition of macros:
13918 AC_DEFUN([TRAVOLTA],
13919 [test "$body_temperature_in_celsius" -gt "38" &&
13920 dance_floor=occupied])
13921 AC_DEFUN([NEWTON_JOHN],
13922 [test "x$hair_style" = xcurly &&
13923 dance_floor=occupied])
13927 AC_DEFUN([RESERVE_DANCE_FLOOR],
13928 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13929 AC_REQUIRE([TRAVOLTA])
13930 AC_REQUIRE([NEWTON_JOHN])
13936 with this @file{configure.ac}
13939 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
13940 RESERVE_DANCE_FLOOR
13941 if test "x$dance_floor" = xoccupied; then
13942 AC_MSG_ERROR([cannot pick up here, let's move])
13947 does not leave you with a better chance to meet a kindred soul at
13948 other times than Saturday night since it expands into:
13952 test "$body_temperature_in_Celsius" -gt "38" &&
13953 dance_floor=occupied
13954 test "x$hair_style" = xcurly &&
13955 dance_floor=occupied
13957 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13964 This behavior was chosen on purpose: (i) it prevents messages in
13965 required macros from interrupting the messages in the requiring macros;
13966 (ii) it avoids bad surprises when shell conditionals are used, as in:
13971 AC_REQUIRE([SOME_CHECK])
13978 However, this implementation can lead to another class of problems.
13979 Consider the case where an outer macro first expands, then indirectly
13980 requires, an inner macro:
13983 AC_DEFUN([TESTA], [[echo in A
13984 if test -n "$SEEN_A" ; then echo duplicate ; fi
13986 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
13987 if test -z "$SEEN_A" ; then echo bug ; fi]])
13988 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13989 AC_DEFUN([OUTER], [[echo in OUTER]
13996 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
13997 recognized that @code{TESTB} needed to be hoisted prior to the expansion
13998 of @code{OUTER}, but because @code{TESTA} had already been directly
13999 expanded, it failed to hoist @code{TESTA}. Therefore, the expansion of
14000 @code{TESTB} occurs prior to its prerequisites, leading to the following
14012 Newer Autoconf is smart enough to recognize this situation, and hoists
14013 @code{TESTA} even though it has already been expanded, but issues a
14014 syntax warning in the process. This is because the hoisted expansion of
14015 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14016 redundant code, and causes its own set of problems if the hoisted macro
14028 The bug is not in Autoconf, but in the macro definitions. If you ever
14029 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14030 that the macro only needs to be expanded once. But to enforce this,
14031 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14032 this only helps in Autoconf 2.64 or newer), or all
14033 uses of that macro should be through @code{AC_REQUIRE}; directly
14034 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14035 eliminate redundant expansion. In the example, this rule of thumb was
14036 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14037 directly expands it. One way of fixing the bug is to factor
14038 @code{TESTA} into two macros, the portion designed for direct and
14039 repeated use (here, named @code{TESTA}), and the portion designed for
14040 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14041 @code{TESTA_PREREQ}). Then, by fixing all clients to use the correct
14042 calling convention according to their needs:
14045 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14046 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14047 if test -n "$SEEN_A" ; then echo duplicate ; fi
14049 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14050 if test -z "$SEEN_A" ; then echo bug ; fi]])
14051 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14052 AC_DEFUN([OUTER], [[echo in OUTER]
14059 the resulting output will then obey all dependency rules and avoid any
14060 syntax warnings, whether the script is built with old or new Autoconf
14071 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14072 enforce expansion of required macros outside of shell conditional
14073 constructs. You are furthermore encouraged, although not required, to
14074 put all @code{AC_REQUIRE} calls
14075 at the beginning of a macro. You can use @code{dnl} to avoid the empty
14078 @node Suggested Ordering
14079 @subsection Suggested Ordering
14080 @cindex Macros, ordering
14081 @cindex Ordering macros
14083 Some macros should be run before another macro if both are called, but
14084 neither @emph{requires} that the other be called. For example, a macro
14085 that changes the behavior of the C compiler should be called before any
14086 macros that run the C compiler. Many of these dependencies are noted in
14089 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14090 with this kind of dependency appear out of order in a
14091 @file{configure.ac} file. The warning occurs when creating
14092 @command{configure} from @file{configure.ac}, not when running
14093 @command{configure}.
14095 For example, @code{AC_PROG_CPP} checks whether the C compiler
14096 can run the C preprocessor when given the @option{-E} option. It should
14097 therefore be called after any macros that change which C compiler is
14098 being used, such as @code{AC_PROG_CC}. So @code{AC_PROG_CC} contains:
14101 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14105 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14106 when @code{AC_PROG_CC} is called.
14108 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14110 Make M4 print a warning message to the standard error output if
14111 @var{called-macro-name} has already been called. @var{this-macro-name}
14112 should be the name of the macro that is calling @code{AC_BEFORE}. The
14113 macro @var{called-macro-name} must have been defined using
14114 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14115 that it has been called.
14118 @node One-Shot Macros
14119 @subsection One-Shot Macros
14120 @cindex One-shot macros
14121 @cindex Macros, called once
14123 Some macros should be called only once, either because calling them
14124 multiple time is unsafe, or because it is bad style. For instance
14125 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14126 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14127 sense to run these expensive checks more than once. Such one-shot
14128 macros can be defined using @code{AC_DEFUN_ONCE}.
14130 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14131 @acindex{DEFUN_ONCE}
14132 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14133 Definitions}), but add additional logic that guarantees that only the
14134 first use of the macro (whether by direct expansion or
14135 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14136 expansion will occur before the start of any enclosing macro defined by
14137 @code{AC_DEFUN}. Subsequent expansions are silently ignored.
14138 Generally, it does not make sense for @var{macro-body} to use parameters
14142 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14143 emit a warning if it was directly expanded a second time, so for
14144 portability, it is better to use @code{AC_REQUIRE} than direct
14145 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14146 (@pxref{Prerequisite Macros}).
14148 @node Obsoleting Macros
14149 @section Obsoleting Macros
14150 @cindex Obsoleting macros
14151 @cindex Macros, obsoleting
14153 Configuration and portability technology has evolved over the years.
14154 Often better ways of solving a particular problem are developed, or
14155 ad-hoc approaches are systematized. This process has occurred in many
14156 parts of Autoconf. One result is that some of the macros are now
14157 considered @dfn{obsolete}; they still work, but are no longer considered
14158 the best thing to do, hence they should be replaced with more modern
14159 macros. Ideally, @command{autoupdate} should replace the old macro calls
14160 with their modern implementation.
14162 Autoconf provides a simple means to obsolete a macro.
14165 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14167 Define @var{old-macro} as @var{implementation}. The only difference
14168 with @code{AC_DEFUN} is that the user is warned that
14169 @var{old-macro} is now obsolete.
14171 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14172 replaced by the modern @var{implementation}. @var{message} should
14173 include information on what to do after running @command{autoupdate};
14174 @command{autoupdate} prints it as a warning, and includes it
14175 in the updated @file{configure.ac} file.
14177 The details of this macro are hairy: if @command{autoconf} encounters an
14178 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14179 as usual. However, when @command{autoupdate} is run, only M4 and M4sugar
14180 macros are expanded here, while all other macros are disabled and
14181 appear literally in the updated @file{configure.ac}.
14184 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14186 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14187 with the same parameters. This happens for example if the macro was renamed.
14191 @section Coding Style
14192 @cindex Coding style
14194 The Autoconf macros follow a strict coding style. You are encouraged to
14195 follow this style, especially if you intend to distribute your macro,
14196 either by contributing it to Autoconf itself or the
14197 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14198 Archive}, or by other means.
14200 The first requirement is to pay great attention to the quotation. For
14201 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14203 Do not try to invent new interfaces. It is likely that there is a macro
14204 in Autoconf that resembles the macro you are defining: try to stick to
14205 this existing interface (order of arguments, default values, etc.). We
14206 @emph{are} conscious that some of these interfaces are not perfect;
14207 nevertheless, when harmless, homogeneity should be preferred over
14210 Be careful about clashes both between M4 symbols and between shell
14213 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14214 you are unlikely to generate conflicts. Nevertheless, when you need to
14215 set a special value, @emph{avoid using a regular macro name}; rather,
14216 use an ``impossible'' name. For instance, up to version 2.13, the macro
14217 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14218 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14219 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14220 impossible to @samp{AC_SUBST(FILE)}! In this case,
14221 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14222 have been used (yes, with the parentheses).
14223 @c or better yet, high-level macros such as @code{m4_expand_once}
14225 No Autoconf macro should ever enter the user-variable name space; i.e.,
14226 except for the variables that are the actual result of running the
14227 macro, all shell variables should start with @code{ac_}. In
14228 addition, small macros or any macro that is likely to be embedded in
14229 other macros should be careful not to use obvious names.
14232 Do not use @code{dnl} to introduce comments: most of the comments you
14233 are likely to write are either header comments which are not output
14234 anyway, or comments that should make their way into @file{configure}.
14235 There are exceptional cases where you do want to comment special M4
14236 constructs, in which case @code{dnl} is right, but keep in mind that it
14239 M4 ignores the leading blanks and newlines before each argument.
14240 Use this feature to
14241 indent in such a way that arguments are (more or less) aligned with the
14242 opening parenthesis of the macro being called. For instance, instead of
14245 AC_CACHE_CHECK(for EMX OS/2 environment,
14247 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14248 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14255 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14256 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14257 [ac_cv_emxos2=yes],
14258 [ac_cv_emxos2=no])])
14265 AC_CACHE_CHECK([for EMX OS/2 environment],
14267 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14268 [return __EMX__;])],
14269 [ac_cv_emxos2=yes],
14270 [ac_cv_emxos2=no])])
14273 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14274 cross-compiling, provide a pessimistic value (typically @samp{no}).
14276 Feel free to use various tricks to prevent auxiliary tools, such as
14277 syntax-highlighting editors, from behaving improperly. For instance,
14281 m4_bpatsubst([$1], [$"])
14288 m4_bpatsubst([$1], [$""])
14292 so that Emacsen do not open an endless ``string'' at the first quote.
14293 For the same reasons, avoid:
14303 test $[@@%:@@] != 0
14307 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14308 breaking the bracket-matching highlighting from Emacsen. Note the
14309 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc. Do
14310 not escape when it is unnecessary. Common examples of useless quotation
14311 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14312 etc. If you add portability issues to the picture, you'll prefer
14313 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14314 better than hacking Autoconf @code{:-)}.
14316 When using @command{sed}, don't use @option{-e} except for indenting
14317 purposes. With the @code{s} and @code{y} commands, the preferred
14318 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14319 or replacement, in which case you should use @samp{|}, or optionally
14320 @samp{,} if you know the pattern and replacement cannot contain a file
14321 name. If none of these characters will do, choose a printable character
14322 that cannot appear in the pattern or replacement. Characters from the
14323 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14324 replacement might contain a file name, since they have special meaning
14325 to the shell and are less likely to occur in file names.
14327 @xref{Macro Definitions}, for details on how to define a macro. If a
14328 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14329 of an @code{AC_REQUIRE} directive, and macros required by other macros
14330 inside arguments do not need to be expanded before this macro, then
14331 use @code{m4_define}. In case of doubt, use @code{AC_DEFUN}.
14332 Also take into account that public third-party macros need to use
14333 @code{AC_DEFUN} in order to be found by @command{aclocal}
14334 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14335 All the @code{AC_REQUIRE} statements should be at the beginning of the
14336 macro, and each statement should be followed by @code{dnl}.
14338 You should not rely on the number of arguments: instead of checking
14339 whether an argument is missing, test that it is not empty. It provides
14340 both a simpler and a more predictable interface to the user, and saves
14341 room for further arguments.
14343 Unless the macro is short, try to leave the closing @samp{])} at the
14344 beginning of a line, followed by a comment that repeats the name of the
14345 macro being defined. This introduces an additional newline in
14346 @command{configure}; normally, that is not a problem, but if you want to
14347 remove it you can use @samp{[]dnl} on the last line. You can similarly
14348 use @samp{[]dnl} after a macro call to remove its newline. @samp{[]dnl}
14349 is recommended instead of @samp{dnl} to ensure that M4 does not
14350 interpret the @samp{dnl} as being attached to the preceding text or
14351 macro output. For example, instead of:
14354 AC_DEFUN([AC_PATH_X],
14355 [AC_MSG_CHECKING([for X])
14357 @r{# @dots{}omitted@dots{}}
14358 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14366 AC_DEFUN([AC_PATH_X],
14367 [AC_REQUIRE_CPP()[]dnl
14368 AC_MSG_CHECKING([for X])
14369 @r{# @dots{}omitted@dots{}}
14370 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14375 If the macro is long, try to split it into logical chunks. Typically,
14376 macros that check for a bug in a function and prepare its
14377 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14378 this setup. Do not hesitate to introduce auxiliary macros to factor
14381 In order to highlight the recommended coding style, here is a macro
14382 written the old way:
14385 dnl Check for EMX on OS/2.
14387 AC_DEFUN(_AC_EMXOS2,
14388 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14389 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14390 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14391 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14400 # Check for EMX on OS/2.
14401 m4_define([_AC_EMXOS2],
14402 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14403 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14404 [ac_cv_emxos2=yes],
14405 [ac_cv_emxos2=no])])
14406 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14413 @c ============================================= Portable Shell Programming
14415 @node Portable Shell
14416 @chapter Portable Shell Programming
14417 @cindex Portable shell programming
14419 When writing your own checks, there are some shell-script programming
14420 techniques you should avoid in order to make your code portable. The
14421 Bourne shell and upward-compatible shells like the Korn shell and Bash
14422 have evolved over the years, and many features added to the original
14423 System7 shell are now supported on all interesting porting targets.
14424 However, the following discussion between Russ Allbery and Robert Lipe
14431 The GNU assumption that @command{/bin/sh} is the one and only shell
14432 leads to a permanent deadlock. Vendors don't want to break users'
14433 existing shell scripts, and there are some corner cases in the Bourne
14434 shell that are not completely compatible with a Posix shell. Thus,
14435 vendors who have taken this route will @emph{never} (OK@dots{}``never say
14436 never'') replace the Bourne shell (as @command{/bin/sh}) with a
14444 This is exactly the problem. While most (at least most System V's) do
14445 have a Bourne shell that accepts shell functions most vendor
14446 @command{/bin/sh} programs are not the Posix shell.
14448 So while most modern systems do have a shell @emph{somewhere} that meets the
14449 Posix standard, the challenge is to find it.
14452 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
14453 is to find such a shell. But to prevent trouble, if you're not using
14454 M4sh you should not take advantage of features that were added after Unix
14455 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
14456 negated character classes, or even @command{unset}. @code{#} comments,
14457 while not in Unix version 7, were retrofitted in the original Bourne
14458 shell and can be assumed to be part of the least common denominator.
14460 On the other hand, if you're using M4sh you can assume that the shell
14461 has the features that were added in SVR2 (circa 1984), including shell
14463 @command{return}, @command{unset}, and I/O redirection for builtins. For
14464 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
14465 However, some pitfalls have to be avoided for portable use of these
14466 constructs; these will be documented in the rest of this chapter.
14467 See in particular @ref{Shell Functions} and @ref{Limitations of
14468 Builtins, , Limitations of Shell Builtins}.
14470 Some ancient systems have quite
14471 small limits on the length of the @samp{#!} line; for instance, 32
14472 bytes (not including the newline) on SunOS 4.
14473 However, these ancient systems are no longer of practical concern.
14475 The set of external programs you should run in a @command{configure} script
14476 is fairly small. @xref{Utilities in Makefiles, , Utilities in
14477 Makefiles, standards, GNU Coding Standards}, for the list. This
14478 restriction allows users to start out with a fairly small set of
14479 programs and build the rest, avoiding too many interdependencies between
14482 Some of these external utilities have a portable subset of features; see
14483 @ref{Limitations of Usual Tools}.
14485 There are other sources of documentation about shells. The
14486 specification for the Posix
14487 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
14488 Command Language}, though more generous than the restrictive shell
14489 subset described above, is fairly portable nowadays. Also please see
14490 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
14493 * Shellology:: A zoology of shells
14494 * Here-Documents:: Quirks and tricks
14495 * File Descriptors:: FDs and redirections
14496 * File System Conventions:: File names
14497 * Shell Pattern Matching:: Pattern matching
14498 * Shell Substitutions:: Variable and command expansions
14499 * Assignments:: Varying side effects of assignments
14500 * Parentheses:: Parentheses in shell scripts
14501 * Slashes:: Slashes in shell scripts
14502 * Special Shell Variables:: Variables you should not change
14503 * Shell Functions:: What to look out for if you use them
14504 * Limitations of Builtins:: Portable use of not so portable /bin/sh
14505 * Limitations of Usual Tools:: Portable use of portable tools
14509 @section Shellology
14512 There are several families of shells, most prominently the Bourne family
14513 and the C shell family which are deeply incompatible. If you want to
14514 write portable shell scripts, avoid members of the C shell family. The
14515 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
14516 Shell difference FAQ} includes a small history of Posix shells, and a
14517 comparison between several of them.
14519 Below we describe some of the members of the Bourne shell family.
14524 Ash is often used on GNU/Linux and BSD
14525 systems as a light-weight Bourne-compatible shell. Ash 0.2 has some
14526 bugs that are fixed in the 0.3.x series, but portable shell scripts
14527 should work around them, since version 0.2 is still shipped with many
14528 GNU/Linux distributions.
14530 To be compatible with Ash 0.2:
14534 don't use @samp{$?} after expanding empty or unset variables,
14535 or at the start of an @command{eval}:
14541 echo "Do not use it: $?"
14543 eval 'echo "Do not use it: $?"'
14547 don't use command substitution within variable expansion:
14554 beware that single builtin substitutions are not performed by a
14555 subshell, hence their effect applies to the current shell! @xref{Shell
14556 Substitutions}, item ``Command Substitution''.
14561 To detect whether you are running Bash, test whether
14562 @code{BASH_VERSION} is set. To require
14563 Posix compatibility, run @samp{set -o posix}. @xref{Bash POSIX
14564 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
14565 Manual}, for details.
14567 @item Bash 2.05 and later
14568 @cindex Bash 2.05 and later
14569 Versions 2.05 and later of Bash use a different format for the
14570 output of the @command{set} builtin, designed to make evaluating its
14571 output easier. However, this output is not compatible with earlier
14572 versions of Bash (or with many other shells, probably). So if
14573 you use Bash 2.05 or higher to execute @command{configure},
14574 you'll need to use Bash 2.05 for all other build tasks as well.
14579 @prindex @samp{ksh}
14580 @prindex @samp{ksh88}
14581 @prindex @samp{ksh93}
14582 The Korn shell is compatible with the Bourne family and it mostly
14583 conforms to Posix. It has two major variants commonly
14584 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
14585 release. It is usually called @command{ksh}, but is called @command{sh}
14586 on some hosts if you set your path appropriately.
14588 Solaris systems have three variants:
14589 @prindex @command{/usr/bin/ksh} on Solaris
14590 @command{/usr/bin/ksh} is @samp{ksh88}; it is
14591 standard on Solaris 2.0 and later.
14592 @prindex @command{/usr/xpg4/bin/sh} on Solaris
14593 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
14594 @samp{ksh88}; it is standard on Solaris 9 and later.
14595 @prindex @command{/usr/dt/bin/dtksh} on Solaris
14596 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
14597 Variants that are not standard may be parts of optional
14598 packages. There is no extra charge for these packages, but they are
14599 not part of a minimal OS install and therefore some installations may
14602 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
14603 is also available as @command{/usr/bin/posix/sh}. If the environment
14604 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14605 the standard shell conform to Posix.
14608 @prindex @samp{pdksh}
14609 A public-domain clone of the Korn shell called @command{pdksh} is widely
14610 available: it has most of the @samp{ksh88} features along with a few of
14611 its own. It usually sets @code{KSH_VERSION}, except if invoked as
14612 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
14613 Posix compatibility by running @samp{set -o posix}. Unfortunately, with
14614 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
14615 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
14616 at least one respect:
14619 $ @kbd{echo "`echo \"hello\"`"}
14621 $ @kbd{set -o posix}
14622 $ @kbd{echo "`echo \"hello\"`"}
14626 The last line of output contains spurious quotes. This is yet another
14627 reason why portable shell code should not contain
14628 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
14633 To detect whether you are running @command{zsh}, test whether
14634 @code{ZSH_VERSION} is set. By default @command{zsh} is @emph{not}
14635 compatible with the Bourne shell: you must execute @samp{emulate sh},
14636 and for @command{zsh} versions before 3.1.6-dev-18 you must also
14637 set @code{NULLCMD} to @samp{:}. @xref{Compatibility, , Compatibility,
14638 zsh, The Z Shell Manual}, for details.
14640 The default Mac OS X @command{sh} was originally Zsh; it was changed to
14641 Bash in Mac OS X 10.2.
14644 @node Here-Documents
14645 @section Here-Documents
14646 @cindex Here-documents
14647 @cindex Shell here-documents
14649 Don't rely on @samp{\} being preserved just because it has no special
14650 meaning together with the next symbol. In the native @command{sh}
14651 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
14652 unquoted delimiter. As a general rule, if @samp{\\} expands to @samp{\}
14653 use @samp{\\} to get @samp{\}.
14655 With OpenBSD 2.7's @command{sh}
14671 bash-2.04$ @kbd{cat <<EOF
14678 Some shells mishandle large here-documents: for example,
14679 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
14680 derived from Korn shell version M-12/28/93d, mishandle braced variable
14681 expansion that crosses a 1024- or 4096-byte buffer boundary
14682 within a here-document. Only the part of the variable name after the boundary
14683 is used. For example, @code{$@{variable@}} could be replaced by the expansion
14684 of @code{$@{ble@}}. If the end of the variable name is aligned with the block
14685 boundary, the shell reports an error, as if you used @code{$@{@}}.
14686 Instead of @code{$@{variable-default@}}, the shell may expand
14687 @code{$@{riable-default@}}, or even @code{$@{fault@}}. This bug can often
14688 be worked around by omitting the braces: @code{$variable}. The bug was
14690 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
14691 still shipping older versions with the bug.
14693 Many shells (including the Bourne shell) implement here-documents
14694 inefficiently. In particular, some shells can be extremely inefficient when
14695 a single statement contains many here-documents. For instance if your
14696 @file{configure.ac} includes something like:
14700 if <cross_compiling>; then
14701 assume this and that
14705 check something else
14713 A shell parses the whole @code{if}/@code{fi} construct, creating
14714 temporary files for each here-document in it. Some shells create links
14715 for such here-documents on every @code{fork}, so that the clean-up code
14716 they had installed correctly removes them. It is creating the links
14717 that can take the shell forever.
14719 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
14720 @code{if}/@code{fi} constructs, would improve the performance
14721 significantly. Anyway, this kind of construct is not exactly the
14722 typical use of Autoconf. In fact, it's even not recommended, because M4
14723 macros can't look into shell conditionals, so we may fail to expand a
14724 macro when it was expanded before in a conditional path, and the
14725 condition turned out to be false at runtime, and we end up not
14726 executing the macro at all.
14728 Be careful with the use of @samp{<<-} to unindent here-documents. The
14729 behavior is only portable for stripping leading @key{TAB}s, and things
14730 can silently break if an overzealous editor converts to using leading
14731 spaces (not all shells are nice enough to warn about unterminated
14735 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
14739 $ @kbd{printf 'cat <<-x\n 1\n 2\n x\n' | bash-3.2 && echo done}
14746 @node File Descriptors
14747 @section File Descriptors
14748 @cindex Descriptors
14749 @cindex File descriptors
14750 @cindex Shell file descriptors
14752 Most shells, if not all (including Bash, Zsh, Ash), output traces on
14753 stderr, even for subshells. This might result in undesirable content
14754 if you meant to capture the standard-error output of the inner command:
14757 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
14759 + eval echo foo >&2
14762 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
14764 + eval 'echo foo >&2'
14767 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
14768 @i{# Traces on startup files deleted here.}
14770 +zsh:1> eval echo foo >&2
14776 One workaround is to grep out uninteresting lines, hoping not to remove
14779 If you intend to redirect both standard error and standard output,
14780 redirect standard output first. This works better with HP-UX,
14781 since its shell mishandles tracing if standard error is redirected
14785 $ @kbd{sh -x -c ': 2>err >out'}
14787 + 2> err $ @kbd{cat err}
14791 Don't try to redirect the standard error of a command substitution. It
14792 must be done @emph{inside} the command substitution. When running
14793 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
14794 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
14796 On the other hand, some shells, such as Solaris or FreeBSD
14797 @command{/bin/sh}, warn about missing programs before performing
14798 redirections. Therefore, to silently check whether a program exists, it
14799 is necessary to perform redirections on a subshell:
14802 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
14804 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
14805 $ @kbd{bash -c 'nosuch 2>/dev/null'}
14808 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
14811 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
14812 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
14814 Some shells, like @command{ash}, don't recognize bi-directional
14815 redirection (@samp{<>}). And even on shells that recognize it, it is
14816 not portable to use on fifos: Posix does not require read-write support
14817 for named pipes, and Cygwin does not support it:
14820 $ @kbd{mkfifo fifo}
14821 $ @kbd{exec 5<>fifo}
14822 $ @kbd{echo hi >&5}
14823 bash: echo: write error: Communication error on send
14826 When catering to old systems, don't redirect the same file descriptor
14827 several times, as you are doomed to failure under Ultrix.
14830 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
14832 $ @kbd{eval 'echo matter >fullness' >void}
14834 $ @kbd{eval '(echo matter >fullness)' >void}
14836 $ @kbd{(eval '(echo matter >fullness)') >void}
14837 Ambiguous output redirect.
14841 In each case the expected result is of course @file{fullness} containing
14842 @samp{matter} and @file{void} being empty. However, this bug is
14843 probably not of practical concern to modern platforms.
14845 Solaris 10 @command{sh} will try to optimize away a @command{:} command
14846 in a loop after the first iteration, even if it is redirected:
14849 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
14855 As a workaround, @command{echo} or @command{eval} can be used.
14857 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
14858 subsidiary program. If any of these descriptors is closed, the
14859 operating system may open an unspecified file for the descriptor in the
14860 new process image. Posix says this may be done only if the subsidiary
14861 program is set-user-ID or set-group-ID, but HP-UX 11.23 does
14862 it even for ordinary programs.
14864 Don't rely on open file descriptors being open in child processes. In
14865 @command{ksh}, file descriptors above 2 which are opened using
14866 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
14867 that involved in the fork-and-exec which runs a program or script).
14868 Thus, using @command{sh}, we have:
14871 $ @kbd{cat ./descrips}
14893 Within the process which runs the @samp{descrips} script, file
14894 descriptor 5 is closed.
14896 Don't rely on redirection to a closed file descriptor to cause an
14897 error. With Solaris @command{/bin/sh}, when the redirection fails, the
14898 output goes to the original file descriptor.
14901 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
14902 bash: 3: Bad file descriptor
14904 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
14909 DOS variants cannot rename or remove open files, such as in
14910 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
14911 perfectly portable among Posix hosts.
14913 A few ancient systems reserved some file descriptors. By convention,
14914 file descriptor 3 was opened to @file{/dev/tty} when you logged into
14915 Eighth Edition (1985) through Tenth Edition Unix (1989). File
14916 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
14917 1990), though we don't now remember what it was. Both these systems are
14918 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
14919 other file descriptors.
14921 @node File System Conventions
14922 @section File System Conventions
14923 @cindex File system conventions
14925 Autoconf uses shell-script processing extensively, so the file names
14926 that it processes should not contain characters that are special to the
14927 shell. Special characters include space, tab, newline, NUL, and
14931 " # $ & ' ( ) * ; < = > ? [ \ ` |
14934 Also, file names should not begin with @samp{~} or @samp{-}, and should
14935 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
14936 immediately after @samp{:}. On Posix-like platforms, directory names
14937 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
14940 These restrictions apply not only to the files that you distribute, but
14941 also to the absolute file names of your source, build, and destination
14944 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
14945 they should be avoided.
14947 Posix lets implementations treat leading @file{//} specially, but
14948 requires leading @file{///} and beyond to be equivalent to @file{/}.
14949 Most Unix variants treat @file{//} like @file{/}. However, some treat
14950 @file{//} as a ``super-root'' that can provide access to files that are
14951 not otherwise reachable from @file{/}. The super-root tradition began
14952 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
14955 While @command{autoconf} and friends are usually run on some Posix
14956 variety, they can be used on other systems, most notably DOS
14957 variants. This impacts several assumptions regarding file names.
14960 For example, the following code:
14967 foo_dir=$dots$foo_dir ;;
14972 fails to properly detect absolute file names on those systems, because
14973 they can use a drivespec, and usually use a backslash as directory
14974 separator. If you want to be portable to DOS variants (at the
14975 price of rejecting valid but oddball Posix file names like @file{a:\b}),
14976 you can check for absolute file names like this:
14978 @cindex absolute file names, detect
14981 [\\/]* | ?:[\\/]* ) # Absolute
14984 foo_dir=$dots$foo_dir ;;
14989 Make sure you quote the brackets if appropriate and keep the backslash as
14990 first character (@pxref{case, , Limitations of Shell Builtins}).
14992 Also, because the colon is used as part of a drivespec, these systems don't
14993 use it as path separator. When creating or accessing paths, you can use the
14994 @code{PATH_SEPARATOR} output variable instead. @command{configure} sets this
14995 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
14998 File names need extra care as well. While DOS variants
14999 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15000 are usually able to handle long file names properly, there are still
15001 limitations that can seriously break packages. Several of these issues
15002 can be easily detected by the
15003 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15006 A short overview follows; problems are marked with SFN/LFN to
15007 indicate where they apply: SFN means the issues are only relevant to
15008 plain DOS, not to DOS under Microsoft Windows
15009 variants, while LFN identifies problems that exist even under
15010 Microsoft Windows variants.
15013 @item No multiple dots (SFN)
15014 DOS cannot handle multiple dots in file names. This is an especially
15015 important thing to remember when building a portable configure script,
15016 as @command{autoconf} uses a .in suffix for template files.
15018 This is perfectly OK on Posix variants:
15021 AC_CONFIG_HEADERS([config.h])
15022 AC_CONFIG_FILES([source.c foo.bar])
15027 but it causes problems on DOS, as it requires @samp{config.h.in},
15028 @samp{source.c.in} and @samp{foo.bar.in}. To make your package more portable
15029 to DOS-based environments, you should use this instead:
15032 AC_CONFIG_HEADERS([config.h:config.hin])
15033 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15037 @item No leading dot (SFN)
15038 DOS cannot handle file names that start with a dot. This is usually
15039 not important for @command{autoconf}.
15041 @item Case insensitivity (LFN)
15042 DOS is case insensitive, so you cannot, for example, have both a
15043 file called @samp{INSTALL} and a directory called @samp{install}. This
15044 also affects @command{make}; if there's a file called @samp{INSTALL} in
15045 the directory, @samp{make install} does nothing (unless the
15046 @samp{install} target is marked as PHONY).
15048 @item The 8+3 limit (SFN)
15049 Because the DOS file system only stores the first 8 characters of
15050 the file name and the first 3 of the extension, those must be unique.
15051 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15052 @file{foobar-prettybird.c} all resolve to the same file name
15053 (@file{FOOBAR-P.C}). The same goes for @file{foo.bar} and
15054 @file{foo.bartender}.
15056 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15058 tails in the short version of file names to make them unique. However, a
15059 registry setting can turn this behavior off. While this makes it
15060 possible to share file trees containing long file names between SFN
15061 and LFN environments, it also means the above problem applies there
15064 @item Invalid characters (LFN)
15065 Some characters are invalid in DOS file names, and should therefore
15066 be avoided. In a LFN environment, these are @samp{/}, @samp{\},
15067 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15068 In a SFN environment, other characters are also invalid. These
15069 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15071 @item Invalid names (LFN)
15072 Some DOS file names are reserved, and cause problems if you
15073 try to use files with those names. These names include @file{CON},
15074 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15075 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15076 File names are case insensitive, so even names like
15077 @file{aux/config.guess} are disallowed.
15081 @node Shell Pattern Matching
15082 @section Shell Pattern Matching
15083 @cindex Shell pattern matching
15085 Nowadays portable patterns can use negated character classes like
15086 @samp{[!-aeiou]}. The older syntax @samp{[^-aeiou]} is supported by
15087 some shells but not others; hence portable scripts should never use
15088 @samp{^} as the first character of a bracket pattern.
15090 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15091 they may match characters that are not lower-case letters.
15093 @node Shell Substitutions
15094 @section Shell Substitutions
15095 @cindex Shell substitutions
15097 Contrary to a persistent urban legend, the Bourne shell does not
15098 systematically split variables and back-quoted expressions, in particular
15099 on the right-hand side of assignments and in the argument of @code{case}.
15100 For instance, the following code:
15103 case "$given_srcdir" in
15104 .) top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15105 *) top_srcdir="$dots$given_srcdir" ;;
15110 is more readable when written as:
15113 case $given_srcdir in
15114 .) top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15115 *) top_srcdir=$dots$given_srcdir ;;
15120 and in fact it is even @emph{more} portable: in the first case of the
15121 first attempt, the computation of @code{top_srcdir} is not portable,
15122 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
15123 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
15124 the same way. There is just no portable way to use double-quoted
15125 strings inside double-quoted back-quoted expressions (pfew!).
15129 @cindex @samp{"$@@"}
15130 One of the most famous shell-portability issues is related to
15131 @samp{"$@@"}. When there are no positional arguments, Posix says
15132 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15133 original Unix version 7 Bourne shell treated it as equivalent to
15134 @samp{""} instead, and this behavior survives in later implementations
15135 like Digital Unix 5.0.
15137 The traditional way to work around this portability problem is to use
15138 @samp{$@{1+"$@@"@}}. Unfortunately this method does not work with
15139 Zsh (3.x and 4.x), which is used on Mac OS X@. When emulating
15140 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15143 zsh $ @kbd{emulate sh}
15144 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15147 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15154 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15155 @samp{"$@@"} because of the portability problems mentioned above.
15156 One workaround relies on Zsh's ``global aliases'' to convert
15157 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15160 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15163 Zsh only recognizes this alias when a shell word matches it exactly;
15164 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting. Since this
15165 case always yields at least one shell word, use plain @samp{"$@@"}.
15167 A more conservative workaround is to avoid @samp{"$@@"} if it is
15168 possible that there may be no positional arguments. For example,
15172 cat conftest.c "$@@"
15175 you can use this instead:
15179 0) cat conftest.c;;
15180 *) cat conftest.c "$@@";;
15184 Autoconf macros often use the @command{set} command to update
15185 @samp{$@@}, so if you are writing shell code intended for
15186 @command{configure} you should not assume that the value of @samp{$@@}
15187 persists for any length of time.
15191 @cindex positional parameters
15192 The 10th, 11th, @dots{} positional parameters can be accessed only after
15193 a @code{shift}. The 7th Edition shell reported an error if given
15194 @code{$@{10@}}, and
15195 Solaris 10 @command{/bin/sh} still acts that way:
15198 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
15199 $ @kbd{echo $@{10@}}
15203 @item $@{@var{var}:-@var{value}@}
15204 @c Info cannot handle `:' in index entries.
15206 @cindex $@{@var{var}:-@var{value}@}
15208 Old BSD shells, including the Ultrix @code{sh}, don't accept the
15209 colon for any shell substitution, and complain and die.
15210 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
15212 @item $@{@var{var}=@var{literal}@}
15213 @cindex $@{@var{var}=@var{literal}@}
15217 : $@{var='Some words'@}
15221 otherwise some shells, such as on Digital Unix V 5.0, die because
15222 of a ``bad substitution''.
15226 Solaris @command{/bin/sh} has a frightening bug in its interpretation
15227 of this. Imagine you need set a variable to a string containing
15228 @samp{@}}. This @samp{@}} character confuses Solaris @command{/bin/sh}
15229 when the affected variable was already set. This bug can be exercised
15234 $ @kbd{foo=$@{foo='@}'@}}
15237 $ @kbd{foo=$@{foo='@}' # no error; this hints to what the bug is}
15240 $ @kbd{foo=$@{foo='@}'@}}
15246 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
15247 though it is enclosed in single quotes. The problem doesn't happen
15248 using double quotes.
15250 @item $@{@var{var}=@var{expanded-value}@}
15251 @cindex $@{@var{var}=@var{expanded-value}@}
15257 : $@{var="$default"@}
15261 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
15262 each char is set. You don't observe the phenomenon using a simple
15263 @samp{echo $var} since apparently the shell resets the 8th bit when it
15264 expands $var. Here are two means to make this shell confess its sins:
15267 $ @kbd{cat -v <<EOF
15276 $ @kbd{set | grep '^var=' | cat -v}
15279 One classic incarnation of this bug is:
15283 : $@{list="$default"@}
15290 You'll get @samp{a b c} on a single line. Why? Because there are no
15291 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
15292 bit set, hence no IFS splitting is performed!!!
15294 One piece of good news is that Ultrix works fine with @samp{:
15295 $@{list=$default@}}; i.e., if you @emph{don't} quote. The bad news is
15296 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
15299 The portable way out consists in using a double assignment, to switch
15300 the 8th bit twice on Ultrix:
15303 list=$@{list="$default"@}
15307 @dots{}but beware of the @samp{@}} bug from Solaris (see above). For safety,
15311 test "$@{var+set@}" = set || var=@var{@{value@}}
15314 @item $@{#@var{var}@}
15315 @itemx $@{@var{var}%@var{word}@}
15316 @itemx $@{@var{var}%%@var{word}@}
15317 @itemx $@{@var{var}#@var{word}@}
15318 @itemx $@{@var{var}##@var{word}@}
15319 @cindex $@{#@var{var}@}
15320 @cindex $@{@var{var}%@var{word}@}
15321 @cindex $@{@var{var}%%@var{word}@}
15322 @cindex $@{@var{var}#@var{word}@}
15323 @cindex $@{@var{var}##@var{word}@}
15324 Posix requires support for these usages, but they do not work with many
15325 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
15327 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms. For
15328 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
15329 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
15330 yields the empty string.
15333 @item `@var{commands}`
15334 @cindex `@var{commands}`
15335 @cindex Command Substitution
15336 Posix requires shells to trim all trailing newlines from command
15337 output before substituting it, so assignments like
15338 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
15339 @samp{$file} ends in a newline.
15341 While in general it makes no sense, do not substitute a single builtin
15342 with side effects, because Ash 0.2, trying to optimize, does not fork a
15343 subshell to perform the command.
15345 For instance, if you wanted to check that @command{cd} is silent, do not
15346 use @samp{test -z "`cd /`"} because the following can happen:
15351 $ @kbd{test -z "`cd /`" && pwd}
15356 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
15358 The MSYS shell leaves a stray byte in the expansion of a double-quoted
15359 command substitution of a native program, if the end of the substitution
15360 is not aligned with the end of the double quote. This may be worked
15361 around by inserting another pair of quotes:
15364 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
15365 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
15366 - broken differ: char 4, line 1
15369 Upon interrupt or SIGTERM, some shells may abort a command substitution,
15370 replace it with a null string, and wrongly evaluate the enclosing
15371 command before entering the trap or ending the script. This can lead to
15375 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
15377 sh: test: hi: unexpected operator/operand
15381 You can avoid this by assigning the command substitution to a temporary
15385 $ @kbd{sh -c 'res=`sleep 5; echo hi`
15386 if test "x$res" = xhi; then echo yes; fi'}
15390 @item $(@var{commands})
15391 @cindex $(@var{commands})
15392 This construct is meant to replace @samp{`@var{commands}`},
15393 and it has most of the problems listed under @code{`@var{commands}`}.
15395 This construct can be
15396 nested while this is impossible to do portably with back quotes.
15397 Unfortunately it is not yet universally supported. Most notably, even recent
15398 releases of Solaris don't support it:
15401 $ @kbd{showrev -c /bin/sh | grep version}
15402 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
15403 $ @kbd{echo $(echo blah)}
15404 syntax error: `(' unexpected
15408 nor does IRIX 6.5's Bourne shell:
15411 IRIX firebird-image 6.5 07151432 IP22
15412 $ @kbd{echo $(echo blah)}
15416 If you do use @samp{$(@var{commands})}, make sure that the commands
15417 do not start with a parenthesis, as that would cause confusion with
15418 a different notation @samp{$((@var{expression}))} that in modern
15419 shells is an arithmetic expression not a command. To avoid the
15420 confusion, insert a space between the two opening parentheses.
15422 Avoid @var{commands} that contain unbalanced parentheses in
15423 here-documents, comments, or case statement patterns, as many shells
15424 mishandle them. For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
15425 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
15428 echo $(case x in x) echo hello;; esac)
15432 @item $((@var{expression}))
15433 @cindex $((@var{expression}))
15434 Arithmetic expansion is not portable as some shells (most
15435 notably Solaris 10 @command{/bin/sh}) don't support it.
15437 Among shells that do support @samp{$(( ))}, not all of them obey the
15438 Posix rule that octal and hexadecimal constants must be recognized:
15441 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
15443 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
15445 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
15447 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
15448 pdksh: 010 + 0x10 : bad number `0x10'
15449 $ @kbd{pdksh -c 'echo $(( 010 ))'}
15453 When it is available, using arithmetic expansion provides a noticeable
15454 speedup in script execution; but testing for support requires
15455 @command{eval} to avoid syntax errors. The following construct is used
15456 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
15457 arguments are provided in decimal and without a leading zero, and all
15458 operators are properly quoted and appear as distinct arguments:
15461 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
15462 eval 'func_arith ()
15464 func_arith_result=$(( $* ))
15469 func_arith_result=`expr "$@@"`
15473 foo=$func_arith_result
15479 Always quote @samp{^}, otherwise traditional shells such as
15480 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
15486 @section Assignments
15487 @cindex Shell assignments
15489 When setting several variables in a row, be aware that the order of the
15490 evaluation is undefined. For instance @samp{foo=1 foo=2; echo $foo}
15491 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
15493 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
15495 Don't rely on the following to find @file{subdir/program}:
15498 PATH=subdir$PATH_SEPARATOR$PATH program
15502 as this does not work with Zsh 3.0.6. Use something like this
15506 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
15509 Don't rely on the exit status of an assignment: Ash 0.2 does not change
15510 the status and propagates that of the last statement:
15513 $ @kbd{false || foo=bar; echo $?}
15515 $ @kbd{false || foo=`:`; echo $?}
15520 and to make things even worse, QNX 4.25 just sets the exit status
15524 $ @kbd{foo=`exit 1`; echo $?}
15528 To assign default values, follow this algorithm:
15532 If the default value is a literal and does not contain any closing
15536 : $@{var='my literal'@}
15540 If the default value contains no closing brace, has to be expanded, and
15541 the variable being initialized is not intended to be IFS-split
15542 (i.e., it's not a list), then use:
15545 : $@{var="$default"@}
15549 If the default value contains no closing brace, has to be expanded, and
15550 the variable being initialized is intended to be IFS-split (i.e., it's a list),
15554 var=$@{var="$default"@}
15558 If the default value contains a closing brace, then use:
15561 test "$@{var+set@}" = set || var="has a '@}'"
15565 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
15566 doubt, just use the last form. @xref{Shell Substitutions}, items
15567 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
15571 @section Parentheses in Shell Scripts
15572 @cindex Shell parentheses
15574 Beware of two opening parentheses in a row, as many shell
15575 implementations treat them specially. Posix requires that the command
15576 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
15577 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
15578 expression equivalent to @samp{let "cat"}, and may or may not report an
15579 error when they detect that @samp{cat} is not a number. As another
15580 example, @samp{pdksh} 5.2.14 misparses the following code:
15583 if ((true) || false); then
15589 To work around this problem, insert a space between the two opening
15590 parentheses. There is a similar problem and workaround with
15591 @samp{$((}; see @ref{Shell Substitutions}.
15594 @section Slashes in Shell Scripts
15595 @cindex Shell slashes
15597 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
15598 arguments that contain two trailing slashes:
15601 $ @kbd{echo / // /// //// .// //.}
15604 $ @kbd{eval "echo \$x"}
15607 $ @kbd{echo abc | tr -t ab //}
15613 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
15614 variable is empty and the second double-quote is followed by a word that
15615 begins and ends with slash:
15618 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
15624 However, our understanding is that patches are available, so perhaps
15625 it's not worth worrying about working around these horrendous bugs.
15627 @node Special Shell Variables
15628 @section Special Shell Variables
15629 @cindex Shell variables
15630 @cindex Special shell variables
15632 Some shell variables should not be used, since they can have a deep
15633 influence on the behavior of the shell. In order to recover a sane
15634 behavior from the shell, some variables should be unset; M4sh takes
15635 care of this and provides fallback values, whenever needed, to cater
15636 for a very old @file{/bin/sh} that does not support @command{unset}.
15637 (@pxref{Portable Shell, , Portable Shell Programming}).
15639 As a general rule, shell variable names containing a lower-case letter
15640 are safe; you can define and use these variables without worrying about
15641 their effect on the underlying system, and without worrying about
15642 whether the shell changes them unexpectedly. (The exception is the
15643 shell variable @code{status}, as described below.)
15645 Here is a list of names that are known to cause trouble. This list is
15646 not exhaustive, but you should be safe if you avoid the name
15647 @code{status} and names containing only upper-case letters and
15650 @c Alphabetical order, case insensitive, `A' before `a'.
15653 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
15654 , Limitations of Shell Builtins}). Not all shells manage @samp{$?}
15655 correctly in shell functions (@pxref{Shell Functions}) or in traps
15656 (@pxref{trap, , Limitations of Shell Builtins}). Not all shells reset
15657 @samp{$?} to zero after an empty command.
15660 $ @kbd{bash -c 'false; $empty; echo $?'}
15662 $ @kbd{zsh -c 'false; $empty; echo $?'}
15668 Many shells reserve @samp{$_} for various purposes, e.g., the name of
15669 the last command executed.
15673 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15674 the standard shell conform to Posix.
15678 When this variable is set it specifies a list of directories to search
15679 when invoking @code{cd} with a relative file name that did not start
15680 with @samp{./} or @samp{../}. Posix
15681 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
15682 is used successfully, @code{cd} prints the resulting absolute
15683 file name. Unfortunately this output can break idioms like
15684 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
15685 Also, many shells do not conform to this part of Posix; for
15686 example, @command{zsh} prints the result only if a directory name
15687 other than @file{.} was chosen from @env{CDPATH}.
15689 In practice the shells that have this problem also support
15690 @command{unset}, so you can work around the problem as follows:
15693 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
15696 You can also avoid output by ensuring that your directory name is
15697 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
15699 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
15700 possible, so you need not worry about this problem in those scripts.
15702 @item CLICOLOR_FORCE
15703 @evindex CLICOLOR_FORCE
15704 When this variable is set, some implementations of tools like
15705 @command{ls} attempt to add color to their output via terminal escape
15706 sequences, even when the output is not directed to a terminal, and can
15707 thus cause spurious failures in scripts. Configure scripts use M4sh,
15708 which automatically unsets this variable.
15712 In the MKS shell, case statements and file name generation are
15713 case-insensitive unless @env{DUALCASE} is nonzero.
15714 Autoconf-generated scripts export this variable when they start up.
15728 These variables should not matter for shell scripts, since they are
15729 supposed to affect only interactive shells. However, at least one
15730 shell (the pre-3.0 UWIN Korn shell) gets confused about
15731 whether it is interactive, which means that (for example) a @env{PS1}
15732 with a side effect can unexpectedly modify @samp{$?}. To work around
15733 this bug, M4sh scripts (including @file{configure} scripts) do something
15737 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
15744 (actually, there is some complication due to bugs in @command{unset};
15745 see @pxref{unset, , Limitations of Shell Builtins}).
15749 The Korn shell uses @env{FPATH} to find shell functions, so avoid
15750 @env{FPATH} in portable scripts. @env{FPATH} is consulted after
15751 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
15752 to find whether a command exists, since they might report the wrong
15753 result if @env{FPATH} is also set.
15756 @evindex GREP_OPTIONS
15757 When this variable is set, some implementations of @command{grep} honor
15758 these options, even if the options include direction to enable colored
15759 output via terminal escape sequences, and the result can cause spurious
15760 failures when the output is not directed to a terminal. Configure
15761 scripts use M4sh, which automatically unsets this variable.
15765 Long ago, shell scripts inherited @env{IFS} from the environment,
15766 but this caused many problems so modern shells ignore any environment
15767 settings for @env{IFS}.
15769 Don't set the first character of @env{IFS} to backslash. Indeed,
15770 Bourne shells use the first character (backslash) when joining the
15771 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
15772 backslash escapes, so you can end up with backspace and other strange
15775 The proper value for @env{IFS} (in regular code, not when performing
15776 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}. The first character is
15777 especially important, as it is used to join the arguments in @samp{$*};
15778 however, note that traditional shells, but also bash-2.04, fail to adhere
15779 to this and join with a space anyway.
15781 M4sh guarantees that @env{IFS} will have the default value at the
15782 beginning of a script, and many macros within autoconf rely on this
15783 setting. It is okay to use blocks of shell code that temporarily change
15784 the value of @env{IFS} in order to split on another character, but
15785 remember to restore it before expanding further macros.
15797 @evindex LC_COLLATE
15799 @evindex LC_MESSAGES
15800 @evindex LC_MONETARY
15801 @evindex LC_NUMERIC
15804 You should set all these variables to @samp{C} because so much
15805 configuration code assumes the C locale and Posix requires that locale
15806 environment variables be set to @samp{C} if the C locale is desired;
15807 @file{configure} scripts and M4sh do that for you.
15808 Export these variables after setting them.
15810 Unsetting @code{IFS} instead of resetting it to the default sequence
15811 is not suggested, since code that tries to save and restore the
15812 variable's value will incorrectly reset it to an empty value, thus
15813 disabling field splitting:
15817 # default separators used for field splitting
15823 # no field splitting performed
15826 @c However, some older, nonstandard
15827 @c systems (notably SCO) break if locale environment variables
15828 @c are set to @samp{C}, so when running on these systems
15829 @c Autoconf-generated scripts unset the variables instead.
15834 @env{LANGUAGE} is not specified by Posix, but it is a GNU
15835 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
15839 @itemx LC_IDENTIFICATION
15840 @itemx LC_MEASUREMENT
15843 @itemx LC_TELEPHONE
15844 @evindex LC_ADDRESS
15845 @evindex LC_IDENTIFICATION
15846 @evindex LC_MEASUREMENT
15849 @evindex LC_TELEPHONE
15851 These locale environment variables are GNU extensions. They
15852 are treated like their Posix brethren (@env{LC_COLLATE},
15853 etc.)@: as described above.
15857 Most modern shells provide the current line number in @code{LINENO}.
15858 Its value is the line number of the beginning of the current command.
15859 M4sh, and hence Autoconf, attempts to execute @command{configure} with
15860 a shell that supports @code{LINENO}. If no such shell is available, it
15861 attempts to implement @code{LINENO} with a Sed prepass that replaces each
15862 instance of the string @code{$LINENO} (not followed by an alphanumeric
15863 character) with the line's number. In M4sh scripts you should execute
15864 @code{AS_LINENO_PREPARE} so that these workarounds are included in
15865 your script; configure scripts do this automatically in @code{AC_INIT}.
15867 You should not rely on @code{LINENO} within @command{eval} or shell
15868 functions, as the behavior differs in practice. The presence of a
15869 quoted newline within simple commands can alter which line number is
15870 used as the starting point for @code{$LINENO} substitutions within that
15871 command. Also, the possibility of the Sed prepass means that you should
15872 not rely on @code{$LINENO} when quoted, when in here-documents, or when
15873 line continuations are used. Subshells should be OK, though. In the
15874 following example, lines 1, 9, and 14 are portable, but the other
15875 instances of @code{$LINENO} do not have deterministic values:
15888 ( echo 9. $LINENO )
15889 eval 'echo 10. $LINENO'
15890 eval 'echo 11. $LINENO
15895 f () @{ echo $1 $LINENO;
15902 $ @kbd{bash-3.2 ./lineno}
15921 $ @kbd{zsh-4.3.4 ./lineno}
15940 $ @kbd{pdksh-5.2.14 ./lineno}
15959 $ @kbd{sed '=' <lineno |}
15965 > @kbd{ s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
15968 > @kbd{ s,^[0-9]*\n,,}
15990 In particular, note that @file{config.status} (and any other subsidiary
15991 script created by @code{AS_INIT_GENERATED}) might report line numbers
15992 relative to the parent script as a result of the potential Sed pass.
15996 When executing the command @samp{>foo}, @command{zsh} executes
15997 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
15998 compatibility mode and the @command{zsh} version is newer
15999 than 3.1.6-dev-18. If you are using an older @command{zsh}
16000 and forget to set @env{NULLCMD},
16001 your script might be suspended waiting for data on its standard input.
16003 @item PATH_SEPARATOR
16004 @evindex PATH_SEPARATOR
16005 On DJGPP systems, the @env{PATH_SEPARATOR} environment
16006 variable can be set to either @samp{:} or @samp{;} to control the path
16007 separator Bash uses to set up certain environment variables (such as
16008 @env{PATH}). You can set this variable to @samp{;} if you want
16009 @command{configure} to use @samp{;} as a separator; this might be useful
16010 if you plan to use non-Posix shells to execute files. @xref{File System
16011 Conventions}, for more information about @code{PATH_SEPARATOR}.
16015 Posix 1003.1-2001 requires that @command{cd} and
16016 @command{pwd} must update the @env{PWD} environment variable to point
16017 to the logical name of the current directory, but traditional shells
16018 do not support this. This can cause confusion if one shell instance
16019 maintains @env{PWD} but a subsidiary and different shell does not know
16020 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
16021 points to the wrong directory. Use @samp{`pwd`} rather than
16026 Many shells provide @code{RANDOM}, a variable that returns a different
16027 integer each time it is used. Most of the time, its value does not
16028 change when it is not used, but on IRIX 6.5 the value changes all
16029 the time. This can be observed by using @command{set}. It is common
16030 practice to use @code{$RANDOM} as part of a file name, but code
16031 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
16035 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
16036 hence read-only. Do not use it.
16039 @node Shell Functions
16040 @section Shell Functions
16041 @cindex Shell Functions
16043 Nowadays, it is difficult to find a shell that does not support
16044 shell functions at all. However, some differences should be expected.
16046 Inside a shell function, you should not rely on the error status of a
16047 subshell if the last command of that subshell was @code{exit} or
16048 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
16049 find a shell that does not exhibit the bug, zsh might be the only shell
16050 present on the user's machine.
16052 Likewise, the state of @samp{$?} is not reliable when entering a shell
16053 function. This has the effect that using a function as the first
16054 command in a @command{trap} handler can cause problems.
16057 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16060 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16065 DJGPP bash 2.04 has a bug in that @command{return} from a
16066 shell function which also used a command substitution causes a
16067 segmentation fault. To work around the issue, you can use
16068 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
16069 in the execution flow of the function (@pxref{Common Shell Constructs}).
16071 Not all shells treat shell functions as simple commands impacted by
16072 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
16075 $ @kbd{bash -c 'f()@{ return 1; @}; set -e; f; echo oops}
16076 $ @kbd{/bin/sh -c 'f()@{ return 1; @}; set -e; f; echo oops}
16080 Shell variables and functions may share the same namespace, for example
16081 with Solaris 10 @command{/bin/sh}:
16084 $ @kbd{f () @{ :; @}; f=; f}
16089 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
16090 uses the prefix @samp{as_fn_} for its functions.
16092 Handling of positional parameters and shell options varies among shells.
16093 For example, Korn shells reset and restore trace output (@samp{set -x})
16094 and other options upon function entry and exit. Inside a function,
16095 IRIX sh sets @samp{$0} to the function name.
16097 It is not portable to pass temporary environment variables to shell
16098 functions. Solaris @command{/bin/sh} does not see the variable.
16099 Meanwhile, not all shells follow the Posix rule that the assignment must
16100 affect the current environment in the same manner as special built-ins.
16103 $ @kbd{/bin/sh -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
16106 $ @kbd{ash -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
16109 $ @kbd{bash -c 'set -o posix; func()@{ echo $a;@}; a=1 func; echo $a'}
16114 Some ancient Bourne shell variants with function support did not reset
16115 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
16116 arguments of the script were lost after the first function invocation.
16117 It is probably not worth worrying about these shells any more.
16119 With AIX sh, a @command{trap} on 0 installed in a shell function
16120 triggers at function exit rather than at script exit, see @xref{trap, ,
16121 Limitations of Shell Builtins}.
16123 @node Limitations of Builtins
16124 @section Limitations of Shell Builtins
16125 @cindex Shell builtins
16126 @cindex Limitations of shell builtins
16128 No, no, we are serious: some shells do have limitations! :)
16130 You should always keep in mind that any builtin or command may support
16131 options, and therefore differ in behavior with arguments
16132 starting with a dash. For instance, even the innocent @samp{echo "$word"}
16133 can give unexpected results when @code{word} starts with a dash. It is
16134 often possible to avoid this problem using @samp{echo "x$word"}, taking
16135 the @samp{x} into account later in the pipe. Many of these limitations
16136 can be worked around using M4sh (@pxref{Programming in M4sh}).
16138 @c This table includes things like `@command{test} (files)', so we can't
16139 @c use @table @command.
16143 @prindex @command{.}
16144 Use @command{.} only with regular files (use @samp{test -f}). Bash
16145 2.03, for instance, chokes on @samp{. /dev/null}. Remember that
16146 @command{.} uses @env{PATH} if its argument contains no slashes. Also,
16147 some shells, including bash 3.2, implicitly append the current directory
16148 to this @env{PATH} search, even though Posix forbids it. So if you want
16149 to use @command{.} on a file @file{foo} in the current directory, you
16150 must use @samp{. ./foo}.
16152 Not all shells gracefully handle syntax errors within a sourced file.
16153 On one extreme, some non-interactive shells abort the entire script. On
16154 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
16158 $ @kbd{echo 'fi' > syntax}
16159 $ @kbd{bash -c '. ./syntax; echo $?'}
16160 ./syntax: line 1: syntax error near unexpected token `fi'
16161 ./syntax: line 1: `fi'
16163 $ @kbd{ash -c '. ./syntax; echo $?'}
16164 ./syntax: 1: Syntax error: "fi" unexpected
16165 $ @kbd{zsh -c '. ./syntax; echo $?'}
16166 ./syntax:1: parse error near `fi'
16172 @prindex @command{!}
16173 The Unix version 7 shell did not support
16174 negating the exit status of commands with @command{!}, and this feature
16175 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
16176 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
16177 bugs when using @command{!}:
16180 $ @kbd{sh -c '! : | :'; echo $?}
16182 $ @kbd{ash -c '! : | :'; echo $?}
16184 $ @kbd{sh -c '! @{ :; @}'; echo $?}
16186 $ @kbd{ash -c '! @{ :; @}'; echo $?}
16188 Syntax error: "@}" unexpected
16192 Shell code like this:
16195 if ! cmp file1 file2 >/dev/null 2>&1; then
16196 echo files differ or trouble
16200 is therefore not portable in practice. Typically it is easy to rewrite
16204 cmp file1 file2 >/dev/null 2>&1 ||
16205 echo files differ or trouble
16208 More generally, one can always rewrite @samp{! @var{command}} as:
16211 if @var{command}; then (exit 1); else :; fi
16215 @item @command{@{...@}}
16216 @c --------------------
16217 @prindex @command{@{...@}}
16218 Bash 3.2 (and earlier versions) sometimes does not properly set
16219 @samp{$?} when failing to write redirected output of a compound command.
16220 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
16221 not occur with @samp{(@dots{})}. For example:
16224 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
16225 bash: line 1: /bad: Permission denied
16227 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
16228 bash: line 1: /bad: Permission denied
16232 To work around the bug, prepend @samp{:;}:
16235 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
16236 bash: line 1: /bad: Permission denied
16240 Posix requires a syntax error if a brace list has no contents. However,
16241 not all shells obey this rule; and on shells where empty lists are
16242 permitted, the effect on @samp{$?} is inconsistent. To avoid problems,
16243 ensure that a brace list is never empty.
16246 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
16247 bash: line 1: syntax error near unexpected token `@}'
16248 bash: line 1: `false; @{ @}; echo $?'
16250 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
16252 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
16257 @item @command{break}
16258 @c ------------------
16259 @prindex @command{break}
16260 The use of @samp{break 2} etc.@: is safe.
16264 @item @command{case}
16265 @c -----------------
16266 @prindex @command{case}
16267 You don't need to quote the argument; no splitting is performed.
16269 You don't need the final @samp{;;}, but you should use it.
16271 Posix requires support for @code{case} patterns with opening
16272 parentheses like this:
16276 (*.c) echo "C source code";;
16281 but the @code{(} in this example is not portable to many Bourne
16282 shell implementations, which is a pity for those of us using tools that
16283 rely on balanced parentheses. For instance, with Solaris
16287 $ @kbd{case foo in (foo) echo foo;; esac}
16288 @error{}syntax error: `(' unexpected
16292 The leading @samp{(} can be omitted safely. Unfortunately, there are
16293 contexts where unbalanced parentheses cause other problems, such as when
16294 using a syntax-highlighting editor that searches for the balancing
16295 counterpart, or more importantly, when using a case statement as an
16296 underquoted argument to an Autoconf macro. @xref{Balancing
16297 Parentheses}, for tradeoffs involved in various styles of dealing with
16298 unbalanced @samp{)}.
16300 Zsh handles pattern fragments derived from parameter expansions or
16301 command substitutions as though quoted:
16304 $ pat=\?; case aa in ?$pat) echo match;; esac
16305 $ pat=\?; case a? in ?$pat) echo match;; esac
16310 Because of a bug in its @code{fnmatch}, Bash fails to properly
16311 handle backslashes in character classes:
16314 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
16319 This is extremely unfortunate, since you are likely to use this code to
16320 handle Posix or MS-DOS absolute file names. To work around this
16321 bug, always put the backslash first:
16324 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
16326 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
16330 Many Bourne shells cannot handle closing brackets in character classes
16333 Some shells also have problems with backslash escaping in case you do not want
16334 to match the backslash: both a backslash and the escaped character match this
16335 pattern. To work around this, specify the character class in a variable, so
16336 that quote removal does not apply afterwards, and the special characters don't
16337 have to be backslash-escaped:
16340 $ @kbd{case '\' in [\<]) echo OK;; esac}
16342 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
16346 Even with this, Solaris @command{ksh} matches a backslash if the set
16348 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
16350 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
16351 a closing parenthesis if not specified in a character class:
16354 $ @kbd{case foo in *\)*) echo fail ;; esac}
16356 $ @kbd{case foo in *')'*) echo fail ;; esac}
16360 Some shells, such as Ash 0.3.8, are confused by an empty
16361 @code{case}/@code{esac}:
16364 ash-0.3.8 $ @kbd{case foo in esac;}
16365 @error{}Syntax error: ";" unexpected (expecting ")")
16368 Posix requires @command{case} to give an exit status of 0 if no cases
16369 match. However, @command{/bin/sh} in Solaris 10 does not obey this
16370 rule. Meanwhile, it is unclear whether a case that matches, but
16371 contains no statements, must also change the exit status to 0. The M4sh
16372 macro @code{AS_CASE} works around these inconsistencies.
16375 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
16377 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
16384 @prindex @command{cd}
16385 Posix 1003.1-2001 requires that @command{cd} must support
16386 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16387 with @option{-L} being the default. However, traditional shells do
16388 not support these options, and their @command{cd} command has the
16389 @option{-P} behavior.
16391 Portable scripts should assume neither option is supported, and should
16392 assume neither behavior is the default. This can be a bit tricky,
16393 since the Posix default behavior means that, for example,
16394 @samp{ls ..} and @samp{cd ..} may refer to different directories if
16395 the current logical directory is a symbolic link. It is safe to use
16396 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
16397 Also, Autoconf-generated scripts check for this problem when computing
16398 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
16399 so it is safe to @command{cd} to these variables.
16401 See @xref{Special Shell Variables}, for portability problems involving
16402 @command{cd} and the @env{CDPATH} environment variable.
16403 Also please see the discussion of the @command{pwd} command.
16407 @item @command{echo}
16408 @c -----------------
16409 @prindex @command{echo}
16410 The simple @command{echo} is probably the most surprising source of
16411 portability troubles. It is not possible to use @samp{echo} portably
16412 unless both options and escape sequences are omitted. Don't expect any
16415 Do not use backslashes in the arguments, as there is no consensus on
16416 their handling. For @samp{echo '\n' | wc -l}, the @command{sh} of
16417 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
16418 The problem is truly @command{echo}: all the shells
16419 understand @samp{'\n'} as the string composed of a backslash and an
16420 @samp{n}. Within a command substitution, @samp{echo 'string\c'} will
16421 mess up the internal state of ksh88 on AIX 6.1 so that it will print
16422 the first character @samp{s} only, followed by a newline, and then
16423 entirely drop the output of the next echo in a command substitution.
16425 Because of these problems, do not pass a string containing arbitrary
16426 characters to @command{echo}. For example, @samp{echo "$foo"} is safe
16427 only if you know that @var{foo}'s value cannot contain backslashes and
16428 cannot start with @samp{-}.
16430 If this may not be true, @command{printf} is in general safer and
16431 easier to use than @command{echo} and @command{echo -n}. Thus, scripts
16432 where portability is not a major concern should use @command{printf
16433 '%s\n'} whenever @command{echo} could fail, and similarly use
16434 @command{printf %s} instead of @command{echo -n}. For portable shell
16435 scripts, instead, it is suggested to use a here-document like this:
16443 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
16444 which choose between various portable implementations: @samp{echo}
16445 or @samp{print} where they work, @command{printf} if it is available,
16446 or else other creative tricks in order to work around the above problems.
16449 @item @command{eval}
16450 @c -----------------
16451 @prindex @command{eval}
16452 The @command{eval} command is useful in limited circumstances, e.g.,
16453 using commands like @samp{eval table_$key=\$value} and @samp{eval
16454 value=table_$key} to simulate a hash table when the key is known to be
16457 You should also be wary of common bugs in @command{eval} implementations.
16458 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
16459 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
16460 4.2.5), the arguments of @samp{eval} are evaluated in a context where
16461 @samp{$?} is 0, so they exhibit behavior like this:
16464 $ @kbd{false; eval 'echo $?'}
16468 The correct behavior here is to output a nonzero value,
16469 but portable scripts should not rely on this.
16471 You should not rely on @code{LINENO} within @command{eval}.
16472 @xref{Special Shell Variables}.
16474 Note that, even though these bugs are easily avoided,
16475 @command{eval} is tricky to use on arbitrary arguments.
16476 It is obviously unwise to use @samp{eval $cmd} if the string value of
16477 @samp{cmd} was derived from an untrustworthy source. But even if the
16478 string value is valid, @samp{eval $cmd} might not work as intended,
16479 since it causes field splitting and file name expansion to occur twice,
16480 once for the @command{eval} and once for the command itself. It is
16481 therefore safer to use @samp{eval "$cmd"}. For example, if @var{cmd}
16482 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
16483 equivalent of @samp{cat test;.c} if there happens to be a file named
16484 @file{test;.c} in the current directory; and this in turn
16485 mistakenly attempts to invoke @command{cat} on the file @file{test} and
16486 then execute the command @command{.c}. To avoid this problem, use
16487 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
16489 However, suppose that you want to output the text of the evaluated
16490 command just before executing it. Assuming the previous example,
16491 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
16492 this output doesn't show the user that @samp{test;.c} is the actual name
16493 of the copied file. Conversely, @samp{eval "echo Executing: $cmd"}
16494 works on this example, but it fails with @samp{cmd='cat foo >bar'},
16495 since it mistakenly replaces the contents of @file{bar} by the
16496 string @samp{cat foo}. No simple, general, and portable solution to
16497 this problem is known.
16499 @item @command{exec}
16500 @c -----------------
16501 @prindex @command{exec}
16502 Posix describes several categories of shell built-ins. Special
16503 built-ins (such as @command{exit}) must impact the environment of the
16504 current shell, and need not be available through @command{exec}. All
16505 other built-ins are regular, and must not propagate variable assignments
16506 to the environment of the current shell. However, the group of regular
16507 built-ins is further distinguished by commands that do not require a
16508 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
16509 are offered as a more efficient version of something that must still be
16510 found in a @env{PATH} search (such as @command{echo}). Posix is not
16511 clear on whether @command{exec} must work with the list of 17 utilities
16512 that are invoked without a @env{PATH} search, and many platforms lack an
16513 executable for some of those built-ins:
16516 $ @kbd{sh -c 'exec cd /tmp'}
16517 sh: line 0: exec: cd: not found
16520 All other built-ins that provide utilities specified by Posix must have
16521 a counterpart executable that exists on @env{PATH}, although Posix
16522 allows @command{exec} to use the built-in instead of the executable.
16523 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
16526 $ @kbd{bash -c 'pwd --version' | head -n1}
16527 bash: line 0: pwd: --: invalid option
16528 pwd: usage: pwd [-LP]
16529 $ @kbd{bash -c 'exec pwd --version' | head -n1}
16530 pwd (GNU coreutils) 6.10
16531 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
16532 pdksh: pwd: --: unknown option
16535 When it is desired to avoid a regular shell built-in, the workaround is
16536 to use some other forwarding command, such as @command{env} or
16537 @command{nice}, that will ensure a path search:
16540 $ @kbd{pdksh -c 'exec true --version' | head -n1}
16541 $ @kbd{pdksh -c 'nice true --version' | head -n1}
16542 true (GNU coreutils) 6.10
16543 $ @kbd{pdksh -c 'env true --version' | head -n1}
16544 true (GNU coreutils) 6.10
16547 @item @command{exit}
16548 @c -----------------
16549 @prindex @command{exit}
16550 The default value of @command{exit} is supposed to be @code{$?};
16551 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
16552 perform @samp{exit 0}.
16555 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
16557 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
16559 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
16563 Using @samp{exit $?} restores the expected behavior.
16565 Some shell scripts, such as those generated by @command{autoconf}, use a
16566 trap to clean up before exiting. If the last shell command exited with
16567 nonzero status, the trap also exits with nonzero status so that the
16568 invoker can tell that an error occurred.
16570 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
16571 trap ignores the @code{exit} command's argument. In these shells, a trap
16572 cannot determine whether it was invoked by plain @code{exit} or by
16573 @code{exit 1}. Instead of calling @code{exit} directly, use the
16574 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
16578 @item @command{export}
16579 @c -------------------
16580 @prindex @command{export}
16581 The builtin @command{export} dubs a shell variable @dfn{environment
16582 variable}. Each update of exported variables corresponds to an update
16583 of the environment variables. Conversely, each environment variable
16584 received by the shell when it is launched should be imported as a shell
16585 variable marked as exported.
16587 Alas, many shells, such as Solaris @command{/bin/sh},
16588 IRIX 6.3, IRIX 5.2,
16589 AIX 4.1.5, and Digital Unix 4.0, forget to
16590 @command{export} the environment variables they receive. As a result,
16591 two variables coexist: the environment variable and the shell
16592 variable. The following code demonstrates this failure:
16603 when run with @samp{FOO=foo} in the environment, these shells print
16604 alternately @samp{foo} and @samp{bar}, although they should print only
16605 @samp{foo} and then a sequence of @samp{bar}s.
16607 Therefore you should @command{export} again each environment variable
16608 that you update; the export can occur before or after the assignment.
16610 Posix is not clear on whether the @command{export} of an undefined
16611 variable causes the variable to be defined with the value of an empty
16612 string, or merely marks any future definition of a variable by that name
16613 for export. Various shells behave differently in this regard:
16616 $ @kbd{sh -c 'export foo; env | grep foo'}
16617 $ @kbd{ash -c 'export foo; env | grep foo'}
16621 @item @command{false}
16622 @c ------------------
16623 @prindex @command{false}
16624 Don't expect @command{false} to exit with status 1: in native
16625 Solaris @file{/bin/false} exits with status 255.
16628 @item @command{for}
16629 @c ----------------
16630 @prindex @command{for}
16631 To loop over positional arguments, use:
16641 You may @emph{not} leave the @code{do} on the same line as @code{for},
16642 since some shells improperly grok:
16650 If you want to explicitly refer to the positional arguments, given the
16651 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
16654 for arg in $@{1+"$@@"@}; do
16660 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
16661 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
16662 item @samp{$@@}, for more.
16668 @prindex @command{if}
16669 Using @samp{!} is not portable. Instead of:
16672 if ! cmp -s file file.new; then
16681 if cmp -s file file.new; then :; else
16687 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
16688 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
16692 AS_IF([cmp -s file file.new], [], [mv file.new file])
16695 This is especially useful in other M4 macros, where the @dfn{then} and
16696 @dfn{else} branches might be macro arguments.
16698 Some very old shells did not reset the exit status from an @command{if}
16699 with no @command{else}:
16702 $ @kbd{if (exit 42); then true; fi; echo $?}
16707 whereas a proper shell should have printed @samp{0}. But this is no
16708 longer a portability problem; any shell that supports functions gets it
16709 correct. However, it explains why some makefiles have lengthy
16713 if test -f "$file"; then
16714 install "$file" "$dest"
16721 @item @command{printf}
16722 @c ------------------
16723 @prindex @command{printf}
16724 A format string starting with a @samp{-} can cause problems.
16725 Bash interprets it as an option and
16726 gives an error. And @samp{--} to mark the end of options is not good
16727 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
16728 literally as the format string. Putting the @samp{-} in a @samp{%c}
16729 or @samp{%s} is probably easiest:
16735 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
16738 $ @kbd{printf '\045'}
16739 bash: printf: `%': missing format character
16742 Large outputs may cause trouble. On Solaris 2.5.1 through 10, for
16743 example, @file{/usr/bin/printf} is buggy, so when using
16744 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
16747 Since @command{printf} is not always a shell builtin, there is a
16748 potential speed penalty for using @code{printf '%s\n'} as a replacement
16749 for an @command{echo} that does not interpret @samp{\} or leading
16750 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
16751 -r --} for this role instead.
16753 For a discussion of portable alternatives to both @command{printf}
16754 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
16757 @item @command{pwd}
16758 @c ----------------
16759 @prindex @command{pwd}
16760 With modern shells, plain @command{pwd} outputs a ``logical''
16761 directory name, some of whose components may be symbolic links. These
16762 directory names are in contrast to ``physical'' directory names, whose
16763 components are all directories.
16765 Posix 1003.1-2001 requires that @command{pwd} must support
16766 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16767 with @option{-L} being the default. However, traditional shells do
16768 not support these options, and their @command{pwd} command has the
16769 @option{-P} behavior.
16771 Portable scripts should assume neither option is supported, and should
16772 assume neither behavior is the default. Also, on many hosts
16773 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
16774 does not require this behavior and portable scripts should not rely on
16777 Typically it's best to use plain @command{pwd}. On modern hosts this
16778 outputs logical directory names, which have the following advantages:
16782 Logical names are what the user specified.
16784 Physical names may not be portable from one installation
16785 host to another due to network file system gymnastics.
16787 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
16788 some parent directory, but plain @command{pwd} cannot fail for this
16792 Also please see the discussion of the @command{cd} command.
16795 @item @command{read}
16796 @c -----------------
16797 @prindex @command{read}
16798 No options are portable, not even support @option{-r} (Solaris
16799 @command{/bin/sh} for example).
16803 @item @command{set}
16804 @c ----------------
16805 @prindex @command{set}
16806 With the FreeBSD 6.0 shell, the @command{set} command (without
16807 any options) does not sort its output.
16809 The @command{set} builtin faces the usual problem with arguments
16811 dash. Modern shells such as Bash or Zsh understand @option{--} to specify
16812 the end of the options (any argument after @option{--} is a parameter,
16813 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
16814 10 @command{/bin/sh}) simply stop option
16815 processing as soon as a non-option argument is found. Therefore, use
16816 @samp{dummy} or simply @samp{x} to end the option processing, and use
16817 @command{shift} to pop it out:
16820 set x $my_list; shift
16823 Avoid @samp{set -}, e.g., @samp{set - $my_list}. Posix no
16824 longer requires support for this command, and in traditional shells
16825 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
16826 makes scripts harder to debug.
16828 Some nonstandard shells do not recognize more than one option
16829 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line). It is
16830 better to combine them:
16836 @cindex @command{set -e}
16837 The option @option{-e} has historically been underspecified, with enough
16838 ambiguities to cause numerous differences across various shell
16839 implementations. Perhaps the best reference is
16840 @uref{http://www.opengroup.org/@/austin/@/mailarchives/@/ag-review/@/msg03507.html,
16841 this link}, recommending a change to Posix 2008 to match @command{ksh88}
16842 behavior. Note that mixing @code{set -e} and shell functions is asking
16856 According to the recommendation, @samp{one} should always be output
16857 regardless of whether the @command{rm} failed, because it occurs within
16858 the body of the shell function @samp{doit} invoked on the left side of
16859 @samp{||}, where the effects of @samp{set -e} are not enforced.
16860 Likewise, @samp{two} should never be printed, since the failure of
16861 @command{rm} does not abort the function, such that the status of
16864 The BSD shell has had several problems with the @option{-e}
16865 option. Older versions of the BSD
16866 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
16867 @samp{case} when @option{-e} was in effect, causing the shell to exit
16868 unexpectedly in some cases. This was particularly a problem with
16869 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
16870 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
16871 wrapper works around the bug (@pxref{Failure in Make Rules}).
16873 Even relatively-recent versions of the BSD shell (e.g.,
16874 OpenBSD 3.4) wrongly exit with @option{-e} if a command within
16875 @samp{&&} fails inside a compound statement. For example:
16881 test -n "$foo" && exit 1
16884 test -n "$foo" && exit 1
16890 does not print @samp{two}. One workaround is to use @samp{if test -n
16891 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
16892 Another possibility is to warn BSD users not to use @samp{sh -e}.
16894 When @samp{set -e} is in effect, a failed command substitution in
16895 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
16898 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
16899 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
16905 Moreover, a command substitution, successful or not, causes this shell to
16906 exit from a failing outer command even in presence of an @samp{&&} list:
16909 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
16911 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
16915 Portable scripts should not use @samp{set -e} if @command{trap} is used
16916 to install an exit handler. This is because Tru64/OSF 5.1 @command{sh}
16917 sometimes enters the trap handler with the exit status of the command
16918 prior to the one that triggered the errexit handler:
16921 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
16923 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
16928 Thus, when writing a script in M4sh, rather than trying to rely on
16929 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
16930 statement where it is desirable to abort on failure.
16932 @cindex @command{set -b}
16933 @cindex @command{set -m}
16934 Job control is not provided by all shells, so the use of @samp{set -m}
16935 or @samp{set -b} must be done with care. When using @command{zsh} in
16936 native mode, asynchronous notification (@samp{set -b}) is enabled by
16937 default, and using @samp{emulate sh} to switch to Posix mode does not
16938 clear this setting (although asynchronous notification has no impact
16939 unless job monitoring is also enabled). Also, @command{zsh} 4.3.10 and
16940 earlier have a bug where job control can be manipulated in interactive
16941 shells, but not in subshells or scripts. Furthermore, some shells, like
16942 @command{pdksh}, fail to treat subshells as interactive, even though the
16946 $ @kbd{echo $ZSH_VERSION}
16948 $ @kbd{set -m; echo $?}
16950 $ @kbd{zsh -c 'set -m; echo $?'}
16951 set: can't change option: -m
16952 $ @kbd{(set -m); echo $?}
16953 set: can't change option: -m
16955 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
16961 @item @command{shift}
16962 @c ------------------
16963 @prindex @command{shift}
16964 Not only is @command{shift}ing a bad idea when there is nothing left to
16965 shift, but in addition it is not portable: the shell of MIPS
16966 RISC/OS 4.52 refuses to do it.
16968 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
16969 it is also absent in many pre-Posix shells.
16972 @item @command{source}
16973 @c -------------------
16974 @prindex @command{source}
16975 This command is not portable, as Posix does not require it; use
16976 @command{.} instead.
16979 @item @command{test}
16980 @c -----------------
16981 @prindex @command{test}
16982 The @code{test} program is the way to perform many file and string
16983 tests. It is often invoked by the alternate name @samp{[}, but using
16984 that name in Autoconf code is asking for trouble since it is an M4 quote
16987 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
16988 present in all implementations, and have been marked obsolete by Posix
16989 2008. This is because there are inherent ambiguities in using them.
16990 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
16991 check whether two strings are both non-empty, but if @samp{$1} is the
16992 literal @samp{!}, then some implementations of @command{test} treat it
16993 as a negation of the unary operator @option{-a}.
16995 Thus, portable uses of @command{test} should never have more than four
16996 arguments, and scripts should use shell constructs like @samp{&&} and
16997 @samp{||} instead. If you combine @samp{&&} and @samp{||} in the same
16998 statement, keep in mind that they have equal precedence, so it is often
16999 better to parenthesize even when this is redundant. For example:
17003 test "X$a" = "X$b" -a \
17004 '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
17007 test "X$a" = "X$b" &&
17008 @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
17011 @command{test} does not process options like most other commands do; for
17012 example, it does not recognize the @option{--} argument as marking the
17015 It is safe to use @samp{!} as a @command{test} operator. For example,
17016 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
17017 -d foo; @dots{}} is not.
17020 @item @command{test} (files)
17021 @c -------------------------
17022 To enable @command{configure} scripts to support cross-compilation, they
17023 shouldn't do anything that tests features of the build system instead of
17024 the host system. But occasionally you may find it necessary to check
17025 whether some arbitrary file exists. To do so, use @samp{test -f} or
17026 @samp{test -r}. Do not use @samp{test -x}, because 4.3BSD does not
17027 have it. Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
17028 lacks it. To test for symbolic links on systems that have them, use
17029 @samp{test -h} rather than @samp{test -L}; either form conforms to
17030 Posix 1003.1-2001, but older shells like Solaris 8
17031 @code{/bin/sh} support only @option{-h}.
17033 @item @command{test} (strings)
17034 @c ---------------------------
17035 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
17036 not null, but this usage is not portable to traditional platforms like
17037 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
17040 Posix also says that @samp{test ! "@var{string}"},
17041 @samp{test -n "@var{string}"} and
17042 @samp{test -z "@var{string}"} work with any string, but many
17043 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
17044 Digital Unix 4, etc.)@: get confused if
17045 @var{string} looks like an operator:
17049 test: argument expected
17051 test: argument expected
17054 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
17055 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
17056 strings, but in practice this is not true for troublesome strings that
17057 look like operators or parentheses, or that begin with @samp{-}.
17059 It is best to protect such strings with a leading @samp{X}, e.g.,
17060 @samp{test "X@var{string}" != X} rather than @samp{test -n
17061 "@var{string}"} or @samp{test ! "@var{string}"}.
17063 It is common to find variations of the following idiom:
17066 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
17071 to take an action when a token matches a given pattern. Such constructs
17072 should be avoided by using:
17075 case $ac_feature in
17076 *[!-a-zA-Z0-9_]*) @var{action};;
17080 If the pattern is a complicated regular expression that cannot be
17081 expressed as a shell pattern, use something like this instead:
17084 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
17088 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
17089 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
17090 @samp{@var{foo}} contains backslashes.
17094 @item @command{trap}
17095 @c -----------------
17096 @prindex @command{trap}
17097 It is safe to trap at least the signals 1, 2, 13, and 15. You can also
17098 trap 0, i.e., have the @command{trap} run when the script ends (either via an
17099 explicit @command{exit}, or the end of the script). The trap for 0 should be
17100 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
17101 will invoke the trap at the end of this function.
17103 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
17104 specified signals to their default values, but many common shells (e.g.,
17105 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
17106 ``command'' named @command{-} when the specified conditions arise.
17107 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
17108 reset traps, as this is supported by a larger set of shells, but there
17109 are still shells like @command{dash} that mistakenly try to execute
17110 @command{1} instead of resetting the traps. Therefore, there is no
17111 portable workaround, except for @samp{trap - 0}, for which
17112 @samp{trap '' 0} is a portable substitute.
17114 Although Posix is not absolutely clear on this point, it is widely
17115 admitted that when entering the trap @samp{$?} should be set to the exit
17116 status of the last command run before the trap. The ambiguity can be
17117 summarized as: ``when the trap is launched by an @command{exit}, what is
17118 the @emph{last} command run: that before @command{exit}, or
17119 @command{exit} itself?''
17121 Bash considers @command{exit} to be the last command, while Zsh and
17122 Solaris @command{/bin/sh} consider that when the trap is run it is
17123 @emph{still} in the @command{exit}, hence it is the previous exit status
17124 that the trap receives:
17127 $ @kbd{cat trap.sh}
17130 $ @kbd{zsh trap.sh}
17132 $ @kbd{bash trap.sh}
17136 The portable solution is then simple: when you want to @samp{exit 42},
17137 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
17138 set the exit status to 42 for Zsh, and the second to trigger the trap
17139 and pass 42 as exit status for Bash. In M4sh, this is covered by using
17142 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
17143 reset to 0 by empty lines if the code is inside @command{trap}.
17146 $ @kbd{trap 'false}
17154 Fortunately, this bug only affects @command{trap}.
17156 Several shells fail to execute an exit trap that is defined inside a
17157 subshell, when the last command of that subshell is not a builtin. A
17158 workaround is to use @samp{exit $?} as the shell builtin.
17161 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
17163 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
17164 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
17169 Likewise, older implementations of @command{bash} failed to preserve
17170 @samp{$?} across an exit trap consisting of a single cleanup command.
17173 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
17175 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
17177 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
17181 @item @command{true}
17182 @c -----------------
17183 @prindex @command{true}
17184 @c Info cannot handle `:' in index entries.
17185 @c @prindex @command{:}
17186 Don't worry: as far as we know @command{true} is portable.
17187 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
17188 portable shell community tends to prefer using @command{:}. This has a
17189 funny side effect: when asked whether @command{false} is more portable
17190 than @command{true} Alexandre Oliva answered:
17193 In a sense, yes, because if it doesn't exist, the shell will produce an
17194 exit status of failure, which is correct for @command{false}, but not
17195 for @command{true}.
17200 @item @command{unset}
17201 @c ------------------
17202 @prindex @command{unset}
17203 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
17204 when @code{FOO} is not set. You can use
17210 if you are not sure that @code{FOO} is set.
17212 A few ancient shells lack @command{unset} entirely. For some variables
17213 such as @code{PS1}, you can use a neutralizing value instead:
17219 Usually, shells that do not support @command{unset} need less effort to
17220 make the environment sane, so for example is not a problem if you cannot
17221 unset @command{CDPATH} on those shells. However, Bash 2.01 mishandles
17222 @code{unset MAIL} in some cases and dumps core. So, you should do
17226 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
17230 @xref{Special Shell Variables}, for some neutralizing values. Also, see
17231 @ref{export, , Limitations of Builtins}, for
17232 the case of environment variables.
17234 @item @command{wait}
17235 @c -----------------
17236 @prindex @command{wait}
17237 The exit status of @command{wait} is not always reliable.
17240 @node Limitations of Usual Tools
17241 @section Limitations of Usual Tools
17242 @cindex Limitations of usual tools
17244 The small set of tools you can expect to find on any machine can still
17245 include some limitations you should be aware of.
17247 @comment Between this list and the list of builtins above, we should
17248 @comment mention all the tools in GNU Coding Standards ``Utilities in
17249 @comment Makefiles''.
17251 @c This table includes things like `@command{expr} (|)', so we can't
17252 @c use @table @command.
17254 @item @command{awk}
17255 @c ----------------
17256 @prindex @command{awk}
17257 Don't leave white space before the opening parenthesis in a user function call.
17258 Posix does not allow this and GNU Awk rejects it:
17261 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
17262 BEGIN @{ die () @}'}
17263 gawk: cmd. line:2: BEGIN @{ die () @}
17264 gawk: cmd. line:2: ^ parse error
17265 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
17266 BEGIN @{ die() @}'}
17270 Posix says that if a program contains only @samp{BEGIN} actions, and
17271 contains no instances of @code{getline}, then the program merely
17272 executes the actions without reading input. However, traditional Awk
17273 implementations (such as Solaris 10 @command{awk}) read and discard
17274 input in this case. Portable scripts can redirect input from
17275 @file{/dev/null} to work around the problem. For example:
17278 awk 'BEGIN @{print "hello world"@}' </dev/null
17281 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
17282 @samp{$1}) retain their value from the last record read, if no
17283 intervening @samp{getline} occurred. However, some implementations
17284 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
17285 @samp{awk}) reset these variables. A workaround is to use an
17286 intermediate variable prior to the @samp{END} block. For example:
17289 $ @kbd{cat end.awk}
17291 END @{ print "a", $1, $NF, "b", tmp @}
17292 $ @kbd{echo 1 | awk -f end.awk}
17294 $ @kbd{echo 1 | gawk -f end.awk}
17298 If you want your program to be deterministic, don't depend on @code{for}
17302 $ @kbd{cat for.awk}
17309 $ @kbd{gawk -f for.awk </dev/null}
17312 $ @kbd{nawk -f for.awk </dev/null}
17317 Some Awk implementations, such as HP-UX 11.0's native one,
17321 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
17322 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
17324 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
17326 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
17331 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
17332 or use a simple test to reject such implementations.
17334 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
17338 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
17342 AIX version 5.2 has an arbitrary limit of 399 on the
17343 length of regular expressions and literal strings in an Awk program.
17345 Traditional Awk implementations derived from Unix version 7, such as
17346 Solaris @command{/bin/awk}, have many limitations and do not
17347 conform to Posix. Nowadays @code{AC_PROG_AWK} (@pxref{Particular
17348 Programs}) finds you an Awk that doesn't have these problems, but if
17349 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
17352 Traditional Awk does not support multidimensional arrays or user-defined
17355 Traditional Awk does not support the @option{-v} option. You can use
17356 assignments after the program instead, e.g., @code{$AWK '@{print v
17357 $1@}' v=x}; however, don't forget that such assignments are not
17358 evaluated until they are encountered (e.g., after any @code{BEGIN}
17361 Traditional Awk does not support the keywords @code{delete} or @code{do}.
17363 Traditional Awk does not support the expressions
17364 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
17365 or @code{@var{a}^=@var{b}}.
17367 Traditional Awk does not support the predefined @code{CONVFMT} variable.
17369 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
17370 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
17371 @code{sqrt}, and @code{substr}.
17373 Traditional Awk @code{getline} is not at all compatible with Posix;
17376 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
17377 @code{in} keyword. For example, it lacks @code{if (i in a) @dots{}}.
17379 In code portable to both traditional and modern Awk, @code{FS} must be a
17380 string containing just one ordinary character, and similarly for the
17381 field-separator argument to @code{split}.
17383 Traditional Awk has a limit of 99 fields in a record. Since some Awk
17384 implementations, like Tru64's, split the input even if you don't refer
17385 to any field in the script, to circumvent this problem, set @samp{FS}
17386 to an unusual character and use @code{split}.
17388 Traditional Awk has a limit of at most 99 bytes in a number formatted by
17389 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
17392 The original version of Awk had a limit of at most 99 bytes per
17393 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
17394 per run of non-special characters in a @code{printf} format, but these
17395 bugs have been fixed on all practical hosts that we know of.
17397 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
17398 of at most 3070 bytes.
17400 @item @command{basename}
17401 @c ---------------------
17402 @prindex @command{basename}
17403 Not all hosts have a working @command{basename}.
17404 You can use @command{expr} instead.
17406 @c AS_BASENAME is to be replaced by a better API.
17408 Not all hosts have a working @command{basename}, and you should instead
17409 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
17410 @command{expr} if you need to strip a suffix. For example:
17413 a=`basename "$aname"` # This is not portable.
17414 a=`AS_BASENAME(["$aname"])` # This is more portable.
17416 # This is not portable.
17417 c=`basename "$cname" .c`
17419 # This is more portable.
17420 c=`AS_BASENAME(["$cname"])`
17422 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
17428 @item @command{cat}
17429 @c ----------------
17430 @prindex @command{cat}
17431 Don't rely on any option.
17436 @prindex @command{cc}
17437 The command @samp{cc -c foo.c} traditionally produces an object file
17438 named @file{foo.o}. Most compilers allow @option{-c} to be combined
17439 with @option{-o} to specify a different object file name, but
17440 Posix does not require this combination and a few compilers
17441 lack support for it. @xref{C Compiler}, for how GNU Make
17442 tests for this feature with @code{AC_PROG_CC_C_O}.
17444 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
17445 (such as CDS on Reliant Unix) leave a @file{foo.o}.
17447 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
17448 assemble. @samp{cc -c foo.S} appears to succeed, but in fact does
17451 The default executable, produced by @samp{cc foo.c}, can be
17454 @item @file{a.out} --- usual Posix convention.
17455 @item @file{b.out} --- i960 compilers (including @command{gcc}).
17456 @item @file{a.exe} --- DJGPP port of @command{gcc}.
17457 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
17458 @item @file{foo.exe} --- various MS-DOS compilers.
17461 The C compiler's traditional name is @command{cc}, but other names like
17462 @command{gcc} are common. Posix 1003.1-2001 specifies the
17463 name @command{c99}, but older Posix editions specified
17464 @command{c89} and anyway these standard names are rarely used in
17465 practice. Typically the C compiler is invoked from makefiles that use
17466 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
17469 @item @command{chgrp}
17470 @itemx @command{chown}
17471 @c -------------------
17472 @prindex @command{chgrp}
17473 @prindex @command{chown}
17474 It is not portable to change a file's group to a group that the owner
17475 does not belong to.
17477 @item @command{chmod}
17478 @c ------------------
17479 @prindex @command{chmod}
17480 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
17481 instead, for two reasons. First, plain @option{-w} does not necessarily
17482 make the file unwritable, since it does not affect mode bits that
17483 correspond to bits in the file mode creation mask. Second,
17484 Posix says that the @option{-w} might be interpreted as an
17485 implementation-specific option, not as a mode; Posix suggests
17486 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
17487 @samp{--} does not work on some older hosts.
17490 @item @command{cmp}
17491 @c ----------------
17492 @prindex @command{cmp}
17493 @command{cmp} performs a raw data comparison of two files, while
17494 @command{diff} compares two text files. Therefore, if you might compare
17495 DOS files, even if only checking whether two files are different, use
17496 @command{diff} to avoid spurious differences due to differences of
17502 @prindex @command{cp}
17503 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
17504 obsolescent and its behavior on special files is implementation-defined.
17505 Use @option{-R} instead. On GNU hosts the two options
17506 are equivalent, but on Solaris hosts (for example) @code{cp -r}
17507 reads from pipes instead of replicating them.
17509 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
17510 trailing slashes at the end of nonexistent destination directories. To
17511 avoid this problem, omit the trailing slashes. For example, use
17512 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
17513 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
17515 @c This is thanks to Ian.
17516 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
17517 its @command{mv} does.
17519 @cindex timestamp resolution
17520 Traditionally, file timestamps had 1-second resolution, and @samp{cp
17521 -p} copied the timestamps exactly. However, many modern file systems
17522 have timestamps with 1-nanosecond resolution. Unfortunately, @samp{cp
17523 -p} implementations truncate timestamps when copying files, so this
17524 can result in the destination file appearing to be older than the
17525 source. The exact amount of truncation depends on the resolution of
17526 the system calls that @command{cp} uses; traditionally this was
17527 @code{utime}, which has 1-second resolution, but some newer
17528 @command{cp} implementations use @code{utimes}, which has
17529 1-microsecond resolution. These newer implementations include GNU
17530 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
17531 later. Unfortunately as of January 2006 there is still no system
17532 call to set timestamps to the full nanosecond resolution.
17534 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
17535 ownerships. But whether it actually does copy ownerships or not is a
17536 system dependent policy decision implemented by the kernel. If the
17537 kernel allows it then it happens. If the kernel does not allow it then
17538 it does not happen. It is not something @command{cp} itself has control
17541 In Unix System V any user can chown files to any other user, and System
17542 V also has a non-sticky @file{/tmp}. That probably derives from the
17543 heritage of System V in a business environment without hostile users.
17545 to be a more secure model where only root can @command{chown} files and
17546 a sticky @file{/tmp} is used. That undoubtedly derives from the heritage
17547 of BSD in a campus environment.
17549 GNU/Linux and Solaris by default follow BSD, but
17550 can be configured to allow a System V style @command{chown}. On the
17551 other hand, HP-UX follows System V, but can
17552 be configured to use the modern security model and disallow
17553 @command{chown}. Since it is an administrator-configurable parameter
17554 you can't use the name of the kernel as an indicator of the behavior.
17558 @item @command{date}
17559 @c -----------------
17560 @prindex @command{date}
17561 Some versions of @command{date} do not recognize special @samp{%} directives,
17562 and unfortunately, instead of complaining, they just pass them through,
17563 and exit with success:
17567 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
17573 @item @command{diff}
17574 @c -----------------
17575 @prindex @command{diff}
17576 Option @option{-u} is nonportable.
17578 Some implementations, such as Tru64's, fail when comparing to
17579 @file{/dev/null}. Use an empty file instead.
17582 @item @command{dirname}
17583 @c --------------------
17584 @prindex @command{dirname}
17585 Not all hosts have a working @command{dirname}, and you should instead
17586 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}). For example:
17589 dir=`dirname "$file"` # This is not portable.
17590 dir=`AS_DIRNAME(["$file"])` # This is more portable.
17594 @item @command{egrep}
17595 @c ------------------
17596 @prindex @command{egrep}
17597 Posix 1003.1-2001 no longer requires @command{egrep},
17598 but many hosts do not yet support the Posix
17599 replacement @code{grep -E}. Also, some traditional implementations do
17600 not work on long input lines. To work around these problems, invoke
17601 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
17603 Portable extended regular expressions should use @samp{\} only to escape
17604 characters in the string @samp{$()*+.?[\^@{|}. For example, @samp{\@}}
17605 is not portable, even though it typically matches @samp{@}}.
17607 The empty alternative is not portable. Use @samp{?} instead. For
17608 instance with Digital Unix v5.0:
17611 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
17613 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
17615 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
17620 @command{$EGREP} also suffers the limitations of @command{grep}
17621 (@pxref{grep, , Limitations of Usual Tools}).
17623 @item @command{expr}
17624 @c -----------------
17625 @prindex @command{expr}
17626 Not all implementations obey the Posix rule that @samp{--} separates
17627 options from arguments; likewise, not all implementations provide the
17628 extension to Posix that the first argument can be treated as part of a
17629 valid expression rather than an invalid option if it begins with
17630 @samp{-}. When performing arithmetic, use @samp{expr 0 + $var} if
17631 @samp{$var} might be a negative number, to keep @command{expr} from
17632 interpreting it as an option.
17634 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
17635 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
17636 misinterpreting @var{word}.
17638 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
17640 @item @command{expr} (@samp{|})
17641 @prindex @command{expr} (@samp{|})
17642 You can use @samp{|}. Although Posix does require that @samp{expr
17643 ''} return the empty string, it does not specify the result when you
17644 @samp{|} together the empty string (or zero) with the empty string. For
17651 Posix 1003.2-1992 returns the empty string
17652 for this case, but traditional Unix returns @samp{0} (Solaris is
17653 one such example). In Posix 1003.1-2001, the specification was
17654 changed to match traditional Unix's behavior (which is
17655 bizarre, but it's too late to fix this). Please note that the same
17656 problem does arise when the empty string results from a computation,
17660 expr bar : foo \| foo : bar
17664 Avoid this portability problem by avoiding the empty string.
17667 @item @command{expr} (@samp{:})
17668 @c ----------------------------
17669 @prindex @command{expr}
17670 Portable @command{expr} regular expressions should use @samp{\} to
17671 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
17672 For example, alternation, @samp{\|}, is common but Posix does not
17673 require its support, so it should be avoided in portable scripts.
17674 Similarly, @samp{\+} and @samp{\?} should be avoided.
17676 Portable @command{expr} regular expressions should not begin with
17677 @samp{^}. Patterns are automatically anchored so leading @samp{^} is
17680 On the other hand, the behavior of the @samp{$} anchor is not portable
17681 on multi-line strings. Posix is ambiguous whether the anchor applies to
17682 each line, as was done in older versions of GNU Coreutils, or
17683 whether it applies only to the end of the overall string, as in
17684 Coreutils 6.0 and most other implementations.
17689 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
17691 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
17695 The Posix standard is ambiguous as to whether
17696 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
17697 In practice, it outputs the empty string on most platforms, but portable
17698 scripts should not assume this. For instance, the QNX 4.25 native
17699 @command{expr} returns @samp{0}.
17701 One might think that a way to get a uniform behavior would be to use
17702 the empty string as a default value:
17705 expr a : '\(b\)' \| ''
17709 Unfortunately this behaves exactly as the original expression; see the
17710 @command{expr} (@samp{|}) entry for more information.
17712 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
17713 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
17714 @command{expr} to fail if the matched substring is longer than 120
17715 bytes. In this case, you might want to fall back on @samp{echo|sed} if
17716 @command{expr} fails. Nowadays this is of practical importance only for
17717 the rare installer who mistakenly puts @file{/usr/ucb} before
17718 @file{/usr/bin} in @env{PATH}.
17720 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
17721 some cases. For example, the command
17723 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
17727 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
17728 This particular case can be worked around by substituting @samp{[^--]}
17731 Don't leave, there is some more!
17733 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
17734 the empty string, has a funny behavior in its exit status: it's always 1
17735 when parentheses are used!
17738 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
17740 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
17743 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
17745 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
17750 In practice this can be a big problem if you are ready to catch failures
17751 of @command{expr} programs with some other method (such as using
17752 @command{sed}), since you may get twice the result. For instance
17755 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
17759 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25. A
17760 simple workaround consists of testing @command{expr} and using a variable
17761 set to @command{expr} or to @command{false} according to the result.
17763 Tru64 @command{expr} incorrectly treats the result as a number, if it
17764 can be interpreted that way:
17767 $ @kbd{expr 00001 : '.*\(...\)'}
17771 On HP-UX 11, @command{expr} only supports a single
17775 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
17776 expr: More than one '\(' was used.
17780 @item @command{fgrep}
17781 @c ------------------
17782 @prindex @command{fgrep}
17783 Posix 1003.1-2001 no longer requires @command{fgrep},
17784 but many hosts do not yet support the Posix
17785 replacement @code{grep -F}. Also, some traditional implementations do
17786 not work on long input lines. To work around these problems, invoke
17787 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
17790 @item @command{find}
17791 @c -----------------
17792 @prindex @command{find}
17793 The option @option{-maxdepth} seems to be GNU specific.
17794 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
17795 commands do not understand it.
17797 The replacement of @samp{@{@}} is guaranteed only if the argument is
17798 exactly @emph{@{@}}, not if it's only a part of an argument. For
17799 instance on DU, and HP-UX 10.20 and HP-UX 11:
17803 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
17808 while GNU @command{find} reports @samp{./foo-./foo}.
17812 @item @command{grep}
17813 @c -----------------
17814 @prindex @command{grep}
17815 Portable scripts can rely on the @command{grep} options @option{-c},
17816 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
17817 options. For example, don't use @option{-w}, as Posix does not require
17818 it and Irix 6.5.16m's @command{grep} does not support it. Also,
17819 portable scripts should not combine @option{-c} with @option{-l},
17820 as Posix does not allow this.
17822 Some of the options required by Posix are not portable in practice.
17823 Don't use @samp{grep -q} to suppress output, because many @command{grep}
17824 implementations (e.g., Solaris) do not support @option{-q}.
17825 Don't use @samp{grep -s} to suppress output either, because Posix
17826 says @option{-s} does not suppress output, only some error messages;
17827 also, the @option{-s} option of traditional @command{grep} behaved
17828 like @option{-q} does in most modern implementations. Instead,
17829 redirect the standard output and standard error (in case the file
17830 doesn't exist) of @code{grep} to @file{/dev/null}. Check the exit
17831 status of @code{grep} to determine whether it found a match.
17833 Some traditional @command{grep} implementations do not work on long
17834 input lines. On AIX the default @code{grep} silently truncates long
17835 lines on the input before matching.
17837 Also, many implementations do not support multiple regexps
17838 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
17839 or honor only the last pattern (e.g., IRIX 6.5 and NeXT). To
17840 work around these problems, invoke @code{AC_PROG_GREP} and then use
17843 Another possible workaround for the multiple @option{-e} problem is to
17844 separate the patterns by newlines, for example:
17852 except that this fails with traditional @command{grep}
17853 implementations and with OpenBSD 3.8 @command{grep}.
17855 Traditional @command{grep} implementations (e.g., Solaris) do not
17856 support the @option{-E} or @option{-F} options. To work around these
17857 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
17858 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}. Even if you are
17859 willing to require support for Posix @command{grep}, your script should
17860 not use both @option{-E} and @option{-F}, since Posix does not allow
17863 Portable @command{grep} regular expressions should use @samp{\} only to
17864 escape characters in the string @samp{$()*.0123456789[\^@{@}}. For example,
17865 alternation, @samp{\|}, is common but Posix does not require its
17866 support in basic regular expressions, so it should be avoided in
17867 portable scripts. Solaris and HP-UX @command{grep} do not support it.
17868 Similarly, the following escape sequences should also be avoided:
17869 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
17870 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
17872 Posix does not specify the behavior of @command{grep} on binary files.
17873 An example where this matters is using BSD @command{grep} to
17874 search text that includes embedded ANSI escape sequences for
17875 colored output to terminals (@samp{\033[m} is the sequence to restore
17876 normal output); the behavior depends on whether input is seekable:
17879 $ @kbd{printf 'esc\033[mape\n' > sample}
17880 $ @kbd{grep . sample}
17881 Binary file sample matches
17882 $ @kbd{cat sample | grep .}
17887 @item @command{join}
17888 @c -----------------
17889 @prindex @command{join}
17890 Solaris 8 @command{join} has bugs when the second operand is standard
17891 input, and when standard input is a pipe. For example, the following
17892 shell script causes Solaris 8 @command{join} to loop forever:
17899 cat file | join file -
17902 Use @samp{join - file} instead.
17907 @prindex @command{ln}
17908 @cindex Symbolic links
17909 Don't rely on @command{ln} having a @option{-f} option. Symbolic links
17910 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
17912 For versions of the DJGPP before 2.04,
17913 @command{ln} emulates symbolic links
17914 to executables by generating a stub that in turn calls the real
17915 program. This feature also works with nonexistent files like in the
17916 Posix spec. So @samp{ln -s file link} generates @file{link.exe},
17917 which attempts to call @file{file.exe} if run. But this feature only
17918 works for executables, so @samp{cp -p} is used instead for these
17919 systems. DJGPP versions 2.04 and later have full support
17920 for symbolic links.
17925 @prindex @command{ls}
17926 @cindex Listing directories
17927 The portable options are @option{-acdilrtu}. Current practice is for
17928 @option{-l} to output both owner and group, even though ancient versions
17929 of @command{ls} omitted the group.
17931 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
17932 to standard output if @file{foo} did not exist. Hence a shell command
17933 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
17934 was equivalent to @samp{sources='*.c not found'} in the absence of
17935 @samp{.c} files. This is no longer a practical problem, since current
17936 @command{ls} implementations send diagnostics to standard error.
17938 The behavior of @command{ls} on a directory that is being concurrently
17939 modified is not always predictable, because of a data race where cached
17940 information returned by @code{readdir} does not match the current
17941 directory state. In fact, MacOS 10.5 has an intermittent bug where
17942 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
17943 once if other files were added or removed from the directory immediately
17944 prior to the @command{ls} call. Since @command{ls} already sorts its
17945 output, the duplicate entries can be avoided by piping the results
17946 through @code{uniq}.
17949 @item @command{mkdir}
17950 @c ------------------
17951 @prindex @command{mkdir}
17952 @cindex Making directories
17953 No @command{mkdir} option is portable to older systems. Instead of
17954 @samp{mkdir -p @var{file-name}}, you should use
17955 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
17956 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
17958 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
17959 go-w -p @var{dir}}, often leads to trouble. FreeBSD
17960 @command{mkdir} incorrectly attempts to change the permissions of
17961 @var{dir} even if it already exists. HP-UX 11.23 and
17962 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
17963 any newly-created parents of @var{dir}.
17965 Posix does not clearly specify whether @samp{mkdir -p foo}
17966 should succeed when @file{foo} is a symbolic link to an already-existing
17967 directory. The GNU Core Utilities 5.1.0 @command{mkdir}
17968 succeeds, but Solaris @command{mkdir} fails.
17970 Traditional @code{mkdir -p} implementations suffer from race conditions.
17971 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
17972 at the same time, both processes might detect that @file{a} is missing,
17973 one might create @file{a}, then the other might try to create @file{a}
17974 and fail with a @code{File exists} diagnostic. The GNU Core
17975 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
17976 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
17977 race-free when two processes invoke @code{mkdir -p} simultaneously, but
17978 earlier versions are vulnerable. Solaris @command{mkdir} is still
17979 vulnerable as of Solaris 10, and other traditional Unix systems are
17980 probably vulnerable too. This possible race is harmful in parallel
17981 builds when several Make rules call @code{mkdir -p} to
17982 construct directories. You may use
17983 @code{install-sh -d} as a safe replacement, provided this script is
17984 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
17985 OK, but copies from older versions are vulnerable.
17988 @item @command{mkfifo}
17989 @itemx @command{mknod}
17990 @c -------------------
17991 @prindex @command{mkfifo}
17992 @prindex @command{mknod}
17993 The GNU Coding Standards state that @command{mknod} is safe to use on
17994 platforms where it has been tested to exist; but it is generally portable
17995 only for creating named FIFOs, since device numbers are
17996 platform-specific. Autotest uses @command{mkfifo} to implement parallel
17997 testsuites. Posix states that behavior is unspecified when opening a
17998 named FIFO for both reading and writing; on at least Cygwin, this
17999 results in failure on any attempt to read or write to that file
18002 @item @command{mktemp}
18003 @c -------------------
18004 @prindex @command{mktemp}
18005 @cindex Creating temporary files
18006 Shell scripts can use temporary files safely with @command{mktemp}, but
18007 it does not exist on all systems. A portable way to create a safe
18008 temporary file name is to create a temporary directory with mode 700 and
18009 use a file inside this directory. Both methods prevent attackers from
18010 gaining control, though @command{mktemp} is far less likely to fail
18011 gratuitously under attack.
18013 Here is sample code to create a new temporary directory safely:
18016 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
18017 # Use mktemp if possible; otherwise fall back on mkdir,
18018 # with $RANDOM to make collisions less likely.
18022 (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
18024 test -n "$tmp" && test -d "$tmp"
18026 tmp=$TMPDIR/foo$$-$RANDOM
18027 (umask 077 && mkdir "$tmp")
18034 @prindex @command{mv}
18035 @cindex Moving open files
18036 The only portable options are @option{-f} and @option{-i}.
18038 Moving individual files between file systems is portable (it was in Unix
18040 but it is not always atomic: when doing @samp{mv new existing}, there's
18041 a critical section where neither the old nor the new version of
18042 @file{existing} actually exists.
18044 On some systems moving files from @file{/tmp} can sometimes cause
18045 undesirable (but perfectly valid) warnings, even if you created these
18046 files. This is because @file{/tmp} belongs to a group that ordinary
18047 users are not members of, and files created in @file{/tmp} inherit
18048 the group of @file{/tmp}. When the file is copied, @command{mv} issues
18049 a diagnostic without failing:
18052 $ @kbd{touch /tmp/foo}
18053 $ @kbd{mv /tmp/foo .}
18054 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
18062 This annoying behavior conforms to Posix, unfortunately.
18064 Moving directories across mount points is not portable, use @command{cp}
18067 DOS variants cannot rename or remove open files, and do not
18068 support commands like @samp{mv foo bar >foo}, even though this is
18069 perfectly portable among Posix hosts.
18074 @prindex @command{od}
18076 In Mac OS X 10.3, @command{od} does not support the
18077 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
18078 @option{-t}, or the XSI option @option{-s}. The only
18079 supported Posix option is @option{-v}, and the only supported
18080 XSI options are those in @option{-bcdox}. The BSD
18081 @command{hexdump} program can be used instead.
18083 This problem no longer exists in Mac OS X 10.4.3.
18088 @prindex @command{rm}
18089 The @option{-f} and @option{-r} options are portable.
18091 It is not portable to invoke @command{rm} without operands. For
18092 example, on many systems @samp{rm -f -r} (with no other arguments)
18093 silently succeeds without doing anything, but it fails with a diagnostic
18096 A file might not be removed even if its parent directory is writable
18097 and searchable. Many Posix hosts cannot remove a mount point, a named
18098 stream, a working directory, or a last link to a file that is being
18101 DOS variants cannot rename or remove open files, and do not
18102 support commands like @samp{rm foo >foo}, even though this is
18103 perfectly portable among Posix hosts.
18105 @item @command{rmdir}
18106 @c ------------------
18107 @prindex @command{rmdir}
18108 Just as with @command{rm}, some platforms refuse to remove a working
18112 @item @command{sed}
18113 @c ----------------
18114 @prindex @command{sed}
18115 Patterns should not include the separator (unless escaped), even as part
18116 of a character class. In conformance with Posix, the Cray
18117 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
18118 Even when escaped, patterns should not include separators that are also
18119 used as @command{sed} metacharacters. For example, GNU sed 4.0.9 rejects
18120 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
18121 before evaluating the basic regular expression.
18123 Avoid empty patterns within parentheses (i.e., @samp{\(\)}). Posix does
18124 not require support for empty patterns, and Unicos 9 @command{sed} rejects
18127 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
18129 Sed scripts should not use branch labels longer than 7 characters and
18130 should not contain comments. HP-UX sed has a limit of 99 commands
18131 (not counting @samp{:} commands) and
18132 48 labels, which can not be circumvented by using more than one script
18133 file. It can execute up to 19 reads with the @samp{r} command per cycle.
18134 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
18135 about 6000 bytes for the internal representation of commands.
18137 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
18138 NetBSD 1.4.2's, incorrectly try to interpret the second
18139 @samp{;} as a command:
18142 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
18143 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
18146 Input should not have unreasonably long lines, since some @command{sed}
18147 implementations have an input buffer limited to 4000 bytes. Likewise,
18148 not all @command{sed} implementations can handle embedded @code{NUL} or
18149 a missing trailing newline.
18151 Portable @command{sed} regular expressions should use @samp{\} only to escape
18152 characters in the string @samp{$()*.0123456789[\^n@{@}}. For example,
18153 alternation, @samp{\|}, is common but Posix does not require its
18154 support, so it should be avoided in portable scripts. Solaris
18155 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
18156 deletes only lines that contain the literal string @samp{a|b}.
18157 Similarly, @samp{\+} and @samp{\?} should be avoided.
18159 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
18161 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
18162 quite portable to current hosts, but was not supported by some ancient
18163 @command{sed} implementations like SVR3.
18165 Some @command{sed} implementations, e.g., Solaris, restrict the special
18166 role of the asterisk @samp{*} to one-character regular expressions and
18167 back-references, and the special role of interval expressions
18168 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
18169 to one-character regular expressions. This may lead to unexpected behavior:
18172 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
18174 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
18178 The @option{-e} option is mostly portable.
18179 However, its argument
18180 cannot start with @samp{a}, @samp{c}, or @samp{i},
18181 as this runs afoul of a Tru64 5.1 bug.
18182 Also, its argument cannot be empty, as this fails on AIX 5.3.
18183 Some people prefer to use @samp{-e}:
18186 sed -e '@var{command-1}' \
18187 -e '@var{command-2}'
18191 as opposed to the equivalent:
18201 The following usage is sometimes equivalent:
18204 sed '@var{command-1};@var{command-2}'
18207 but Posix says that this use of a semicolon has undefined effect if
18208 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
18209 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
18210 should use semicolon only with simple scripts that do not use these
18213 Commands inside @{ @} brackets are further restricted. Posix says that
18214 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
18215 each command must be followed immediately by a newline, without any
18216 intervening blanks or semicolons. The closing bracket must be alone on
18217 a line, other than white space preceding or following it.
18219 Contrary to yet another urban legend, you may portably use @samp{&} in
18220 the replacement part of the @code{s} command to mean ``what was
18221 matched''. All descendants of Unix version 7 @command{sed}
18223 don't have first hand experience with older @command{sed} implementations) have
18226 Posix requires that you must not have any white space between
18227 @samp{!} and the following command. It is OK to have blanks between
18228 the address and the @samp{!}. For instance, on Solaris:
18231 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
18232 @error{}Unrecognized command: /bar/ ! p
18233 $ @kbd{echo "foo" | sed -n '/bar/! p'}
18234 @error{}Unrecognized command: /bar/! p
18235 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
18239 Posix also says that you should not combine @samp{!} and @samp{;}. If
18240 you use @samp{!}, it is best to put it on a command that is delimited by
18241 newlines rather than @samp{;}.
18243 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
18244 @samp{w} commands be followed by exactly one space before their argument.
18245 On the other hand, no white space is allowed between @samp{:} and the
18246 subsequent label name.
18248 If a sed script is specified on the command line and ends in an
18249 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
18250 should be followed by a newline. Otherwise some @command{sed}
18251 implementations (e.g., OpenBSD 3.9) do not append a newline to the
18254 Many @command{sed} implementations (e.g., MacOS X 10.4,
18255 OpenBSD 3.9, Solaris 10
18256 @command{/usr/ucb/sed}) strip leading white space from the text of
18257 @samp{a}, @samp{c}, and @samp{i} commands. Prepend a backslash to
18258 work around this incompatibility with Posix:
18261 $ @kbd{echo flushleft | sed 'a\}
18266 $ @kbd{echo foo | sed 'a\}
18273 Posix requires that with an empty regular expression, the last non-empty
18274 regular expression from either an address specification or substitution
18275 command is applied. However, busybox 1.6.1 complains when using a
18276 substitution command with a replacement containing a back-reference to
18277 an empty regular expression; the workaround is repeating the regular
18281 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
18282 sed: No previous regexp.
18283 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
18288 @item @command{sed} (@samp{t})
18289 @c ---------------------------
18290 @prindex @command{sed} (@samp{t})
18291 Some old systems have @command{sed} that ``forget'' to reset their
18292 @samp{t} flag when starting a new cycle. For instance on MIPS
18293 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
18294 script (the line numbers are not actual part of the texts):
18297 s/keep me/kept/g # a
18333 Why? When processing line 1, (c) matches, therefore sets the @samp{t}
18334 flag, and the output is produced. When processing
18335 line 2, the @samp{t} flag is still set (this is the bug). Command (a)
18336 fails to match, but @command{sed} is not supposed to clear the @samp{t}
18337 flag when a substitution fails. Command (b) sees that the flag is set,
18338 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
18339 instead of @samp{deleted}. When processing line (3), @samp{t} is clear,
18340 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
18341 Finally, since the flag is clear, line 4 is processed properly.
18343 There are two things one should remember about @samp{t} in @command{sed}.
18344 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
18345 succeeded, not only the immediately preceding substitution. Therefore,
18346 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
18347 line, to reset the @samp{t} flag where needed.
18349 Secondly, you cannot rely on @command{sed} to clear the flag at each new
18352 One portable implementation of the script above is:
18363 @item @command{sleep}
18364 @c ------------------
18365 @prindex @command{sleep}
18366 Using @command{sleep} is generally portable. However, remember that
18367 adding a @command{sleep} to work around timestamp issues, with a minimum
18368 granularity of one second, doesn't scale well for parallel builds on
18369 modern machines with sub-second process completion.
18371 @item @command{sort}
18372 @c -----------------
18373 @prindex @command{sort}
18374 Remember that sort order is influenced by the current locale. Inside
18375 @file{configure}, the C locale is in effect, but in Makefile snippets,
18376 you may need to specify @code{LC_ALL=C sort}.
18378 @item @command{tar}
18379 @c ----------------
18380 @prindex @command{tar}
18381 There are multiple file formats for @command{tar}; if you use Automake,
18382 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
18383 level of portability to use.
18386 @item @command{touch}
18387 @c ------------------
18388 @prindex @command{touch}
18389 @cindex timestamp resolution
18390 If you specify the desired timestamp (e.g., with the @option{-r}
18391 option), @command{touch} typically uses the @code{utime} or
18392 @code{utimes} system call, which can result in the same kind of
18393 timestamp truncation problems that @samp{cp -p} has.
18395 On ancient BSD systems, @command{touch} or any command that
18396 results in an empty file does not update the timestamps, so use a
18397 command like @command{echo} as a workaround.
18399 GNU @command{touch} 3.16r (and presumably all before that)
18400 fails to work on SunOS 4.1.3 when the empty file is on an
18401 NFS-mounted 4.2 volume.
18402 However, these problems are no longer of practical concern.
18406 @prindex @command{tr}
18407 @cindex carriage return, deleting
18408 @cindex newline, deleting
18409 @cindex deleting carriage return
18410 Not all versions of @command{tr} handle all backslash character escapes.
18411 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
18412 Solaris contains more modern @command{tr} in other locations.
18413 Using octal escapes is more portable for carriage returns, since
18414 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
18415 literal carriage returns in scripts causes a number of other problems.
18416 But for other characters, like newline, using octal escapes ties the
18417 operation to ASCII, so it is better to use literal characters.
18420 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
18423 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
18425 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
18428 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
18432 Not all versions of @command{tr} recognize ranges of characters: at
18433 least Solaris @command{/usr/bin/tr} still fails to do so. But you can
18434 use @command{/usr/xpg4/bin/tr} instead.
18437 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
18439 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
18443 When providing two arguments, be sure the second string is at least as
18447 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
18449 $ @kbd{echo abc | coreutils/tr bc d}
18453 Posix requires @command{tr} to operate on binary files. But at least
18454 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
18455 @code{NUL} in the input prior to doing any translation. When using
18456 @command{tr} to process a binary file that may contain @code{NUL} bytes,
18457 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
18458 @command{/usr/xpg6/bin/tr} if that is available.
18461 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
18463 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
18465 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
18469 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
18470 octal escape for @code{NUL}.
18473 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
18475 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
18477 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
18484 @node Portable Make
18485 @chapter Portable Make Programming
18486 @prindex @command{make}
18487 @cindex Limitations of @command{make}
18489 Writing portable makefiles is an art. Since a makefile's commands are
18490 executed by the shell, you must consider the shell portability issues
18491 already mentioned. However, other issues are specific to @command{make}
18495 * $< in Ordinary Make Rules:: $< in ordinary rules
18496 * Failure in Make Rules:: Failing portably in rules
18497 * Special Chars in Names:: Special Characters in Macro Names
18498 * Backslash-Newline-Newline:: Empty last lines in macro definitions
18499 * Backslash-Newline Comments:: Spanning comments across line boundaries
18500 * Long Lines in Makefiles:: Line length limitations
18501 * Macros and Submakes:: @code{make macro=value} and submakes
18502 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
18503 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
18504 * Parallel Make:: Parallel @command{make} quirks
18505 * Comments in Make Rules:: Other problems with Make comments
18506 * obj/ and Make:: Don't name a subdirectory @file{obj}
18507 * make -k Status:: Exit status of @samp{make -k}
18508 * VPATH and Make:: @code{VPATH} woes
18509 * Single Suffix Rules:: Single suffix rules and separated dependencies
18510 * Timestamps and Make:: Subsecond timestamp resolution
18513 @node $< in Ordinary Make Rules
18514 @section @code{$<} in Ordinary Make Rules
18516 Posix says that the @samp{$<} construct in makefiles can be
18517 used only in inference rules and in the @samp{.DEFAULT} rule; its
18518 meaning in ordinary rules is unspecified. Solaris @command{make}
18519 for instance replaces it with the empty string. OpenBSD (3.0 and
18520 later) @command{make} diagnoses these uses and errors out.
18522 @node Failure in Make Rules
18523 @section Failure in Make Rules
18525 Posix 2008 requires that @command{make} must invoke each command with
18526 the equivalent of a @samp{sh -e -c} subshell, which causes the
18527 subshell to exit immediately if a subsidiary simple-command fails,
18528 although not all @command{make} implementations have historically
18529 followed this rule. For
18530 example, the command @samp{touch T; rm -f U} may attempt to
18531 remove @file{U} even if the @command{touch} fails, although this is not
18532 permitted with Posix make. One way to work around failures in simple
18533 commands is to reword them so that they always succeed, e.g., @samp{touch
18535 However, even this approach can run into common bugs in BSD
18536 implementations of the @option{-e} option of @command{sh} and
18537 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
18539 about porting to buggy BSD shells it may be simpler to migrate
18540 complicated @command{make} actions into separate scripts.
18542 @node Special Chars in Names
18543 @section Special Characters in Make Macro Names
18545 Posix limits macro names to nonempty strings containing only
18546 ASCII letters and digits, @samp{.}, and @samp{_}. Many
18547 @command{make} implementations allow a wider variety of characters, but
18548 portable makefiles should avoid them. It is portable to start a name
18549 with a special character, e.g., @samp{$(.FOO)}.
18551 Some ancient @command{make} implementations don't support leading
18552 underscores in macro names. An example is NEWS-OS 4.2R.
18555 $ @kbd{cat Makefile}
18558 all:; @@echo this is test
18560 Make: Must be a separator on rules line 2. Stop.
18561 $ @kbd{cat Makefile2}
18564 all:; @@echo this is test
18565 $ @kbd{make -f Makefile2}
18570 However, this problem is no longer of practical concern.
18572 @node Backslash-Newline-Newline
18573 @section Backslash-Newline-Newline in Make Macro Values
18575 @c This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
18576 @c but another hppa hpux 10.20 didn't have it. Bob Proulx
18577 @c <bob@proulx.com> thinks it was in hpux 8.0 too.
18578 On some versions of HP-UX, @command{make} reads multiple newlines
18579 following a backslash, continuing to the next non-empty line. For
18593 shows @code{FOO} equal to @code{one BAR = two}. Other implementations
18594 sensibly let a backslash continue only to the immediately following
18597 @node Backslash-Newline Comments
18598 @section Backslash-Newline in Make Comments
18600 According to Posix, Make comments start with @code{#}
18601 and continue until an unescaped newline is reached.
18604 $ @kbd{cat Makefile}
18611 $ @kbd{make} # GNU make
18616 However this is not always the case. Some implementations
18617 discard everything from @code{#} through the end of the line, ignoring any
18618 trailing backslash.
18621 $ @kbd{pmake} # BSD make
18622 "Makefile", line 3: Need an operator
18623 Fatal errors encountered -- cannot continue
18627 Therefore, if you want to comment out a multi-line definition, prefix each
18628 line with @code{#}, not only the first.
18636 @node Long Lines in Makefiles
18637 @section Long Lines in Makefiles
18639 Tru64 5.1's @command{make} has been reported to crash when given a
18640 makefile with lines longer than around 20 kB. Earlier versions are
18641 reported to exit with @code{Line too long} diagnostics.
18643 @node Macros and Submakes
18644 @section @code{make macro=value} and Submakes
18646 A command-line variable definition such as @code{foo=bar} overrides any
18647 definition of @code{foo} in a makefile. Some @command{make}
18648 implementations (such as GNU @command{make}) propagate this
18649 override to subsidiary invocations of @command{make}. Some other
18650 implementations do not pass the substitution along to submakes.
18653 $ @kbd{cat Makefile}
18660 $ @kbd{make foo=bar} # GNU make 3.79.1
18663 make[1]: Entering directory `/home/adl'
18665 make[1]: Leaving directory `/home/adl'
18666 $ @kbd{pmake foo=bar} # BSD make
18672 You have a few possibilities if you do want the @code{foo=bar} override
18673 to propagate to submakes. One is to use the @option{-e}
18674 option, which causes all environment variables to have precedence over
18675 the makefile macro definitions, and declare foo as an environment
18679 $ @kbd{env foo=bar make -e}
18682 The @option{-e} option is propagated to submakes automatically,
18683 and since the environment is inherited between @command{make}
18684 invocations, the @code{foo} macro is overridden in
18685 submakes as expected.
18687 This syntax (@code{foo=bar make -e}) is portable only when used
18688 outside of a makefile, for instance from a script or from the
18689 command line. When run inside a @command{make} rule, GNU
18690 @command{make} 3.80 and prior versions forget to propagate the
18691 @option{-e} option to submakes.
18693 Moreover, using @option{-e} could have unexpected side effects if your
18694 environment contains some other macros usually defined by the
18695 makefile. (See also the note about @code{make -e} and @code{SHELL}
18698 Another way to propagate overrides to submakes is to do it
18699 manually, from your makefile:
18705 $(MAKE) foo=$(foo) two
18710 You need to foresee all macros that a user might want to override if
18713 Makefiles generated by @command{automake} expand @code{$(AM_MAKEFLAGS)}
18714 on the command line of submakes, which can be used for propagated overrides
18715 (@pxref{Subdirectories, , Automake, automake, GNU Automake}).
18717 @node The Make Macro MAKEFLAGS
18718 @section The Make Macro MAKEFLAGS
18719 @cindex @code{MAKEFLAGS} and @command{make}
18720 @cindex @command{make} and @code{MAKEFLAGS}
18722 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
18723 current and recursive invocations of make, but allows implementations
18724 several formats for the variable. It is tricky to parse
18725 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
18726 or @option{-k} for continued execution are in effect. For example, you
18727 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
18728 contains single-letter options, since in the Cygwin version of
18729 GNU @command{make} it is either @option{--unix} or
18730 @option{--win32} with the second word containing single-letter options.
18733 $ @kbd{cat Makefile}
18735 @@echo MAKEFLAGS = $(MAKEFLAGS)
18739 MAKEFLAGS = --unix -k
18742 @node The Make Macro SHELL
18743 @section The Make Macro @code{SHELL}
18744 @cindex @code{SHELL} and @command{make}
18745 @cindex @command{make} and @code{SHELL}
18747 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
18748 macro to spawn shell processes and execute Make rules. This
18749 is a builtin macro supplied by @command{make}, but it can be modified
18750 by a makefile or by a command-line argument.
18752 Not all @command{make} implementations define this @code{SHELL} macro.
18754 @command{make} is an example; this implementation always uses
18755 @code{/bin/sh}. So it's a good idea to always define @code{SHELL} in
18756 your makefiles. If you use Autoconf, do
18763 If you use Automake, this is done for you.
18765 Do not force @code{SHELL = /bin/sh} because that is not correct
18766 everywhere. Remember, @file{/bin/sh} is not Posix compliant on many
18767 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
18768 Additionally, DJGPP lacks @code{/bin/sh}, and when its
18769 GNU @command{make} port sees such a setting it enters a
18770 special emulation mode where features like pipes and redirections are
18771 emulated on top of DOS's @command{command.com}. Unfortunately this
18772 emulation is incomplete; for instance it does not handle command
18773 substitutions. Using @code{@@SHELL@@} means that your makefile will
18774 benefit from the same improved shell, such as @command{bash} or
18775 @command{ksh}, that was discovered during @command{configure}, so that
18776 you aren't fighting two different sets of shell bugs between the two
18779 Posix-compliant @command{make} should never acquire the value of
18780 $(SHELL) from the environment, even when @code{make -e} is used
18781 (otherwise, think about what would happen to your rules if
18782 @code{SHELL=/bin/tcsh}).
18784 However not all @command{make} implementations have this exception.
18785 For instance it's not surprising that Tru64 @command{make} doesn't
18786 protect @code{SHELL}, since it doesn't use it.
18789 $ @kbd{cat Makefile}
18795 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e} # Tru64 Make
18798 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e} # GNU make
18803 Conversely, @command{make} is not supposed to export any changes to the
18804 macro @code{SHELL} to child processes. Again, many implementations
18808 $ @kbd{cat Makefile}
18812 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh} # BSD Make, GNU make 3.80
18815 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh} # GNU make 3.81
18820 @node Parallel Make
18821 @section Parallel Make
18822 @cindex Parallel @command{make}
18824 Support for parallel execution in @command{make} implementation varies.
18825 Generally, using GNU make is your best bet. When NetBSD
18826 @command{make} is invoked with @option{-j@var{N}}, it will reuse the
18827 same shell for multiple commands within one recipe. This can have
18828 unexpected consequences.@footnote{Note that GNU make has
18829 heuristics to avoid spawning a shell at all if the command is deemed
18830 safe to be executed directly.} For example, change of directories or
18831 variables persist between commands:
18835 @@var=value; cd /; pwd; echo $$var; echo $$$$
18836 @@pwd; echo $$var; echo $$$$
18840 may output the following with @code{make -j1}:
18852 while without @option{-j1}, or with @option{-B}, the output looks less
18864 Another consequence of this is that, if one command in a recipe uses
18865 @code{exit 0} to indicate a successful exit, the shell will be gone
18866 and the remaining commands of this recipe will not be executed.
18868 The above example also shows additional status output NetBSD
18869 @command{make} produces in parallel mode for targets being updated.
18871 Furthermore, parallel NetBSD @command{make} will route standard error
18872 from commands that it spawns into its own standard output, and may
18873 remove leading whitespace from output lines.
18875 You can avoid these issues by using the @option{-B} option to enable
18876 compatibility semantics. However, that will effectively also disable
18877 all parallelism as that will cause prerequisites to be updated in the
18878 order they are listed in a rule.
18880 @node Comments in Make Rules
18881 @section Comments in Make Rules
18882 @cindex Comments in @file{Makefile} rules
18883 @cindex @file{Makefile} rules and comments
18885 Never put comments in a rule.
18887 Some @command{make} treat anything starting with a tab as a command for
18888 the current rule, even if the tab is immediately followed by a @code{#}.
18889 The @command{make} from Tru64 Unix V5.1 is one of them. The following
18890 makefile runs @code{# foo} through the shell.
18897 @node obj/ and Make
18898 @section The @file{obj/} Subdirectory and Make
18899 @cindex @file{obj/}, subdirectory
18900 @cindex BSD @command{make} and @file{obj/}
18902 Never name one of your subdirectories @file{obj/} if you don't like
18905 If an @file{obj/} directory exists, BSD @command{make} enters it
18906 before reading the makefile. Hence the makefile in the
18907 current directory is not read.
18910 $ @kbd{cat Makefile}
18913 $ @kbd{cat obj/Makefile}
18916 $ @kbd{make} # GNU make
18919 $ @kbd{pmake} # BSD make
18924 @node make -k Status
18925 @section Exit Status of @code{make -k}
18926 @cindex @code{make -k}
18928 Do not rely on the exit status of @code{make -k}. Some implementations
18929 reflect whether they encountered an error in their exit status; other
18930 implementations always succeed.
18933 $ @kbd{cat Makefile}
18936 $ @kbd{make -k; echo exit status: $?} # GNU make
18938 make: *** [all] Error 1
18940 $ @kbd{pmake -k; echo exit status: $?} # BSD make
18942 *** Error code 1 (continuing)
18946 @node VPATH and Make
18947 @section @code{VPATH} and Make
18948 @cindex @code{VPATH}
18950 Posix does not specify the semantics of @code{VPATH}. Typically,
18951 @command{make} supports @code{VPATH}, but its implementation is not
18954 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
18955 portable to recent-enough popular implementations of @command{make}, but
18956 to keep the resulting makefiles portable, a package's makefile
18957 prototypes must take the following issues into account. These issues
18958 are complicated and are often poorly understood, and installers who use
18959 @code{VPATH} should expect to find many bugs in this area. If you use
18960 @code{VPATH}, the simplest way to avoid these portability bugs is to
18961 stick with GNU @command{make}, since it is the most
18962 commonly-used @command{make} among Autoconf users.
18964 Here are some known issues with some @code{VPATH}
18968 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
18969 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
18970 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
18971 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
18972 * Tru64 Directory Magic:: @command{mkdir} goes wild on Tru64
18973 * Make Target Lookup:: More details about @code{VPATH} lookup
18976 @node Variables listed in VPATH
18977 @subsection Variables listed in @code{VPATH}
18978 @cindex @code{VPATH} and variables
18979 @cindex variables and @code{VPATH}
18981 Do not set @code{VPATH} to the value of another variable, for example
18982 @samp{VPATH = $(srcdir)}, because some ancient versions of
18983 @command{make} do not do variable substitutions on the value of
18984 @code{VPATH}. For example, use this
18987 srcdir = @@srcdir@@
18992 rather than @samp{VPATH = $(srcdir)}. Note that with GNU
18993 Automake, there is no need to set this yourself.
18995 @node VPATH and Double-colon
18996 @subsection @code{VPATH} and Double-colon Rules
18997 @cindex @code{VPATH} and double-colon rules
18998 @cindex double-colon rules and @code{VPATH}
19000 With ancient versions of Sun @command{make},
19001 any assignment to @code{VPATH} causes @command{make} to execute only
19002 the first set of double-colon rules.
19003 However, this problem is no longer of practical concern.
19005 @node $< in Explicit Rules
19006 @subsection @code{$<} Not Supported in Explicit Rules
19007 @cindex explicit rules, @code{$<}, and @code{VPATH}
19008 @cindex @code{$<}, explicit rules, and @code{VPATH}
19009 @cindex @code{VPATH}, explicit rules, and @code{$<}
19011 Using @code{$<} in explicit rules is not portable.
19012 The prerequisite file must be named explicitly in the rule. If you want
19013 to find the prerequisite via a @code{VPATH} search, you have to code the
19014 whole thing manually. @xref{Build Directories}.
19016 @node Automatic Rule Rewriting
19017 @subsection Automatic Rule Rewriting
19018 @cindex @code{VPATH} and automatic rule rewriting
19019 @cindex automatic rule rewriting and @code{VPATH}
19021 Some @command{make} implementations, such as Solaris and Tru64,
19022 search for prerequisites in @code{VPATH} and
19023 then rewrite each occurrence as a plain word in the rule.
19027 # This isn't portable to GNU make.
19034 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
19035 found in @file{../pkg/src}.
19037 However, this rule leads to real problems in practice. For example, if
19038 the source directory contains an ordinary file named @file{test} that is
19039 used in a dependency, Solaris @command{make} rewrites commands like
19040 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
19041 @dots{}}, which is typically undesirable. To avoid this problem,
19042 portable makefiles should never mention a source file whose name is that
19043 of a shell keyword like @file{until} or a shell command like
19044 @command{cat} or @command{gcc} or @command{test}.
19046 Because of these problems GNU @command{make} and many other
19047 @command{make} implementations do not rewrite commands, so portable
19049 search @code{VPATH} manually. It is tempting to write this:
19052 # This isn't portable to Solaris make.
19055 cp `test -f if.c || echo $(VPATH)/`if.c f.c
19059 However, the ``prerequisite rewriting'' still applies here. So if
19060 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
19064 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
19075 and thus fails. Oops.
19077 A simple workaround, and good practice anyway, is to use @samp{$?} and
19078 @samp{$@@} when possible:
19087 but this does not generalize well to commands with multiple
19088 prerequisites. A more general workaround is to rewrite the rule so that
19089 the prerequisite @file{if.c} never appears as a plain word. For
19090 example, these three rules would be safe, assuming @file{if.c} is in
19091 @file{../pkg/src} and the other files are in the working directory:
19096 cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
19098 cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
19100 cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
19103 Things get worse when your prerequisites are in a macro.
19107 HEADERS = f.h g.h h.h
19108 install-HEADERS: $(HEADERS)
19109 for i in $(HEADERS); do \
19110 $(INSTALL) -m 644 \
19111 `test -f $$i || echo $(VPATH)/`$$i \
19112 $(DESTDIR)$(includedir)/$$i; \
19116 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
19117 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
19118 where @code{f.h} and @code{g.h} are plain words and are hence
19119 subject to @code{VPATH} adjustments.
19121 If the three files are in @file{../pkg/src}, the rule is run as:
19124 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
19126 `test -f $i || echo ../pkg/src/`$i \
19127 /usr/local/include/$i; \
19131 where the two first @command{install} calls fail. For instance,
19132 consider the @code{f.h} installation:
19136 `test -f ../pkg/src/f.h || \
19139 /usr/local/include/../pkg/src/f.h;
19148 /usr/local/include/../pkg/src/f.h;
19151 Note that the manual @code{VPATH} search did not cause any problems here;
19152 however this command installs @file{f.h} in an incorrect directory.
19154 Trying to quote @code{$(HEADERS)} in some way, as we did for
19155 @code{foo.c} a few makefiles ago, does not help:
19158 install-HEADERS: $(HEADERS)
19159 headers='$(HEADERS)'; \
19160 for i in $$headers; do \
19161 $(INSTALL) -m 644 \
19162 `test -f $$i || echo $(VPATH)/`$$i \
19163 $(DESTDIR)$(includedir)/$$i; \
19167 Now, @code{headers='$(HEADERS)'} macro-expands to:
19170 headers='f.h g.h h.h'
19174 but @code{g.h} is still a plain word. (As an aside, the idiom
19175 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
19176 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
19177 syntax error on @code{for i in;}.)
19179 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
19183 HEADERS = f.h g.h h.h
19184 install-HEADERS: $(HEADERS)
19185 headers='$(HEADERS)'; \
19186 for i in $$headers; do \
19187 i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
19188 $(INSTALL) -m 644 \
19189 `test -f $$i || echo $(VPATH)/`$$i \
19190 $(DESTDIR)$(includedir)/$$i; \
19194 Automake does something similar. However the above hack works only if
19195 the files listed in @code{HEADERS} are in the current directory or a
19196 subdirectory; they should not be in an enclosing directory. If we had
19197 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
19198 build with Tru64 @command{make}. The reason is that not only does
19199 Tru64 @command{make} rewrite dependencies, but it also simplifies
19200 them. Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
19201 @code{../pkg/src/../f.h}. This obviously defeats any attempt to strip
19202 a leading @file{../pkg/src/} component.
19204 The following example makes the behavior of Tru64 @command{make}
19208 $ @kbd{cat Makefile}
19220 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
19221 @command{make} simplified it as @file{foo}. (Note that the @file{sub/}
19222 directory does not even exist, this just means that the simplification
19223 occurred before the file was checked for.)
19225 For the record here is how SunOS 4 @command{make} behaves on this
19230 make: Fatal error: Don't know how to make target `../foo'
19238 @node Tru64 Directory Magic
19239 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
19240 @cindex @code{VPATH} and prerequisite directories
19241 @cindex prerequisite directories and @code{VPATH}
19243 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
19244 @command{make} creates it in the current directory.
19247 $ @kbd{mkdir -p foo/bar build}
19249 $ @kbd{cat >Makefile <<END
19258 This can yield unexpected results if a rule uses a manual @code{VPATH}
19259 search as presented before.
19264 command `test -d foo/bar || echo ../`foo/bar
19267 The above @command{command} is run on the empty @file{foo/bar}
19268 directory that was created in the current directory.
19270 @node Make Target Lookup
19271 @subsection Make Target Lookup
19272 @cindex @code{VPATH}, resolving target pathnames
19274 GNU @command{make} uses a complex algorithm to decide when it
19275 should use files found via a @code{VPATH} search. @xref{Search
19276 Algorithm, , How Directory Searches are Performed, make, The GNU Make
19279 If a target needs to be rebuilt, GNU @command{make} discards the
19280 file name found during the @code{VPATH} search for this target, and
19281 builds the file locally using the file name given in the makefile.
19282 If a target does not need to be rebuilt, GNU @command{make} uses the
19283 file name found during the @code{VPATH} search.
19285 Other @command{make} implementations, like NetBSD @command{make}, are
19286 easier to describe: the file name found during the @code{VPATH} search
19287 is used whether the target needs to be rebuilt or not. Therefore
19288 new files are created locally, but existing files are updated at their
19289 @code{VPATH} location.
19291 OpenBSD and FreeBSD @command{make}, however,
19293 @code{VPATH} search for a dependency that has an explicit rule.
19294 This is extremely annoying.
19296 When attempting a @code{VPATH} build for an autoconfiscated package
19297 (e.g., @code{mkdir build && cd build && ../configure}), this means
19299 @command{make} builds everything locally in the @file{build}
19300 directory, while BSD @command{make} builds new files locally and
19301 updates existing files in the source directory.
19304 $ @kbd{cat Makefile}
19307 foo.x bar.x: newer.x
19308 @@echo Building $@@
19309 $ @kbd{touch ../bar.x}
19310 $ @kbd{touch ../newer.x}
19311 $ @kbd{make} # GNU make
19314 $ @kbd{pmake} # NetBSD make
19317 $ @kbd{fmake} # FreeBSD make, OpenBSD make
19320 $ @kbd{tmake} # Tru64 make
19323 $ @kbd{touch ../bar.x}
19324 $ @kbd{make} # GNU make
19326 $ @kbd{pmake} # NetBSD make
19328 $ @kbd{fmake} # FreeBSD make, OpenBSD make
19331 $ @kbd{tmake} # Tru64 make
19336 Note how NetBSD @command{make} updates @file{../bar.x} in its
19337 VPATH location, and how FreeBSD, OpenBSD, and Tru64
19338 @command{make} always
19339 update @file{bar.x}, even when @file{../bar.x} is up to date.
19341 Another point worth mentioning is that once GNU @command{make} has
19342 decided to ignore a @code{VPATH} file name (e.g., it ignored
19343 @file{../bar.x} in the above example) it continues to ignore it when
19344 the target occurs as a prerequisite of another rule.
19346 The following example shows that GNU @command{make} does not look up
19347 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
19348 because it ignored the @code{VPATH} result of @file{bar.x} while running
19349 the @code{bar.x: newer.x} rule.
19352 $ @kbd{cat Makefile}
19356 @@echo Building $@@
19360 $ @kbd{touch ../bar.x}
19361 $ @kbd{touch ../newer.x}
19362 $ @kbd{make} # GNU make
19365 cp: cannot stat `bar.x': No such file or directory
19366 make: *** [bar.y] Error 1
19367 $ @kbd{pmake} # NetBSD make
19371 $ @kbd{fmake} # FreeBSD make, OpenBSD make
19372 echo Building bar.x
19374 cp: cannot stat `bar.x': No such file or directory
19376 $ @kbd{tmake} # Tru64 make
19378 cp: bar.x: No such file or directory
19382 Note that if you drop away the command from the @code{bar.x: newer.x}
19383 rule, GNU @command{make} magically starts to work: it
19384 knows that @code{bar.x} hasn't been updated, therefore it doesn't
19385 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
19386 uses. Tru64 also works, but FreeBSD and OpenBSD
19390 $ @kbd{cat Makefile}
19397 $ @kbd{touch ../bar.x}
19398 $ @kbd{touch ../newer.x}
19399 $ @kbd{make} # GNU make
19402 $ @kbd{pmake} # NetBSD make
19405 $ @kbd{fmake} # FreeBSD make, OpenBSD make
19407 cp: cannot stat `bar.x': No such file or directory
19409 $ @kbd{tmake} # Tru64 make
19413 It seems the sole solution that would please every @command{make}
19414 implementation is to never rely on @code{VPATH} searches for targets.
19415 In other words, @code{VPATH} should be reserved to unbuilt sources.
19418 @node Single Suffix Rules
19419 @section Single Suffix Rules and Separated Dependencies
19420 @cindex Single Suffix Inference Rule
19421 @cindex Rule, Single Suffix Inference
19422 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
19423 (@samp{.from.to:}), but which @emph{destination} suffix is empty
19426 @cindex Separated Dependencies
19427 @dfn{Separated dependencies} simply refers to listing the prerequisite
19428 of a target, without defining a rule. Usually one can list on the one
19429 hand side, the rules, and on the other hand side, the dependencies.
19431 Solaris @command{make} does not support separated dependencies for
19432 targets defined by single suffix rules:
19435 $ @kbd{cat Makefile}
19440 $ @kbd{touch foo.in}
19447 while GNU Make does:
19453 Makefile foo foo.in
19456 Note it works without the @samp{foo: foo.in} dependency.
19459 $ @kbd{cat Makefile}
19468 and it works with double suffix inference rules:
19471 $ @kbd{cat Makefile}
19473 .SUFFIXES: .in .out
19480 As a result, in such a case, you have to write target rules.
19482 @node Timestamps and Make
19483 @section Timestamp Resolution and Make
19484 @cindex timestamp resolution
19485 Traditionally, file timestamps had 1-second resolution, and
19486 @command{make} used those timestamps to determine whether one file was
19487 newer than the other. However, many modern file systems have
19488 timestamps with 1-nanosecond resolution. Some @command{make}
19489 implementations look at the entire timestamp; others ignore the
19490 fractional part, which can lead to incorrect results. Normally this
19491 is not a problem, but in some extreme cases you may need to use tricks
19492 like @samp{sleep 1} to work around timestamp truncation bugs.
19494 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
19495 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
19496 Tools}). Hence you should be wary of rules like this:
19503 as @file{dest} often appears to be older than @file{src} after the
19504 timestamp is truncated, and this can cause @command{make} to do
19505 needless rework the next time it is invoked. To work around this
19506 problem, you can use a timestamp file, e.g.:
19517 @c ======================================== Portable C and C++ Programming
19519 @node Portable C and C++
19520 @chapter Portable C and C++ Programming
19521 @cindex Portable C and C++ programming
19523 C and C++ programs often use low-level features of the underlying
19524 system, and therefore are often more difficult to make portable to other
19527 Several standards have been developed to help make your programs more
19528 portable. If you write programs with these standards in mind, you can
19529 have greater confidence that your programs work on a wide variety
19532 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
19533 Standards Supported by GCC}
19536 @xref{Standards, , Language Standards Supported by
19537 GCC, gcc, Using the GNU Compiler Collection
19540 for a list of C-related standards. Many programs also assume the
19541 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
19543 Some old code is written to be portable to K&R C, which predates any C
19544 standard. K&R C compilers are no longer of practical interest, though,
19545 and the rest of section assumes at least C89, the first C standard.
19547 Program portability is a huge topic, and this section can only briefly
19548 introduce common pitfalls. @xref{System Portability, , Portability
19549 between System Types, standards, GNU Coding Standards}, for
19553 * Varieties of Unportability:: How to make your programs unportable
19554 * Integer Overflow:: When integers get too large
19555 * Preprocessor Arithmetic:: @code{#if} expression problems
19556 * Null Pointers:: Properties of null pointers
19557 * Buffer Overruns:: Subscript errors and the like
19558 * Volatile Objects:: @code{volatile} and signals
19559 * Floating Point Portability:: Portable floating-point arithmetic
19560 * Exiting Portably:: Exiting and the exit status
19563 @node Varieties of Unportability
19564 @section Varieties of Unportability
19565 @cindex portability
19567 Autoconf tests and ordinary programs often need to test what is allowed
19568 on a system, and therefore they may need to deliberately exceed the
19569 boundaries of what the standards allow, if only to see whether an
19570 optional feature is present. When you write such a program, you should
19571 keep in mind the difference between constraints, unspecified behavior,
19572 and undefined behavior.
19574 In C, a @dfn{constraint} is a rule that the compiler must enforce. An
19575 example constraint is that C programs must not declare a bit-field with
19576 negative width. Tests can therefore reliably assume that programs with
19577 negative-width bit-fields are rejected by a compiler that conforms
19580 @dfn{Unspecified behavior} is valid behavior, where the standard allows
19581 multiple possibilities. For example, the order of evaluation of
19582 function arguments is unspecified. Some unspecified behavior is
19583 @dfn{implementation-defined}, i.e., documented by the implementation,
19584 but since Autoconf tests cannot read the documentation they cannot
19585 distinguish between implementation-defined and other unspecified
19586 behavior. It is common for Autoconf tests to probe implementations to
19587 determine otherwise-unspecified behavior.
19589 @dfn{Undefined behavior} is invalid behavior, where the standard allows
19590 the implementation to do anything it pleases. For example,
19591 dereferencing a null pointer leads to undefined behavior. If possible,
19592 test programs should avoid undefined behavior, since a program with
19593 undefined behavior might succeed on a test that should fail.
19595 The above rules apply to programs that are intended to conform to the
19596 standard. However, strictly-conforming programs are quite rare, since
19597 the standards are so limiting. A major goal of Autoconf is to support
19598 programs that use implementation features not described by the standard,
19599 and it is fairly common for test programs to violate the above rules, if
19600 the programs work well enough in practice.
19602 @node Integer Overflow
19603 @section Integer Overflow
19604 @cindex integer overflow
19605 @cindex overflow, signed integer
19606 @cindex signed integer overflow
19607 @cindex wraparound arithmetic
19609 In practice many portable C programs assume that signed integer overflow wraps
19610 around reliably using two's complement arithmetic. Yet the C standard
19611 says that program behavior is undefined on overflow, and in a few cases
19612 C programs do not work on some modern implementations because their
19613 overflows do not wrap around as their authors expected. Conversely, in
19614 signed integer remainder, the C standard requires overflow
19615 behavior that is commonly not implemented.
19618 * Integer Overflow Basics:: Why integer overflow is a problem
19619 * Signed Overflow Examples:: Examples of code assuming wraparound
19620 * Optimization and Wraparound:: Optimizations that break uses of wraparound
19621 * Signed Overflow Advice:: Practical advice for signed overflow issues
19622 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
19625 @node Integer Overflow Basics
19626 @subsection Basics of Integer Overflow
19627 @cindex integer overflow
19628 @cindex overflow, signed integer
19629 @cindex signed integer overflow
19630 @cindex wraparound arithmetic
19632 In languages like C, unsigned integer overflow reliably wraps around;
19633 e.g., @code{UINT_MAX + 1} yields zero.
19634 This is guaranteed by the C standard and is
19635 portable in practice, unless you specify aggressive,
19636 nonstandard optimization options
19637 suitable only for special applications.
19639 In contrast, the C standard says that signed integer overflow leads to
19640 undefined behavior where a program can do anything, including dumping
19641 core or overrunning a buffer. The misbehavior can even precede the
19642 overflow. Such an overflow can occur during addition, subtraction,
19643 multiplication, division, and left shift.
19645 Despite this requirement of the standard, many C programs and Autoconf
19646 tests assume that signed integer overflow silently wraps around modulo a
19647 power of two, using two's complement arithmetic, so long as you cast the
19648 resulting value to a signed integer type or store it into a signed
19649 integer variable. If you use conservative optimization flags, such
19650 programs are generally portable to the vast majority of modern
19651 platforms, with a few exceptions discussed later.
19653 For historical reasons the C standard also allows implementations with
19654 ones' complement or signed magnitude arithmetic, but it is safe to
19655 assume two's complement nowadays.
19657 Also, overflow can occur when converting an out-of-range value to a
19658 signed integer type. Here a standard implementation must define what
19659 happens, but this might include raising an exception. In practice all
19660 known implementations support silent wraparound in this case, so you need
19661 not worry about other possibilities.
19663 @node Signed Overflow Examples
19664 @subsection Examples of Code Assuming Wraparound Overflow
19665 @cindex integer overflow
19666 @cindex overflow, signed integer
19667 @cindex signed integer overflow
19668 @cindex wraparound arithmetic
19670 There has long been a tension between what the C standard requires for
19671 signed integer overflow, and what C programs commonly assume. The
19672 standard allows aggressive optimizations based on assumptions that
19673 overflow never occurs, but many practical C programs rely on overflow
19674 wrapping around. These programs do not conform to the standard, but
19675 they commonly work in practice because compiler writers are
19676 understandably reluctant to implement optimizations that would break
19677 many programs, unless perhaps a user specifies aggressive optimization.
19679 The C Standard says that if a program has signed integer overflow its
19680 behavior is undefined, and the undefined behavior can even precede the
19681 overflow. To take an extreme example:
19683 @c Inspired by Robert Dewar's example in
19684 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
19686 if (password == expected_password)
19687 allow_superuser_privileges ();
19688 else if (counter++ == INT_MAX)
19691 printf ("%d password mismatches\n", counter);
19695 If the @code{int} variable @code{counter} equals @code{INT_MAX},
19696 @code{counter++} must overflow and the behavior is undefined, so the C
19697 standard allows the compiler to optimize away the test against
19698 @code{INT_MAX} and the @code{abort} call.
19699 Worse, if an earlier bug in the program lets the compiler deduce that
19700 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
19701 the C standard allows the compiler to optimize away the password test
19702 and generate code that allows superuser privileges unconditionally.
19704 Despite this requirement by the standard, it has long been common for C
19705 code to assume wraparound arithmetic after signed overflow, and all
19706 known practical C implementations support some C idioms that assume
19707 wraparound signed arithmetic, even if the idioms do not conform
19708 strictly to the standard. If your code looks like the following
19709 examples it will almost surely work with real-world compilers.
19711 Here is an example derived from the 7th Edition Unix implementation of
19712 @code{atoi} (1979-01-10):
19718 while (*p >= '0' && *p <= '9')
19719 n = n * 10 + *p++ - '0';
19720 return (f ? -n : n);
19724 Even if the input string is in range, on most modern machines this has
19725 signed overflow when computing the most negative integer (the @code{-n}
19726 overflows) or a value near an extreme integer (the first @code{+}
19729 Here is another example, derived from the 7th Edition implementation of
19730 @code{rand} (1979-01-10). Here the programmer expects both
19731 multiplication and addition to wrap on overflow:
19734 static long int randx = 1;
19736 randx = randx * 1103515245 + 12345;
19737 return (randx >> 16) & 077777;
19740 In the following example, derived from the GNU C Library 2.5
19741 implementation of @code{mktime} (2006-09-09), the code assumes
19742 wraparound arithmetic in @code{+} to detect signed overflow:
19746 int sec_requested, sec_adjustment;
19748 t1 = t + sec_requested;
19749 t2 = t1 + sec_adjustment;
19750 if (((t1 < t) != (sec_requested < 0))
19751 | ((t2 < t1) != (sec_adjustment < 0)))
19755 If your code looks like these examples, it is probably safe even though
19756 it does not strictly conform to the C standard. This might lead one to
19757 believe that one can generally assume wraparound on overflow, but that
19758 is not always true, as can be seen in the next section.
19760 @node Optimization and Wraparound
19761 @subsection Optimizations That Break Wraparound Arithmetic
19762 @cindex loop induction
19764 Compilers sometimes generate code that is incompatible with wraparound
19765 integer arithmetic. A simple example is an algebraic simplification: a
19766 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
19767 because it assumes that @code{i * 2000} does not overflow. The
19768 translation is not equivalent to the original when overflow occurs:
19769 e.g., in the typical case of 32-bit signed two's complement wraparound
19770 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
19771 the original expression returns @minus{}2147483 but the optimized
19772 version returns the mathematically correct value 2147484.
19774 More subtly, loop induction optimizations often exploit the undefined
19775 behavior of signed overflow. Consider the following contrived function
19780 sumc (int lo, int hi)
19784 for (i = lo; i <= hi; i++)
19791 To avoid multiplying by 53 each time through the loop, an optimizing
19792 compiler might internally transform @code{sumc} to the equivalent of the
19797 transformed_sumc (int lo, int hi)
19802 for (ic = lo * 53; ic <= hic; ic += 53)
19809 This transformation is allowed by the C standard, but it is invalid for
19810 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
19811 overflow in computing expressions like @code{hi * 53} can cause the
19812 expression @code{i <= hi} to yield a different value from the
19813 transformed expression @code{ic <= hic}.
19815 For this reason, compilers that use loop induction and similar
19816 techniques often do not support reliable wraparound arithmetic when a
19817 loop induction variable like @code{ic} is involved. Since loop
19818 induction variables are generated by the compiler, and are not visible
19819 in the source code, it is not always trivial to say whether the problem
19822 Hardly any code actually depends on wraparound arithmetic in cases like
19823 these, so in practice these loop induction optimizations are almost
19824 always useful. However, edge cases in this area can cause problems.
19829 for (j = 1; 0 < j; j *= 2)
19834 Here, the loop attempts to iterate through all powers of 2 that
19835 @code{int} can represent, but the C standard allows a compiler to
19836 optimize away the comparison and generate an infinite loop,
19837 under the argument that behavior is undefined on overflow. As of this
19838 writing this optimization is not done by any production version of
19839 GCC with @option{-O2}, but it might be performed by other
19840 compilers, or by more aggressive GCC optimization options,
19841 and the GCC developers have not decided whether it will
19842 continue to work with GCC and @option{-O2}.
19844 @node Signed Overflow Advice
19845 @subsection Practical Advice for Signed Overflow Issues
19846 @cindex integer overflow
19847 @cindex overflow, signed integer
19848 @cindex signed integer overflow
19849 @cindex wraparound arithmetic
19851 Ideally the safest approach is to avoid signed integer overflow
19852 entirely. For example, instead of multiplying two signed integers, you
19853 can convert them to unsigned integers, multiply the unsigned values,
19854 then test whether the result is in signed range.
19856 Rewriting code in this way will be inconvenient, though, particularly if
19857 the signed values might be negative. Also, it may hurt
19858 performance. Using unsigned arithmetic to check for overflow is
19859 particularly painful to do portably and efficiently when dealing with an
19860 integer type like @code{uid_t} whose width and signedness vary from
19861 platform to platform.
19863 Furthermore, many C applications pervasively assume wraparound behavior
19864 and typically it is not easy to find and remove all these assumptions.
19865 Hence it is often useful to maintain nonstandard code that assumes
19866 wraparound on overflow, instead of rewriting the code. The rest of this
19867 section attempts to give practical advice for this situation.
19869 If your code wants to detect signed integer overflow in @code{sum = a +
19870 b}, it is generally safe to use an expression like @code{(sum < a) != (b
19873 If your code uses a signed loop index, make sure that the index cannot
19874 overflow, along with all signed expressions derived from the index.
19875 Here is a contrived example of problematic code with two instances of
19879 for (i = INT_MAX - 10; i <= INT_MAX; i++)
19882 report_overflow ();
19888 Because of the two overflows, a compiler might optimize away or
19889 transform the two comparisons in a way that is incompatible with the
19890 wraparound assumption.
19892 If your code uses an expression like @code{(i * 2000) / 1000} and you
19893 actually want the multiplication to wrap around on overflow, use
19894 unsigned arithmetic
19895 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
19897 If your code assumes wraparound behavior and you want to insulate it
19898 against any GCC optimizations that would fail to support that
19899 behavior, you should use GCC's @option{-fwrapv} option, which
19900 causes signed overflow to wrap around reliably (except for division and
19901 remainder, as discussed in the next section).
19903 If you need to port to platforms where signed integer overflow does not
19904 reliably wrap around (e.g., due to hardware overflow checking, or to
19905 highly aggressive optimizations), you should consider debugging with
19906 GCC's @option{-ftrapv} option, which causes signed overflow to
19907 raise an exception.
19909 @node Signed Integer Division
19910 @subsection Signed Integer Division and Integer Overflow
19911 @cindex division, integer
19914 integer division is not always harmless: for example, on CPUs of the
19915 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
19916 which by default terminates the program. Worse, taking the remainder
19917 of these two values typically yields the same signal on these CPUs,
19918 even though the C standard requires @code{INT_MIN % -1} to yield zero
19919 because the expression does not overflow.
19921 @node Preprocessor Arithmetic
19922 @section Preprocessor Arithmetic
19923 @cindex preprocessor arithmetic
19925 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
19926 be evaluated as if all signed values are of type @code{intmax_t} and all
19927 unsigned values of type @code{uintmax_t}. Many compilers are buggy in
19928 this area, though. For example, as of 2007, Sun C mishandles @code{#if
19929 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
19930 @code{long long int}. Also, some older preprocessors mishandle
19931 constants ending in @code{LL}. To work around these problems, you can
19932 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
19933 @code{configure}-time rather than at @code{#if}-time.
19935 @node Null Pointers
19936 @section Properties of Null Pointers
19937 @cindex null pointers
19939 Most modern hosts reliably fail when you attempt to dereference a null
19942 On almost all modern hosts, null pointers use an all-bits-zero internal
19943 representation, so you can reliably use @code{memset} with 0 to set all
19944 the pointers in an array to null values.
19946 If @code{p} is a null pointer to an object type, the C expression
19947 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
19948 the standard says that it has undefined behavior.
19950 @node Buffer Overruns
19951 @section Buffer Overruns and Subscript Errors
19952 @cindex buffer overruns
19954 Buffer overruns and subscript errors are the most common dangerous
19955 errors in C programs. They result in undefined behavior because storing
19956 outside an array typically modifies storage that is used by some other
19957 object, and most modern systems lack runtime checks to catch these
19958 errors. Programs should not rely on buffer overruns being caught.
19960 There is one exception to the usual rule that a portable program cannot
19961 address outside an array. In C, it is valid to compute the address just
19962 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
19963 so long as you do not dereference the resulting pointer. But it is not
19964 valid to compute the address just before an object, e.g., @code{&a[-1]};
19965 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}. On
19966 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
19967 reliable in general, and it is usually easy enough to avoid the
19968 potential portability problem, e.g., by allocating an extra unused array
19969 element at the start or end.
19971 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
19973 users might also consider using the @option{-fmudflap} option to catch
19976 Buffer overruns are usually caused by off-by-one errors, but there are
19977 more subtle ways to get them.
19979 Using @code{int} values to index into an array or compute array sizes
19980 causes problems on typical 64-bit hosts where an array index might
19981 be @math{2^31} or larger. Index values of type @code{size_t} avoid this
19982 problem, but cannot be negative. Index values of type @code{ptrdiff_t}
19983 are signed, and are wide enough in practice.
19985 If you add or multiply two numbers to calculate an array size, e.g.,
19986 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
19987 multiplication overflows.
19989 Many implementations of the @code{alloca} function silently misbehave
19990 and can generate buffer overflows if given sizes that are too large.
19991 The size limits are implementation dependent, but are at least 4000
19992 bytes on all platforms that we know about.
19994 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
19995 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
19996 portable code should not use them unless the inputs are known to be
19997 within certain limits. The time-related functions can overflow their
19998 buffers if given timestamps out of range (e.g., a year less than -999
19999 or greater than 9999). Time-related buffer overflows cannot happen with
20000 recent-enough versions of the GNU C library, but are possible
20002 implementations. The @code{gets} function is the worst, since it almost
20003 invariably overflows its buffer when presented with an input line larger
20006 @node Volatile Objects
20007 @section Volatile Objects
20008 @cindex volatile objects
20010 The keyword @code{volatile} is often misunderstood in portable code.
20011 Its use inhibits some memory-access optimizations, but programmers often
20012 wish that it had a different meaning than it actually does.
20014 @code{volatile} was designed for code that accesses special objects like
20015 memory-mapped device registers whose contents spontaneously change.
20016 Such code is inherently low-level, and it is difficult to specify
20017 portably what @code{volatile} means in these cases. The C standard
20018 says, ``What constitutes an access to an object that has
20019 volatile-qualified type is implementation-defined,'' so in theory each
20020 implementation is supposed to fill in the gap by documenting what
20021 @code{volatile} means for that implementation. In practice, though,
20022 this documentation is usually absent or incomplete.
20024 One area of confusion is the distinction between objects defined with
20025 volatile types, and volatile lvalues. From the C standard's point of
20026 view, an object defined with a volatile type has externally visible
20027 behavior. You can think of such objects as having little oscilloscope
20028 probes attached to them, so that the user can observe some properties of
20029 accesses to them, just as the user can observe data written to output
20030 files. However, the standard does not make it clear whether users can
20031 observe accesses by volatile lvalues to ordinary objects. For example:
20034 /* Declare and access a volatile object.
20035 Accesses to X are "visible" to users. */
20036 static int volatile x;
20039 /* Access two ordinary objects via a volatile lvalue.
20040 It's not clear whether accesses to *P are "visible". */
20042 int *z = malloc (sizeof (int));
20050 Programmers often wish that @code{volatile} meant ``Perform the memory
20051 access here and now, without merging several memory accesses, without
20052 changing the memory word size, and without reordering.'' But the C
20053 standard does not require this. For objects defined with a volatile
20054 type, accesses must be done before the next sequence point; but
20055 otherwise merging, reordering, and word-size change is allowed. Worse,
20056 it is not clear from the standard whether volatile lvalues provide more
20057 guarantees in general than nonvolatile lvalues, if the underlying
20058 objects are ordinary.
20060 Even when accessing objects defined with a volatile type,
20061 the C standard allows only
20062 extremely limited signal handlers: the behavior is undefined if a signal
20063 handler reads any nonlocal object, or writes to any nonlocal object
20064 whose type is not @code{sig_atomic_t volatile}, or calls any standard
20065 library function other than @code{abort}, @code{signal}, and (if C99)
20066 @code{_Exit}. Hence C compilers need not worry about a signal handler
20067 disturbing ordinary computation, unless the computation accesses a
20068 @code{sig_atomic_t volatile} lvalue that is not a local variable.
20069 (There is an obscure exception for accesses via a pointer to a volatile
20070 character, since it may point into part of a @code{sig_atomic_t
20071 volatile} object.) Posix
20072 adds to the list of library functions callable from a portable signal
20073 handler, but otherwise is like the C standard in this area.
20075 Some C implementations allow memory-access optimizations within each
20076 translation unit, such that actual behavior agrees with the behavior
20077 required by the standard only when calling a function in some other
20078 translation unit, and a signal handler acts like it was called from a
20079 different translation unit. The C standard hints that in these
20080 implementations, objects referred to by signal handlers ``would require
20081 explicit specification of @code{volatile} storage, as well as other
20082 implementation-defined restrictions.'' But unfortunately even for this
20083 special case these other restrictions are often not documented well.
20084 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
20085 GNU Compiler Collection (GCC)}, for some
20086 restrictions imposed by GCC. @xref{Defining Handlers, ,
20087 Defining Signal Handlers, libc, The GNU C Library}, for some
20088 restrictions imposed by the GNU C library. Restrictions
20089 differ on other platforms.
20091 If possible, it is best to use a signal handler that fits within the
20092 limits imposed by the C and Posix standards.
20094 If this is not practical, you can try the following rules of thumb. A
20095 signal handler should access only volatile lvalues, preferably lvalues
20096 that refer to objects defined with a volatile type, and should not
20097 assume that the accessed objects have an internally consistent state
20098 if they are larger than a machine word. Furthermore, installers
20099 should employ compilers and compiler options that are commonly used
20100 for building operating system kernels, because kernels often need more
20101 from @code{volatile} than the C Standard requires, and installers who
20102 compile an application in a similar environment can sometimes benefit
20103 from the extra constraints imposed by kernels on compilers.
20104 Admittedly we are handwaving somewhat here, as there are few
20105 guarantees in this area; the rules of thumb may help to fix some bugs
20106 but there is a good chance that they will not fix them all.
20108 For @code{volatile}, C++ has the same problems that C does.
20109 Multithreaded applications have even more problems with @code{volatile},
20110 but they are beyond the scope of this section.
20112 The bottom line is that using @code{volatile} typically hurts
20113 performance but should not hurt correctness. In some cases its use
20114 does help correctness, but these cases are often so poorly understood
20115 that all too often adding @code{volatile} to a data structure merely
20116 alleviates some symptoms of a bug while not fixing the bug in general.
20118 @node Floating Point Portability
20119 @section Floating Point Portability
20120 @cindex floating point
20122 Almost all modern systems use IEEE-754 floating point, and it is safe to
20123 assume IEEE-754 in most portable code these days. For more information,
20124 please see David Goldberg's classic paper
20125 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
20126 Scientist Should Know About Floating-Point Arithmetic}.
20128 @node Exiting Portably
20129 @section Exiting Portably
20130 @cindex exiting portably
20132 A C or C++ program can exit with status @var{N} by returning
20133 @var{N} from the @code{main} function. Portable programs are supposed
20134 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
20135 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
20136 fail by exiting with status 1, and test programs that assume Posix can
20137 fail by exiting with status values from 1 through 255. Programs on
20138 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
20139 status when @code{main} returned nonzero, but ancient systems like these
20140 are no longer of practical concern.
20142 A program can also exit with status @var{N} by passing @var{N} to the
20143 @code{exit} function, and a program can fail by calling the @code{abort}
20144 function. If a program is specialized to just some platforms, it can fail
20145 by calling functions specific to those platforms, e.g., @code{_exit}
20146 (Posix) and @code{_Exit} (C99). However, like other functions, an exit
20147 function should be declared, typically by including a header. For
20148 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
20149 either directly or via the default includes (@pxref{Default Includes}).
20151 A program can fail due to undefined behavior such as dereferencing a null
20152 pointer, but this is not recommended as undefined behavior allows an
20153 implementation to do whatever it pleases and this includes exiting
20157 @c ================================================== Manual Configuration
20159 @node Manual Configuration
20160 @chapter Manual Configuration
20162 A few kinds of features can't be guessed automatically by running test
20163 programs. For example, the details of the object-file format, or
20164 special options that need to be passed to the compiler or linker. You
20165 can check for such features using ad-hoc means, such as having
20166 @command{configure} check the output of the @code{uname} program, or
20167 looking for libraries that are unique to particular systems. However,
20168 Autoconf provides a uniform method for handling unguessable features.
20171 * Specifying Target Triplets:: Specifying target triplets
20172 * Canonicalizing:: Getting the canonical system type
20173 * Using System Type:: What to do with the system type
20176 @node Specifying Target Triplets
20177 @section Specifying target triplets
20178 @cindex System type
20179 @cindex Target triplet
20180 @c This node used to be named Specifying Names. The @anchor allows old
20181 @c links to still work.
20182 @anchor{Specifying Names}
20185 @command{configure} scripts can make decisions based on a canonical name
20186 for the system type, or @dfn{target triplet}, which has the form:
20187 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
20188 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
20190 @command{configure} can usually guess the canonical name for the type of
20191 system it's running on. To do so it runs a script called
20192 @command{config.guess}, which infers the name using the @code{uname}
20193 command or symbols predefined by the C preprocessor.
20195 Alternately, the user can specify the system type with command line
20196 arguments to @command{configure} (@pxref{System Type}. Doing so is
20198 cross-compiling. In the most complex case of cross-compiling, three
20199 system types are involved. The options to specify them are:
20202 @item --build=@var{build-type}
20203 the type of system on which the package is being configured and
20204 compiled. It defaults to the result of running @command{config.guess}.
20206 @item --host=@var{host-type}
20207 the type of system on which the package runs. By default it is the
20208 same as the build machine. Specifying it enables the cross-compilation
20211 @item --target=@var{target-type}
20212 the type of system for which any compiler tools in the package
20213 produce code (rarely needed). By default, it is the same as host.
20216 If you mean to override the result of @command{config.guess}, use
20217 @option{--build}, not @option{--host}, since the latter enables
20218 cross-compilation. For historical reasons,
20219 whenever you specify @option{--host},
20220 be sure to specify @option{--build} too; this will be fixed in the
20221 future. So, to enter cross-compilation mode, use a command like this
20224 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20228 Note that if you do not specify @option{--host}, @command{configure}
20229 fails if it can't run the code generated by the specified compiler. For
20230 example, configuring as follows fails:
20233 ./configure CC=m68k-coff-gcc
20236 When cross-compiling, @command{configure} will warn about any tools
20237 (compilers, linkers, assemblers) whose name is not prefixed with the
20238 host type. This is an aid to users performing cross-compilation.
20239 Continuing the example above, if a cross-compiler named @command{cc} is
20240 used with a native @command{pkg-config}, then libraries found by
20241 @command{pkg-config} will likely cause subtle build failures; but using
20242 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
20243 avoids any confusion. Avoiding the warning is as simple as creating the
20244 correct symlinks naming the cross tools.
20246 @cindex @command{config.sub}
20247 @command{configure} recognizes short aliases for many system types; for
20248 example, @samp{decstation} can be used instead of
20249 @samp{mips-dec-ultrix4.2}. @command{configure} runs a script called
20250 @command{config.sub} to canonicalize system type aliases.
20252 This section deliberately omits the description of the obsolete
20253 interface; see @ref{Hosts and Cross-Compilation}.
20256 @node Canonicalizing
20257 @section Getting the Canonical System Type
20258 @cindex System type
20259 @cindex Canonical system type
20261 The following macros make the system type available to @command{configure}
20264 @ovindex build_alias
20265 @ovindex host_alias
20266 @ovindex target_alias
20268 The variables @samp{build_alias}, @samp{host_alias}, and
20269 @samp{target_alias} are always exactly the arguments of @option{--build},
20270 @option{--host}, and @option{--target}; in particular, they are left empty
20271 if the user did not use them, even if the corresponding
20272 @code{AC_CANONICAL} macro was run. Any configure script may use these
20273 variables anywhere. These are the variables that should be used when in
20274 interaction with the user.
20276 If you need to recognize some special environments based on their system
20277 type, run the following macros to get canonical system names. These
20278 variables are not set before the macro call.
20280 If you use these macros, you must distribute @command{config.guess} and
20281 @command{config.sub} along with your source code. @xref{Output}, for
20282 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
20283 to control in which directory @command{configure} looks for those scripts.
20286 @defmac AC_CANONICAL_BUILD
20287 @acindex{CANONICAL_BUILD}
20290 @ovindex build_vendor
20292 Compute the canonical build-system type variable, @code{build}, and its
20293 three individual parts @code{build_cpu}, @code{build_vendor}, and
20296 If @option{--build} was specified, then @code{build} is the
20297 canonicalization of @code{build_alias} by @command{config.sub},
20298 otherwise it is determined by the shell script @command{config.guess}.
20301 @defmac AC_CANONICAL_HOST
20302 @acindex{CANONICAL_HOST}
20305 @ovindex host_vendor
20307 Compute the canonical host-system type variable, @code{host}, and its
20308 three individual parts @code{host_cpu}, @code{host_vendor}, and
20311 If @option{--host} was specified, then @code{host} is the
20312 canonicalization of @code{host_alias} by @command{config.sub},
20313 otherwise it defaults to @code{build}.
20316 @defmac AC_CANONICAL_TARGET
20317 @acindex{CANONICAL_TARGET}
20319 @ovindex target_cpu
20320 @ovindex target_vendor
20322 Compute the canonical target-system type variable, @code{target}, and its
20323 three individual parts @code{target_cpu}, @code{target_vendor}, and
20326 If @option{--target} was specified, then @code{target} is the
20327 canonicalization of @code{target_alias} by @command{config.sub},
20328 otherwise it defaults to @code{host}.
20331 Note that there can be artifacts due to the backward compatibility
20332 code. See @xref{Hosts and Cross-Compilation}, for more.
20334 @node Using System Type
20335 @section Using the System Type
20337 In @file{configure.ac} the system type is generally used by one or more
20338 @code{case} statements to select system-specifics. Shell wildcards can
20339 be used to match a group of system types.
20341 For example, an extra assembler code object file could be chosen, giving
20342 access to a CPU cycle counter register. @code{$(CYCLE_OBJ)} in the
20343 following would be used in a makefile to add the object to a
20344 program or library.
20348 [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
20349 [i?86-*-*], [CYCLE_OBJ=rdtsc.o],
20352 AC_SUBST([CYCLE_OBJ])
20355 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
20356 to select variant source files, for example optimized code for some
20357 CPUs. The configured CPU type doesn't always indicate exact CPU types,
20358 so some runtime capability checks may be necessary too.
20362 alpha*-*-*) AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
20363 powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
20364 *-*-*) AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
20368 The host system type can also be used to find cross-compilation tools
20369 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
20371 The above examples all show @samp{$host}, since this is where the code
20372 is going to run. Only rarely is it necessary to test @samp{$build}
20373 (which is where the build is being done).
20375 Whenever you're tempted to use @samp{$host} it's worth considering
20376 whether some sort of probe would be better. New system types come along
20377 periodically or previously missing features are added. Well-written
20378 probes can adapt themselves to such things, but hard-coded lists of
20379 names can't. Here are some guidelines,
20383 Availability of libraries and library functions should always be checked
20386 Variant behavior of system calls is best identified with runtime tests
20387 if possible, but bug workarounds or obscure difficulties might have to
20388 be driven from @samp{$host}.
20390 Assembler code is inevitably highly CPU-specific and is best selected
20391 according to @samp{$host_cpu}.
20393 Assembler variations like underscore prefix on globals or ELF versus
20394 COFF type directives are however best determined by probing, perhaps
20395 even examining the compiler output.
20398 @samp{$target} is for use by a package creating a compiler or similar.
20399 For ordinary packages it's meaningless and should not be used. It
20400 indicates what the created compiler should generate code for, if it can
20401 cross-compile. @samp{$target} generally selects various hard-coded CPU
20402 and system conventions, since usually the compiler or tools under
20403 construction themselves determine how the target works.
20406 @c ===================================================== Site Configuration.
20408 @node Site Configuration
20409 @chapter Site Configuration
20411 @command{configure} scripts support several kinds of local configuration
20412 decisions. There are ways for users to specify where external software
20413 packages are, include or exclude optional features, install programs
20414 under modified names, and set default values for @command{configure}
20418 * Help Formatting:: Customizing @samp{configure --help}
20419 * External Software:: Working with other optional software
20420 * Package Options:: Selecting optional features
20421 * Pretty Help Strings:: Formatting help string
20422 * Option Checking:: Controlling checking of @command{configure} options
20423 * Site Details:: Configuring site details
20424 * Transforming Names:: Changing program names when installing
20425 * Site Defaults:: Giving @command{configure} local defaults
20428 @node Help Formatting
20429 @section Controlling Help Output
20431 Users consult @samp{configure --help} to learn of configuration
20432 decisions specific to your package. By default, @command{configure}
20433 breaks this output into sections for each type of option; within each
20434 section, help strings appear in the order @file{configure.ac} defines
20440 --enable-bar include bar
20447 @defmac AC_PRESERVE_HELP_ORDER
20448 @acindex{PRESERVE_HELP_ORDER}
20450 Request an alternate @option{--help} format, in which options of all
20451 types appear together, in the order defined. Call this macro before any
20452 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
20455 Optional Features and Packages:
20457 --enable-bar include bar
20463 @node External Software
20464 @section Working With External Software
20465 @cindex External software
20467 Some packages require, or can optionally use, other software packages
20468 that are already installed. The user can give @command{configure}
20469 command line options to specify which such external software to use.
20470 The options have one of these forms:
20472 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
20475 --with-@var{package}[=@var{arg}]
20476 --without-@var{package}
20479 For example, @option{--with-gnu-ld} means work with the GNU linker
20480 instead of some other linker. @option{--with-x} means work with The X
20483 The user can give an argument by following the package name with
20484 @samp{=} and the argument. Giving an argument of @samp{no} is for
20485 packages that are used by default; it says to @emph{not} use the
20486 package. An argument that is neither @samp{yes} nor @samp{no} could
20487 include a name or number of a version of the other package, to specify
20488 more precisely which other package this program is supposed to work
20489 with. If no argument is given, it defaults to @samp{yes}.
20490 @option{--without-@var{package}} is equivalent to
20491 @option{--with-@var{package}=no}.
20493 Normally @command{configure} scripts complain about
20494 @option{--with-@var{package}} options that they do not support.
20495 @xref{Option Checking}, for details, and for how to override the
20498 For each external software package that may be used, @file{configure.ac}
20499 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
20500 user asked to use it. Whether each package is used or not by default,
20501 and which arguments are valid, is up to you.
20503 @anchor{AC_ARG_WITH}
20504 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
20505 @ovar{action-if-given}, @ovar{action-if-not-given})
20507 If the user gave @command{configure} the option @option{--with-@var{package}}
20508 or @option{--without-@var{package}}, run shell commands
20509 @var{action-if-given}. If neither option was given, run shell commands
20510 @var{action-if-not-given}. The name @var{package} indicates another
20511 software package that this program should work with. It should consist
20512 only of alphanumeric characters, dashes, and dots.
20514 The option's argument is available to the shell commands
20515 @var{action-if-given} in the shell variable @code{withval}, which is
20516 actually just the value of the shell variable named
20517 @code{with_@var{package}}, with any non-alphanumeric characters in
20518 @var{package} changed into @samp{_}. You may use that variable instead,
20521 The argument @var{help-string} is a description of the option that
20524 --with-readline support fancy command line editing
20528 @var{help-string} may be more than one line long, if more detail is
20529 needed. Just make sure the columns line up in @samp{configure
20530 --help}. Avoid tabs in the help string. The easiest way to provide the
20531 proper leading whitespace is to format your @var{help-string} with the macro
20532 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
20534 The following example shows how to use the @code{AC_ARG_WITH} macro in
20535 a common situation. You want to let the user decide whether to enable
20536 support for an external library (e.g., the readline library); if the user
20537 specified neither @option{--with-readline} nor @option{--without-readline},
20538 you want to enable support for readline only if the library is available
20541 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20543 AC_ARG_WITH([readline],
20544 [AS_HELP_STRING([--with-readline],
20545 [support fancy command line editing @@<:@@default=check@@:>@@])],
20547 [with_readline=check])
20550 AS_IF([test "x$with_readline" != xno],
20551 [AC_CHECK_LIB([readline], [main],
20552 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20553 AC_DEFINE([HAVE_LIBREADLINE], [1],
20554 [Define if you have libreadline])
20556 [if test "x$with_readline" != xcheck; then
20558 [--with-readline was given, but test for readline failed])
20563 The next example shows how to use @code{AC_ARG_WITH} to give the user the
20564 possibility to enable support for the readline library, in case it is still
20565 experimental and not well tested, and is therefore disabled by default.
20567 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20569 AC_ARG_WITH([readline],
20570 [AS_HELP_STRING([--with-readline],
20571 [enable experimental support for readline])],
20573 [with_readline=no])
20576 AS_IF([test "x$with_readline" != xno],
20577 [AC_CHECK_LIB([readline], [main],
20578 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20579 AC_DEFINE([HAVE_LIBREADLINE], [1],
20580 [Define if you have libreadline])
20583 [--with-readline was given, but test for readline failed])],
20587 The last example shows how to use @code{AC_ARG_WITH} to give the user the
20588 possibility to disable support for the readline library, given that it is
20589 an important feature and that it should be enabled by default.
20591 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20593 AC_ARG_WITH([readline],
20594 [AS_HELP_STRING([--without-readline],
20595 [disable support for readline])],
20597 [with_readline=yes])
20600 AS_IF([test "x$with_readline" != xno],
20601 [AC_CHECK_LIB([readline], [main],
20602 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20603 AC_DEFINE([HAVE_LIBREADLINE], [1],
20604 [Define if you have libreadline])
20607 [readline test failed (--without-readline to disable)])],
20611 These three examples can be easily adapted to the case where
20612 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
20613 @ref{Package Options}).
20616 @node Package Options
20617 @section Choosing Package Options
20618 @cindex Package options
20619 @cindex Options, package
20621 If a software package has optional compile-time features, the user can
20622 give @command{configure} command line options to specify whether to
20623 compile them. The options have one of these forms:
20625 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
20628 --enable-@var{feature}[=@var{arg}]
20629 --disable-@var{feature}
20632 These options allow users to choose which optional features to build and
20633 install. @option{--enable-@var{feature}} options should never make a
20634 feature behave differently or cause one feature to replace another.
20635 They should only cause parts of the program to be built rather than left
20638 The user can give an argument by following the feature name with
20639 @samp{=} and the argument. Giving an argument of @samp{no} requests
20640 that the feature @emph{not} be made available. A feature with an
20641 argument looks like @option{--enable-debug=stabs}. If no argument is
20642 given, it defaults to @samp{yes}. @option{--disable-@var{feature}} is
20643 equivalent to @option{--enable-@var{feature}=no}.
20645 Normally @command{configure} scripts complain about
20646 @option{--enable-@var{package}} options that they do not support.
20647 @xref{Option Checking}, for details, and for how to override the
20650 For each optional feature, @file{configure.ac} should call
20651 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
20652 to include it. Whether each feature is included or not by default, and
20653 which arguments are valid, is up to you.
20655 @anchor{AC_ARG_ENABLE}
20656 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
20657 @ovar{action-if-given}, @ovar{action-if-not-given})
20658 @acindex{ARG_ENABLE}
20659 If the user gave @command{configure} the option
20660 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
20661 shell commands @var{action-if-given}. If neither option was given, run
20662 shell commands @var{action-if-not-given}. The name @var{feature}
20663 indicates an optional user-level facility. It should consist only of
20664 alphanumeric characters, dashes, and dots.
20666 The option's argument is available to the shell commands
20667 @var{action-if-given} in the shell variable @code{enableval}, which is
20668 actually just the value of the shell variable named
20669 @code{enable_@var{feature}}, with any non-alphanumeric characters in
20670 @var{feature} changed into @samp{_}. You may use that variable instead,
20671 if you wish. The @var{help-string} argument is like that of
20672 @code{AC_ARG_WITH} (@pxref{External Software}).
20674 You should format your @var{help-string} with the macro
20675 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
20677 See the examples suggested with the definition of @code{AC_ARG_WITH}
20678 (@pxref{External Software}) to get an idea of possible applications of
20679 @code{AC_ARG_ENABLE}.
20682 @node Pretty Help Strings
20683 @section Making Your Help Strings Look Pretty
20684 @cindex Help strings
20686 Properly formatting the @samp{help strings} which are used in
20687 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
20688 (@pxref{Package Options}) can be challenging. Specifically, you want
20689 your own @samp{help strings} to line up in the appropriate columns of
20690 @samp{configure --help} just like the standard Autoconf @samp{help
20691 strings} do. This is the purpose of the @code{AS_HELP_STRING} macro.
20693 @anchor{AS_HELP_STRING}
20694 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
20695 @dvar{indent-column, 26}, @dvar{wrap-column, 79})
20696 @asindex{HELP_STRING}
20698 Expands into a help string that looks pretty when the user executes
20699 @samp{configure --help}. It is typically used in @code{AC_ARG_WITH}
20700 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
20701 Options}). The following example makes this clearer.
20705 [AS_HELP_STRING([--with-foo],
20706 [use foo (default is no)])],
20707 [use_foo=$withval],
20711 Then the last few lines of @samp{configure --help} appear like
20715 --enable and --with options recognized:
20716 --with-foo use foo (default is no)
20719 Macro expansion is performed on the first argument. However, the second
20720 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
20721 list of text to be reformatted, and is not subject to macro expansion.
20722 Since it is not expanded, it should not be double quoted.
20723 @xref{Autoconf Language}, for a more detailed explanation.
20725 The @code{AS_HELP_STRING} macro is particularly helpful when the
20726 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
20727 arguments, as shown in the following example. Be aware that
20728 @var{left-hand-side} may not expand to unbalanced quotes,
20729 although quadrigraphs can be used.
20732 AC_DEFUN([MY_ARG_WITH],
20733 [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
20734 [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
20735 [use $1 (default is $2)])],
20736 [use_[]$1=$withval],
20738 MY_ARG_WITH([a_b], [no])
20741 Here, the last few lines of @samp{configure --help} will include:
20744 --enable and --with options recognized:
20745 --with-a-b use a_b (default is no)
20748 The parameters @var{indent-column} and @var{wrap-column} were introduced
20749 in Autoconf 2.62. Generally, they should not be specified; they exist
20750 for fine-tuning of the wrapping.
20752 AS_HELP_STRING([--option], [description of option])
20753 @result{} --option description of option
20754 AS_HELP_STRING([--option], [description of option], [15], [30])
20755 @result{} --option description of
20761 @node Option Checking
20762 @section Controlling Checking of @command{configure} Options
20763 @cindex Options, Package
20765 The @command{configure} script checks its command-line options against a
20766 list of known options, like @option{--help} or @option{--config-cache}.
20767 An unknown option ordinarily indicates a mistake by the user and
20768 @command{configure} halts with an error. However, by default unknown
20769 @option{--with-@var{package}} and @option{--enable-@var{feature}}
20770 options elicit only a warning, to support configuring entire source
20773 Source trees often contain multiple packages with a top-level
20774 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
20775 (@pxref{Subdirectories}). Because the packages generally support
20776 different @option{--with-@var{package}} and
20777 @option{--enable-@var{feature}} options, the GNU Coding
20778 Standards say they must accept unrecognized options without halting.
20779 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
20780 automatically disables the warnings.
20782 This default behavior may be modified in two ways. First, the installer
20783 can invoke @code{configure --disable-option-checking} to disable
20784 these warnings, or invoke @code{configure --enable-option-checking=fatal}
20785 options to turn them into fatal errors, respectively. Second, the
20786 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
20788 @defmac AC_DISABLE_OPTION_CHECKING
20789 @acindex{DISABLE_OPTION_CHECKING}
20791 By default, disable warnings related to any unrecognized
20792 @option{--with-@var{package}} or @option{--enable-@var{feature}}
20793 options. This is implied by @code{AC_CONFIG_SUBDIRS}.
20795 The installer can override this behavior by passing
20796 @option{--enable-option-checking} (enable warnings) or
20797 @option{--enable-option-checking=fatal} (enable errors) to
20798 @command{configure}.
20803 @section Configuring Site Details
20804 @cindex Site details
20806 Some software packages require complex site-specific information. Some
20807 examples are host names to use for certain services, company names, and
20808 email addresses to contact. Since some configuration scripts generated
20809 by Metaconfig ask for such information interactively, people sometimes
20810 wonder how to get that information in Autoconf-generated configuration
20811 scripts, which aren't interactive.
20813 Such site configuration information should be put in a file that is
20814 edited @emph{only by users}, not by programs. The location of the file
20815 can either be based on the @code{prefix} variable, or be a standard
20816 location such as the user's home directory. It could even be specified
20817 by an environment variable. The programs should examine that file at
20818 runtime, rather than at compile time. Runtime configuration is more
20819 convenient for users and makes the configuration process simpler than
20820 getting the information while configuring. @xref{Directory Variables, ,
20821 Variables for Installation Directories, standards, GNU Coding
20822 Standards}, for more information on where to put data files.
20824 @node Transforming Names
20825 @section Transforming Program Names When Installing
20826 @cindex Transforming program names
20827 @cindex Program names, transforming
20829 Autoconf supports changing the names of programs when installing them.
20830 In order to use these transformations, @file{configure.ac} must call the
20831 macro @code{AC_ARG_PROGRAM}.
20833 @defmac AC_ARG_PROGRAM
20834 @acindex{ARG_PROGRAM}
20835 @ovindex program_transform_name
20836 Place in output variable @code{program_transform_name} a sequence of
20837 @code{sed} commands for changing the names of installed programs.
20839 If any of the options described below are given to @command{configure},
20840 program names are transformed accordingly. Otherwise, if
20841 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
20842 is given, the target type followed by a dash is used as a prefix.
20843 Otherwise, no program name transformation is done.
20847 * Transformation Options:: @command{configure} options to transform names
20848 * Transformation Examples:: Sample uses of transforming names
20849 * Transformation Rules:: Makefile uses of transforming names
20852 @node Transformation Options
20853 @subsection Transformation Options
20855 You can specify name transformations by giving @command{configure} these
20856 command line options:
20859 @item --program-prefix=@var{prefix}
20860 prepend @var{prefix} to the names;
20862 @item --program-suffix=@var{suffix}
20863 append @var{suffix} to the names;
20865 @item --program-transform-name=@var{expression}
20866 perform @code{sed} substitution @var{expression} on the names.
20869 @node Transformation Examples
20870 @subsection Transformation Examples
20872 These transformations are useful with programs that can be part of a
20873 cross-compilation development environment. For example, a
20874 cross-assembler running on a Sun 4 configured with
20875 @option{--target=i960-vxworks} is normally installed as
20876 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
20877 with a native Sun 4 assembler.
20879 You can force a program name to begin with @file{g}, if you don't want
20880 GNU programs installed on your system to shadow other programs with
20881 the same name. For example, if you configure GNU @code{diff} with
20882 @option{--program-prefix=g}, then when you run @samp{make install} it is
20883 installed as @file{/usr/local/bin/gdiff}.
20885 As a more sophisticated example, you could use
20888 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
20892 to prepend @samp{g} to most of the program names in a source tree,
20893 excepting those like @code{gdb} that already have one and those like
20894 @code{less} and @code{lesskey} that aren't GNU programs. (That is
20895 assuming that you have a source tree containing those programs that is
20896 set up to use this feature.)
20898 One way to install multiple versions of some programs simultaneously is
20899 to append a version number to the name of one or both. For example, if
20900 you want to keep Autoconf version 1 around for awhile, you can configure
20901 Autoconf version 2 using @option{--program-suffix=2} to install the
20902 programs as @file{/usr/local/bin/autoconf2},
20903 @file{/usr/local/bin/autoheader2}, etc. Nevertheless, pay attention
20904 that only the binaries are renamed, therefore you'd have problems with
20905 the library files which might overlap.
20907 @node Transformation Rules
20908 @subsection Transformation Rules
20910 Here is how to use the variable @code{program_transform_name} in a
20911 @file{Makefile.in}:
20914 PROGRAMS = cp ls rm
20915 transform = @@program_transform_name@@
20917 for p in $(PROGRAMS); do \
20918 $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
20919 sed '$(transform)'`; \
20923 for p in $(PROGRAMS); do \
20924 rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
20928 It is guaranteed that @code{program_transform_name} is never empty, and
20929 that there are no useless separators. Therefore you may safely embed
20930 @code{program_transform_name} within a sed program using @samp{;}:
20933 transform = @@program_transform_name@@
20934 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
20937 Whether to do the transformations on documentation files (Texinfo or
20938 @code{man}) is a tricky question; there seems to be no perfect answer,
20939 due to the several reasons for name transforming. Documentation is not
20940 usually particular to a specific architecture, and Texinfo files do not
20941 conflict with system documentation. But they might conflict with
20942 earlier versions of the same files, and @code{man} pages sometimes do
20943 conflict with system documentation. As a compromise, it is probably
20944 best to do name transformations on @code{man} pages but not on Texinfo
20947 @node Site Defaults
20948 @section Setting Site Defaults
20949 @cindex Site defaults
20950 @cindex config.site
20952 Autoconf-generated @command{configure} scripts allow your site to provide
20953 default values for some configuration values. You do this by creating
20954 site- and system-wide initialization files.
20956 @evindex CONFIG_SITE
20957 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
20958 uses its value as the name of a shell script to read. Otherwise, it
20959 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
20960 then @file{@var{prefix}/etc/config.site} if it exists. Thus,
20961 settings in machine-specific files override those in machine-independent
20962 ones in case of conflict.
20964 Site files can be arbitrary shell scripts, but only certain kinds of
20965 code are really appropriate to be in them. Because @command{configure}
20966 reads any cache file after it has read any site files, a site file can
20967 define a default cache file to be shared between all Autoconf-generated
20968 @command{configure} scripts run on that system (@pxref{Cache Files}). If
20969 you set a default cache file in a site file, it is a good idea to also
20970 set the output variable @code{CC} in that site file, because the cache
20971 file is only valid for a particular compiler, but many systems have
20974 You can examine or override the value set by a command line option to
20975 @command{configure} in a site file; options set shell variables that have
20976 the same names as the options, with any dashes turned into underscores.
20977 The exceptions are that @option{--without-} and @option{--disable-} options
20978 are like giving the corresponding @option{--with-} or @option{--enable-}
20979 option and the value @samp{no}. Thus, @option{--cache-file=localcache}
20980 sets the variable @code{cache_file} to the value @samp{localcache};
20981 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
20982 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
20983 variable @code{prefix} to the value @samp{/usr}; etc.
20985 Site files are also good places to set default values for other output
20986 variables, such as @code{CFLAGS}, if you need to give them non-default
20987 values: anything you would normally do, repetitively, on the command
20988 line. If you use non-default values for @var{prefix} or
20989 @var{exec_prefix} (wherever you locate the site file), you can set them
20990 in the site file if you specify it with the @code{CONFIG_SITE}
20991 environment variable.
20993 You can set some cache values in the site file itself. Doing this is
20994 useful if you are cross-compiling, where it is impossible to check features
20995 that require running a test program. You could ``prime the cache'' by
20996 setting those values correctly for that system in
20997 @file{@var{prefix}/etc/config.site}. To find out the names of the cache
20998 variables you need to set, see the documentation of the respective
20999 Autoconf macro. If the variables or their semantics are undocumented,
21000 you may need to look for shell variables with @samp{_cv_} in their names
21001 in the affected @command{configure} scripts, or in the Autoconf M4
21002 source code for those macros; but in that case, their name or semantics
21003 may change in a future Autoconf version.
21005 The cache file is careful to not override any variables set in the site
21006 files. Similarly, you should not override command-line options in the
21007 site files. Your code should check that variables such as @code{prefix}
21008 and @code{cache_file} have their default values (as set near the top of
21009 @command{configure}) before changing them.
21011 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}. The
21012 command @samp{configure --prefix=/usr/share/local/gnu} would read this
21013 file (if @code{CONFIG_SITE} is not set to a different file).
21016 # /usr/share/local/gnu/share/config.site for configure
21018 # Change some defaults.
21019 test "$prefix" = NONE && prefix=/usr/share/local/gnu
21020 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
21021 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21022 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21024 # Give Autoconf 2.x generated configure scripts a shared default
21025 # cache file for feature test results, architecture-specific.
21026 if test "$cache_file" = /dev/null; then
21027 cache_file="$prefix/var/config.cache"
21028 # A cache file is only valid for one C compiler.
21033 @cindex Filesystem Hierarchy Standard
21036 Another use of @file{config.site} is for priming the directory variables
21037 in a manner consistent with the Filesystem Hierarchy Standard
21038 (FHS). Once the following file is installed at
21039 @file{/usr/share/config.site}, a user can execute simply
21040 @code{./configure --prefix=/usr} to get all the directories chosen in
21041 the locations recommended by FHS.
21044 # /usr/share/config.site for FHS defaults when installing below /usr,
21045 # and the respective settings were not changed on the command line.
21046 if test "$prefix" = /usr; then
21047 test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
21048 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21049 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21054 @cindex 64-bit libraries
21055 Likewise, on platforms where 64-bit libraries are built by default, then
21056 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
21057 it is appropriate to install @file{/usr/local/@/share/config.site}:
21060 # /usr/local/share/config.site for platforms that prefer
21061 # the directory /usr/local/lib64 over /usr/local/lib.
21062 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
21066 @c ============================================== Running configure Scripts.
21068 @node Running configure Scripts
21069 @chapter Running @command{configure} Scripts
21070 @cindex @command{configure}
21072 Below are instructions on how to configure a package that uses a
21073 @command{configure} script, suitable for inclusion as an @file{INSTALL}
21074 file in the package. A plain-text version of @file{INSTALL} which you
21075 may use comes with Autoconf.
21078 * Basic Installation:: Instructions for typical cases
21079 * Compilers and Options:: Selecting compilers and optimization
21080 * Multiple Architectures:: Compiling for multiple architectures at once
21081 * Installation Names:: Installing in different directories
21082 * Optional Features:: Selecting optional features
21083 * Particular Systems:: Particular systems
21084 * System Type:: Specifying the system type
21085 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
21086 * Defining Variables:: Specifying the compiler etc.
21087 * configure Invocation:: Changing how @command{configure} runs
21091 @include install.texi
21094 @c ============================================== config.status Invocation
21096 @node config.status Invocation
21097 @chapter config.status Invocation
21098 @cindex @command{config.status}
21100 The @command{configure} script creates a file named @file{config.status},
21101 which actually configures, @dfn{instantiates}, the template files. It
21102 also records the configuration options that were specified when the
21103 package was last configured in case reconfiguring is needed.
21107 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
21110 It configures each @var{tag}; if none are specified, all the templates
21111 are instantiated. A @var{tag} refers to a file or other tag associated
21112 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
21113 macro (@pxref{Configuration Actions}). The files must be specified
21114 without their dependencies, as in
21117 ./config.status foobar
21124 ./config.status foobar:foo.in:bar.in
21127 The supported options are:
21132 Print a summary of the command line options, the list of the template
21137 Print the version number of Autoconf and the configuration settings,
21141 Print the configuration settings in reusable way, quoted for the shell,
21142 and exit. For example, for a debugging build that otherwise reuses the
21143 configuration from a different build directory @var{build-dir} of a
21144 package in @var{src-dir}, you could use the following:
21147 args=`@var{build-dir}/config.status --config`
21148 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
21152 Note that it may be necessary to override a @option{--srcdir} setting
21153 that was saved in the configuration, if the arguments are used in a
21154 different build directory.
21159 Do not print progress messages.
21163 Don't remove the temporary files.
21165 @item --file=@var{file}[:@var{template}]
21166 Require that @var{file} be instantiated as if
21167 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used. Both
21168 @var{file} and @var{template} may be @samp{-} in which case the standard
21169 output and/or standard input, respectively, is used. If a
21170 @var{template} file name is relative, it is first looked for in the build
21171 tree, and then in the source tree. @xref{Configuration Actions}, for
21174 This option and the following ones provide one way for separately
21175 distributed packages to share the values computed by @command{configure}.
21176 Doing so can be useful if some of the packages need a superset of the
21177 features that one of them, perhaps a common library, does. These
21178 options allow a @file{config.status} file to create files other than the
21179 ones that its @file{configure.ac} specifies, so it can be used for a
21180 different package, or for extracting a subset of values. For example,
21183 echo '@@CC@@' | ./config.status --file=-
21187 provides the value of @code{@@CC@@} on standard output.
21189 @item --header=@var{file}[:@var{template}]
21190 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
21193 Ask @file{config.status} to update itself and exit (no instantiation).
21194 This option is useful if you change @command{configure}, so that the
21195 results of some tests might be different from the previous run. The
21196 @option{--recheck} option reruns @command{configure} with the same arguments
21197 you used before, plus the @option{--no-create} option, which prevents
21198 @command{configure} from running @file{config.status} and creating
21199 @file{Makefile} and other files, and the @option{--no-recursion} option,
21200 which prevents @command{configure} from running other @command{configure}
21201 scripts in subdirectories. (This is so other Make rules can
21202 run @file{config.status} when it changes; @pxref{Automatic Remaking},
21206 @file{config.status} checks several optional environment variables that
21207 can alter its behavior:
21209 @anchor{CONFIG_SHELL}
21210 @defvar CONFIG_SHELL
21211 @evindex CONFIG_SHELL
21212 The shell with which to run @command{configure} for the @option{--recheck}
21213 option. It must be Bourne-compatible. The default is a shell that
21214 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
21215 Invoking @command{configure} by hand bypasses this setting, so you may
21216 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
21217 to insure that the same shell is used everywhere. The absolute name of the
21218 shell should be passed.
21221 @defvar CONFIG_STATUS
21222 @evindex CONFIG_STATUS
21223 The file name to use for the shell script that records the
21224 configuration. The default is @file{./config.status}. This variable is
21225 useful when one package uses parts of another and the @command{configure}
21226 scripts shouldn't be merged because they are maintained separately.
21229 You can use @file{./config.status} in your makefiles. For example, in
21230 the dependencies given above (@pxref{Automatic Remaking}),
21231 @file{config.status} is run twice when @file{configure.ac} has changed.
21232 If that bothers you, you can make each run only regenerate the files for
21237 stamp-h: config.h.in config.status
21238 ./config.status config.h
21241 Makefile: Makefile.in config.status
21242 ./config.status Makefile
21246 The calling convention of @file{config.status} has changed; see
21247 @ref{Obsolete config.status Use}, for details.
21250 @c =================================================== Obsolete Constructs
21252 @node Obsolete Constructs
21253 @chapter Obsolete Constructs
21254 @cindex Obsolete constructs
21256 Autoconf changes, and throughout the years some constructs have been
21257 obsoleted. Most of the changes involve the macros, but in some cases
21258 the tools themselves, or even some concepts, are now considered
21261 You may completely skip this chapter if you are new to Autoconf. Its
21262 intention is mainly to help maintainers updating their packages by
21263 understanding how to move to more modern constructs.
21266 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
21267 * acconfig Header:: Additional entries in @file{config.h.in}
21268 * autoupdate Invocation:: Automatic update of @file{configure.ac}
21269 * Obsolete Macros:: Backward compatibility macros
21270 * Autoconf 1:: Tips for upgrading your files
21271 * Autoconf 2.13:: Some fresher tips
21274 @node Obsolete config.status Use
21275 @section Obsolete @file{config.status} Invocation
21277 @file{config.status} now supports arguments to specify the files to
21278 instantiate; see @ref{config.status Invocation}, for more details.
21279 Before, environment variables had to be used.
21281 @defvar CONFIG_COMMANDS
21282 @evindex CONFIG_COMMANDS
21283 The tags of the commands to execute. The default is the arguments given
21284 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
21285 @file{configure.ac}.
21288 @defvar CONFIG_FILES
21289 @evindex CONFIG_FILES
21290 The files in which to perform @samp{@@@var{variable}@@} substitutions.
21291 The default is the arguments given to @code{AC_OUTPUT} and
21292 @code{AC_CONFIG_FILES} in @file{configure.ac}.
21295 @defvar CONFIG_HEADERS
21296 @evindex CONFIG_HEADERS
21297 The files in which to substitute C @code{#define} statements. The
21298 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
21299 macro was not called, @file{config.status} ignores this variable.
21302 @defvar CONFIG_LINKS
21303 @evindex CONFIG_LINKS
21304 The symbolic links to establish. The default is the arguments given to
21305 @code{AC_CONFIG_LINKS}; if that macro was not called,
21306 @file{config.status} ignores this variable.
21309 In @ref{config.status Invocation}, using this old interface, the example
21315 stamp-h: config.h.in config.status
21316 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
21317 CONFIG_HEADERS=config.h ./config.status
21320 Makefile: Makefile.in config.status
21321 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
21322 CONFIG_FILES=Makefile ./config.status
21327 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
21328 no need to set @code{CONFIG_HEADERS} in the @command{make} rules. Equally
21329 for @code{CONFIG_COMMANDS}, etc.)
21332 @node acconfig Header
21333 @section @file{acconfig.h}
21335 @cindex @file{acconfig.h}
21336 @cindex @file{config.h.top}
21337 @cindex @file{config.h.bot}
21339 In order to produce @file{config.h.in}, @command{autoheader} needs to
21340 build or to find templates for each symbol. Modern releases of Autoconf
21341 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
21342 Macros}), but in older releases a file, @file{acconfig.h}, contained the
21343 list of needed templates. @command{autoheader} copied comments and
21344 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
21345 the current directory, if present. This file used to be mandatory if
21346 you @code{AC_DEFINE} any additional symbols.
21348 Modern releases of Autoconf also provide @code{AH_TOP} and
21349 @code{AH_BOTTOM} if you need to prepend/append some information to
21350 @file{config.h.in}. Ancient versions of Autoconf had a similar feature:
21351 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
21352 @command{autoheader} copies the lines before the line containing
21353 @samp{@@TOP@@} into the top of the file that it generates. Similarly,
21354 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
21355 @command{autoheader} copies the lines after that line to the end of the
21356 file it generates. Either or both of those strings may be omitted. An
21357 even older alternate way to produce the same effect in ancient versions
21358 of Autoconf is to create the files @file{@var{file}.top} (typically
21359 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
21360 directory. If they exist, @command{autoheader} copies them to the
21361 beginning and end, respectively, of its output.
21363 In former versions of Autoconf, the files used in preparing a software
21364 package for distribution were:
21367 configure.ac --. .------> autoconf* -----> configure
21369 [aclocal.m4] --+ `---.
21371 +--> [autoheader*] -> [config.h.in]
21372 [acconfig.h] ----. |
21379 Using only the @code{AH_} macros, @file{configure.ac} should be
21380 self-contained, and should not depend upon @file{acconfig.h} etc.
21383 @node autoupdate Invocation
21384 @section Using @command{autoupdate} to Modernize @file{configure.ac}
21385 @cindex @command{autoupdate}
21387 The @command{autoupdate} program updates a @file{configure.ac} file that
21388 calls Autoconf macros by their old names to use the current macro names.
21389 In version 2 of Autoconf, most of the macros were renamed to use a more
21390 uniform and descriptive naming scheme. @xref{Macro Names}, for a
21391 description of the new scheme. Although the old names still work
21392 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
21393 new names), you can make your @file{configure.ac} files more readable
21394 and make it easier to use the current Autoconf documentation if you
21395 update them to use the new macro names.
21397 @evindex SIMPLE_BACKUP_SUFFIX
21398 If given no arguments, @command{autoupdate} updates @file{configure.ac},
21399 backing up the original version with the suffix @file{~} (or the value
21400 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
21401 set). If you give @command{autoupdate} an argument, it reads that file
21402 instead of @file{configure.ac} and writes the updated file to the
21406 @command{autoupdate} accepts the following options:
21411 Print a summary of the command line options and exit.
21415 Print the version number of Autoconf and exit.
21419 Report processing steps.
21423 Don't remove the temporary files.
21427 Force the update even if the file has not changed. Disregard the cache.
21429 @item --include=@var{dir}
21430 @itemx -I @var{dir}
21431 Also look for input files in @var{dir}. Multiple invocations accumulate.
21432 Directories are browsed from last to first.
21434 @item --prepend-include=@var{dir}
21435 @itemx -B @var{dir}
21436 Prepend directory @var{dir} to the search path. This is used to include
21437 the language-specific files before any third-party macros.
21440 @node Obsolete Macros
21441 @section Obsolete Macros
21443 Several macros are obsoleted in Autoconf, for various reasons (typically
21444 they failed to quote properly, couldn't be extended for more recent
21445 issues, etc.). They are still supported, but deprecated: their use
21448 During the jump from Autoconf version 1 to version 2, most of the
21449 macros were renamed to use a more uniform and descriptive naming scheme,
21450 but their signature did not change. @xref{Macro Names}, for a
21451 description of the new naming scheme. Below, if there is just the mapping
21452 from old names to new names for these macros, the reader is invited to
21453 refer to the definition of the new macro for the signature and the
21458 @cvindex _ALL_SOURCE
21459 This macro is a platform-specific subset of
21460 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21465 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
21468 @defmac AC_ARG_ARRAY
21469 @acindex{ARG_ARRAY}
21470 Removed because of limited usefulness.
21475 This macro is obsolete; it does nothing.
21478 @defmac AC_C_LONG_DOUBLE
21479 @acindex{C_LONG_DOUBLE}
21480 @cvindex HAVE_LONG_DOUBLE
21481 If the C compiler supports a working @code{long double} type with more
21482 range or precision than the @code{double} type, define
21483 @code{HAVE_LONG_DOUBLE}.
21485 You should use @code{AC_TYPE_LONG_DOUBLE} or
21486 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
21489 @defmac AC_CANONICAL_SYSTEM
21490 @acindex{CANONICAL_SYSTEM}
21491 Determine the system type and set output variables to the names of the
21492 canonical system types. @xref{Canonicalizing}, for details about the
21493 variables this macro sets.
21495 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
21496 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
21497 the needs. Using @code{AC_CANONICAL_TARGET} is enough to run the two
21498 other macros (@pxref{Canonicalizing}).
21501 @defmac AC_CHAR_UNSIGNED
21502 @acindex{CHAR_UNSIGNED}
21503 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
21506 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
21507 @acindex{CHECK_TYPE}
21508 Autoconf, up to 2.13, used to provide this version of
21509 @code{AC_CHECK_TYPE}, deprecated because of its flaws. First, although
21510 it is a member of the @code{CHECK} clan, it does
21511 more than just checking. Secondly, missing types are defined
21512 using @code{#define}, not @code{typedef}, and this can lead to
21513 problems in the case of pointer types.
21515 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
21516 @ref{Generic Types}, for the description of the current macro.
21518 If the type @var{type} is not defined, define it to be the C (or C++)
21519 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
21521 This macro is equivalent to:
21524 AC_CHECK_TYPE([@var{type}], [],
21525 [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
21526 [Define to `@var{default}'
21527 if <sys/types.h> does not define.])])
21530 In order to keep backward compatibility, the two versions of
21531 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
21535 If there are three or four arguments, the modern version is used.
21538 If the second argument appears to be a C or C++ type, then the
21539 obsolete version is used. This happens if the argument is a C or C++
21540 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
21541 followed by one of @samp{[(* } and then by a string of zero or more
21542 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
21545 If the second argument is spelled with the alphabet of valid C and C++
21546 types, the user is warned and the modern version is used.
21549 Otherwise, the modern version is used.
21553 You are encouraged either to use a valid builtin type, or to use the
21554 equivalent modern code (see above), or better yet, to use
21555 @code{AC_CHECK_TYPES} together with
21558 #ifndef HAVE_LOFF_T
21559 typedef loff_t off_t;
21563 @c end of AC_CHECK_TYPE
21565 @defmac AC_CHECKING (@var{feature-description})
21570 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
21574 @xref{AC_MSG_NOTICE}.
21577 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
21578 @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
21579 @acindex{COMPILE_CHECK}
21580 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
21581 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
21582 addition that it prints @samp{checking for @var{echo-text}} to the
21583 standard output first, if @var{echo-text} is non-empty. Use
21584 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
21585 messages (@pxref{Printing Messages}).
21590 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
21593 @defmac AC_CROSS_CHECK
21594 @acindex{CROSS_CHECK}
21595 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
21602 Check for the Cygwin environment in which case the shell variable
21603 @code{CYGWIN} is set to @samp{yes}. Don't use this macro, the dignified
21604 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
21605 (@pxref{Canonicalizing}). As a matter of fact this macro is defined as:
21608 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
21610 *cygwin* ) CYGWIN=yes;;
21615 Beware that the variable @env{CYGWIN} has a special meaning when
21616 running Cygwin, and should not be changed. That's yet another reason
21617 not to use this macro.
21620 @defmac AC_DECL_SYS_SIGLIST
21621 @acindex{DECL_SYS_SIGLIST}
21622 @cvindex SYS_SIGLIST_DECLARED
21626 AC_CHECK_DECLS([sys_siglist], [], [],
21627 [#include <signal.h>
21628 /* NetBSD declares sys_siglist in unistd.h. */
21629 #ifdef HAVE_UNISTD_H
21630 # include <unistd.h>
21636 @xref{AC_CHECK_DECLS}.
21639 @defmac AC_DECL_YYTEXT
21640 @acindex{DECL_YYTEXT}
21641 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
21644 @defmac AC_DIR_HEADER
21645 @acindex{DIR_HEADER}
21650 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
21651 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
21652 (@pxref{AC_HEADER_DIRENT}),
21653 but defines a different set of C preprocessor macros to indicate which
21654 header file is found:
21656 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
21657 @item Header @tab Old Symbol @tab New Symbol
21658 @item @file{dirent.h} @tab @code{DIRENT} @tab @code{HAVE_DIRENT_H}
21659 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
21660 @item @file{sys/dir.h} @tab @code{SYSDIR} @tab @code{HAVE_SYS_DIR_H}
21661 @item @file{ndir.h} @tab @code{NDIR} @tab @code{HAVE_NDIR_H}
21665 @defmac AC_DYNIX_SEQ
21666 @acindex{DYNIX_SEQ}
21667 If on DYNIX/ptx, add @option{-lseq} to output variable
21668 @code{LIBS}. This macro used to be defined as
21671 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
21675 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
21681 Defined the output variable @code{EXEEXT} based on the output of the
21682 compiler, which is now done automatically. Typically set to empty
21683 string if Posix and @samp{.exe} if a DOS variant.
21688 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
21689 and sets @code{EMXOS2}. Don't use this macro, the dignified means to
21690 check the nature of the host is using @code{AC_CANONICAL_HOST}
21691 (@pxref{Canonicalizing}).
21694 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
21695 @ovar{action-if-not-given})
21697 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
21698 support providing a help string (@pxref{AC_ARG_ENABLE}).
21703 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
21708 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
21711 @defmac AC_FIND_XTRA
21712 @acindex{FIND_XTRA}
21713 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
21718 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
21721 @defmac AC_FUNC_CHECK
21722 @acindex{FUNC_CHECK}
21723 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
21726 @anchor{AC_FUNC_SETVBUF_REVERSED}
21727 @defmac AC_FUNC_SETVBUF_REVERSED
21728 @acindex{FUNC_SETVBUF_REVERSED}
21729 @cvindex SETVBUF_REVERSED
21730 @c @fuindex setvbuf
21731 @prindex @code{setvbuf}
21732 Do nothing. Formerly, this macro checked whether @code{setvbuf} takes
21733 the buffering type as its second argument and the buffer pointer as the
21734 third, instead of the other way around, and defined
21735 @code{SETVBUF_REVERSED}. However, the last systems to have the problem
21736 were those based on SVR2, which became obsolete in 1987, and the macro
21737 is no longer needed.
21740 @defmac AC_FUNC_WAIT3
21741 @acindex{FUNC_WAIT3}
21742 @cvindex HAVE_WAIT3
21744 @prindex @code{wait3}
21745 If @code{wait3} is found and fills in the contents of its third argument
21746 (a @samp{struct rusage *}), which HP-UX does not do, define
21749 These days portable programs should use @code{waitpid}, not
21750 @code{wait3}, as @code{wait3} has been removed from Posix.
21753 @defmac AC_GCC_TRADITIONAL
21754 @acindex{GCC_TRADITIONAL}
21755 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
21758 @defmac AC_GETGROUPS_T
21759 @acindex{GETGROUPS_T}
21760 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
21763 @defmac AC_GETLOADAVG
21764 @acindex{GETLOADAVG}
21765 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
21768 @defmac AC_GNU_SOURCE
21769 @acindex{GNU_SOURCE}
21770 @cvindex _GNU_SOURCE
21771 This macro is a platform-specific subset of
21772 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21775 @defmac AC_HAVE_FUNCS
21776 @acindex{HAVE_FUNCS}
21777 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
21780 @defmac AC_HAVE_HEADERS
21781 @acindex{HAVE_HEADERS}
21782 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
21785 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
21786 @ovar{action-if-not-found}, @ovar{other-libraries})
21787 @acindex{HAVE_LIBRARY}
21788 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
21789 @var{function} argument of @code{main}. In addition, @var{library} can
21790 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}. In
21791 all of those cases, the compiler is passed @option{-lfoo}. However,
21792 @var{library} cannot be a shell variable; it must be a literal name.
21793 @xref{AC_CHECK_LIB}.
21796 @defmac AC_HAVE_POUNDBANG
21797 @acindex{HAVE_POUNDBANG}
21798 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
21801 @defmac AC_HEADER_CHECK
21802 @acindex{HEADER_CHECK}
21803 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
21806 @defmac AC_HEADER_EGREP
21807 @acindex{HEADER_EGREP}
21808 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
21811 @defmac AC_HELP_STRING
21812 @acindex{HELP_STRING}
21813 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
21816 @defmac AC_INIT (@var{unique-file-in-source-dir})
21818 Formerly @code{AC_INIT} used to have a single argument, and was
21823 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
21825 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
21830 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
21833 @defmac AC_INT_16_BITS
21834 @acindex{INT_16_BITS}
21835 @cvindex INT_16_BITS
21836 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
21837 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
21840 @defmac AC_IRIX_SUN
21842 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
21843 @code{LIBS}. If you were using it to get @code{getmntent}, use
21844 @code{AC_FUNC_GETMNTENT} instead. If you used it for the NIS versions
21845 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
21846 getpwnam)}. Up to Autoconf 2.13, it used to be
21849 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
21853 now it is defined as
21857 AC_CHECK_LIB([sun], [getpwnam])
21861 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
21864 @defmac AC_ISC_POSIX
21865 @acindex{ISC_POSIX}
21867 This macro adds @option{-lcposix} to output variable @code{LIBS} if
21868 necessary for Posix facilities. Sun dropped support for the obsolete
21869 INTERACTIVE Systems Corporation Unix on 2006-07-23. New programs
21870 need not use this macro. It is implemented as
21871 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
21876 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
21879 @defmac AC_LANG_CPLUSPLUS
21880 @acindex{LANG_CPLUSPLUS}
21881 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
21884 @defmac AC_LANG_FORTRAN77
21885 @acindex{LANG_FORTRAN77}
21886 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
21889 @defmac AC_LANG_RESTORE
21890 @acindex{LANG_RESTORE}
21891 Select the @var{language} that is saved on the top of the stack, as set
21892 by @code{AC_LANG_SAVE}, remove it from the stack, and call
21893 @code{AC_LANG(@var{language})}. @xref{Language Choice}, for the
21894 preferred way to change languages.
21897 @defmac AC_LANG_SAVE
21898 @acindex{LANG_SAVE}
21899 Remember the current language (as set by @code{AC_LANG}) on a stack.
21900 The current language does not change. @code{AC_LANG_PUSH} is preferred
21901 (@pxref{AC_LANG_PUSH}).
21904 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
21905 @acindex{LINK_FILES}
21906 This is an obsolete version of @code{AC_CONFIG_LINKS}
21907 (@pxref{AC_CONFIG_LINKS}. An updated version of:
21910 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
21918 AC_CONFIG_LINKS([host.h:config/$machine.h
21919 object.h:config/$obj_format.h])
21925 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
21928 @defmac AC_LONG_64_BITS
21929 @acindex{LONG_64_BITS}
21930 @cvindex LONG_64_BITS
21931 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
21932 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
21933 (@pxref{AC_CHECK_SIZEOF}).
21936 @defmac AC_LONG_DOUBLE
21937 @acindex{LONG_DOUBLE}
21938 If the C compiler supports a working @code{long double} type with more
21939 range or precision than the @code{double} type, define
21940 @code{HAVE_LONG_DOUBLE}.
21942 You should use @code{AC_TYPE_LONG_DOUBLE} or
21943 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
21946 @defmac AC_LONG_FILE_NAMES
21947 @acindex{LONG_FILE_NAMES}
21950 AC_SYS_LONG_FILE_NAMES
21953 @xref{AC_SYS_LONG_FILE_NAMES}.
21956 @defmac AC_MAJOR_HEADER
21957 @acindex{MAJOR_HEADER}
21958 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
21961 @defmac AC_MEMORY_H
21963 @cvindex NEED_MEMORY_H
21964 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
21965 defined in @file{memory.h}. Today it is equivalent to
21966 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}). Adjust
21967 your code to depend upon
21968 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
21974 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
21975 environment and sets @code{MINGW32}. Don't use this macro, the
21976 dignified means to check the nature of the host is using
21977 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
21983 @cvindex _POSIX_SOURCE
21984 @cvindex _POSIX_1_SOURCE
21985 This macro is a platform-specific subset of
21986 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21989 @defmac AC_MINUS_C_MINUS_O
21990 @acindex{MINUS_C_MINUS_O}
21991 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
21996 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
22001 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
22007 Defined the output variable @code{OBJEXT} based on the output of the
22008 compiler, after .c files have been excluded. Typically set to @samp{o}
22009 if Posix, @samp{obj} if a DOS variant.
22010 Now the compiler checking macros handle
22011 this automatically.
22014 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
22016 Make M4 print a message to the standard error output warning that
22017 @var{this-macro-name} is obsolete, and giving the file and line number
22018 where it was called. @var{this-macro-name} should be the name of the
22019 macro that is calling @code{AC_OBSOLETE}. If @var{suggestion} is given,
22020 it is printed at the end of the warning message; for example, it can be
22021 a suggestion for what to use instead of @var{this-macro-name}.
22026 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
22030 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
22031 services to the user (@pxref{AU_DEFUN}).
22036 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
22039 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
22041 The use of @code{AC_OUTPUT} with arguments is deprecated. This obsoleted
22042 interface is equivalent to:
22046 AC_CONFIG_FILES(@var{file}@dots{})
22047 AC_CONFIG_COMMANDS([default],
22048 @var{extra-cmds}, @var{init-cmds})
22054 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
22057 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
22058 @acindex{OUTPUT_COMMANDS}
22059 Specify additional shell commands to run at the end of
22060 @file{config.status}, and shell commands to initialize any variables
22061 from @command{configure}. This macro may be called multiple times. It is
22062 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
22064 Here is an unrealistic example:
22068 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
22070 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
22074 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
22075 additional key, an important difference is that
22076 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
22077 @code{AC_CONFIG_COMMANDS}. This means that @code{AC_CONFIG_COMMANDS}
22078 can safely be given macro calls as arguments:
22081 AC_CONFIG_COMMANDS(foo, [my_FOO()])
22085 Conversely, where one level of quoting was enough for literal strings
22086 with @code{AC_OUTPUT_COMMANDS}, you need two with
22087 @code{AC_CONFIG_COMMANDS}. The following lines are equivalent:
22091 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
22092 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
22099 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
22104 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
22107 @defmac AC_PROGRAMS_CHECK
22108 @acindex{PROGRAMS_CHECK}
22109 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
22112 @defmac AC_PROGRAMS_PATH
22113 @acindex{PROGRAMS_PATH}
22114 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
22117 @defmac AC_PROGRAM_CHECK
22118 @acindex{PROGRAM_CHECK}
22119 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
22122 @defmac AC_PROGRAM_EGREP
22123 @acindex{PROGRAM_EGREP}
22124 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
22127 @defmac AC_PROGRAM_PATH
22128 @acindex{PROGRAM_PATH}
22129 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
22132 @defmac AC_REMOTE_TAPE
22133 @acindex{REMOTE_TAPE}
22134 Removed because of limited usefulness.
22137 @defmac AC_RESTARTABLE_SYSCALLS
22138 @acindex{RESTARTABLE_SYSCALLS}
22139 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}. However,
22140 these days portable programs should use @code{sigaction} with
22141 @code{SA_RESTART} if they want restartable system calls. They should
22142 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22143 system call is restartable is a dynamic issue, not a configuration-time
22147 @defmac AC_RETSIGTYPE
22148 @acindex{RETSIGTYPE}
22149 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
22150 is obsolete when assuming C89 or better.
22155 Removed because of limited usefulness.
22158 @defmac AC_SCO_INTL
22161 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}. This
22162 macro used to do this:
22165 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
22169 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
22172 @defmac AC_SETVBUF_REVERSED
22173 @acindex{SETVBUF_REVERSED}
22176 AC_FUNC_SETVBUF_REVERSED
22179 @xref{AC_FUNC_SETVBUF_REVERSED}.
22182 @defmac AC_SET_MAKE
22184 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
22187 @defmac AC_SIZEOF_TYPE
22188 @acindex{SIZEOF_TYPE}
22189 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
22194 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
22197 @defmac AC_STAT_MACROS_BROKEN
22198 @acindex{STAT_MACROS_BROKEN}
22199 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
22202 @defmac AC_STDC_HEADERS
22203 @acindex{STDC_HEADERS}
22204 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
22209 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
22212 @defmac AC_STRUCT_ST_BLKSIZE
22213 @acindex{STRUCT_ST_BLKSIZE}
22214 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
22215 @cvindex HAVE_ST_BLKSIZE
22216 If @code{struct stat} contains an @code{st_blksize} member, define
22217 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}. The former name,
22218 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
22219 the future. This macro is obsoleted, and should be replaced by
22222 AC_CHECK_MEMBERS([struct stat.st_blksize])
22225 @xref{AC_CHECK_MEMBERS}.
22228 @defmac AC_STRUCT_ST_RDEV
22229 @acindex{STRUCT_ST_RDEV}
22230 @cvindex HAVE_ST_RDEV
22231 @cvindex HAVE_STRUCT_STAT_ST_RDEV
22232 If @code{struct stat} contains an @code{st_rdev} member, define
22233 @code{HAVE_STRUCT_STAT_ST_RDEV}. The former name for this macro,
22234 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
22235 in the future. Actually, even the new macro is obsolete and should be
22238 AC_CHECK_MEMBERS([struct stat.st_rdev])
22241 @xref{AC_CHECK_MEMBERS}.
22244 @defmac AC_ST_BLKSIZE
22245 @acindex{ST_BLKSIZE}
22246 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22249 @defmac AC_ST_BLOCKS
22250 @acindex{ST_BLOCKS}
22251 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
22256 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22259 @defmac AC_SYS_RESTARTABLE_SYSCALLS
22260 @acindex{SYS_RESTARTABLE_SYSCALLS}
22261 @cvindex HAVE_RESTARTABLE_SYSCALLS
22262 If the system automatically restarts a system call that is interrupted
22263 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}. This macro does
22264 not check whether system calls are restarted in general---it checks whether a
22265 signal handler installed with @code{signal} (but not @code{sigaction})
22266 causes system calls to be restarted. It does not check whether system calls
22267 can be restarted when interrupted by signals that have no handler.
22269 These days portable programs should use @code{sigaction} with
22270 @code{SA_RESTART} if they want restartable system calls. They should
22271 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22272 system call is restartable is a dynamic issue, not a configuration-time
22276 @defmac AC_SYS_SIGLIST_DECLARED
22277 @acindex{SYS_SIGLIST_DECLARED}
22278 This macro was renamed @code{AC_DECL_SYS_SIGLIST}. However, even that
22279 name is obsolete, as the same functionality is now acheived via
22280 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
22283 @defmac AC_TEST_CPP
22285 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
22286 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
22289 @defmac AC_TEST_PROGRAM
22290 @acindex{TEST_PROGRAM}
22291 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
22292 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
22295 @defmac AC_TIMEZONE
22297 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
22300 @defmac AC_TIME_WITH_SYS_TIME
22301 @acindex{TIME_WITH_SYS_TIME}
22302 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
22305 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
22306 @ovar{action-if-true}, @ovar{action-if-false})
22307 @acindex{TRY_COMPILE}
22312 [AC_LANG_PROGRAM([[@var{includes}]],
22313 [[@var{function-body}]])],
22314 [@var{action-if-true}],
22315 [@var{action-if-false}])
22319 @xref{Running the Compiler}.
22321 This macro double quotes both @var{includes} and @var{function-body}.
22323 For C and C++, @var{includes} is any @code{#include} statements needed
22324 by the code in @var{function-body} (@var{includes} is ignored if
22325 the currently selected language is Fortran or Fortran 77). The compiler
22326 and compilation flags are determined by the current language
22327 (@pxref{Language Choice}).
22330 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
22336 [AC_LANG_SOURCE([[@var{input}]])],
22337 [@var{action-if-true}],
22338 [@var{action-if-false}])
22342 @xref{Running the Preprocessor}.
22344 This macro double quotes the @var{input}.
22347 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
22348 @ovar{action-if-true}, @ovar{action-if-false})
22354 [AC_LANG_PROGRAM([[@var{includes}]],
22355 [[@var{function-body}]])],
22356 [@var{action-if-true}],
22357 [@var{action-if-false}])
22361 @xref{Running the Compiler}.
22363 This macro double quotes both @var{includes} and @var{function-body}.
22365 Depending on the current language (@pxref{Language Choice}), create a
22366 test program to see whether a function whose body consists of
22367 @var{function-body} can be compiled and linked. If the file compiles
22368 and links successfully, run shell commands @var{action-if-found},
22369 otherwise run @var{action-if-not-found}.
22371 This macro double quotes both @var{includes} and @var{function-body}.
22373 For C and C++, @var{includes} is any @code{#include} statements needed
22374 by the code in @var{function-body} (@var{includes} is ignored if
22375 the currently selected language is Fortran or Fortran 77). The compiler
22376 and compilation flags are determined by the current language
22377 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
22378 @code{LIBS} are used for linking.
22381 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
22382 @ovar{action-if-not-found})
22383 @acindex{TRY_LINK_FUNC}
22384 This macro is equivalent to
22386 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
22387 [@var{action-if-found}], [@var{action-if-not-found}])
22390 @xref{AC_LINK_IFELSE}.
22393 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
22394 @ovar{action-if-false}, @ovar{action-if-cross-compiling})
22400 [AC_LANG_SOURCE([[@var{program}]])],
22401 [@var{action-if-true}],
22402 [@var{action-if-false}],
22403 [@var{action-if-cross-compiling}])
22410 @anchor{AC_TYPE_SIGNAL}
22411 @defmac AC_TYPE_SIGNAL
22412 @acindex{TYPE_SIGNAL}
22413 @cvindex RETSIGTYPE
22414 @hdrindex{signal.h}
22415 If @file{signal.h} declares @code{signal} as returning a pointer to a
22416 function returning @code{void}, define @code{RETSIGTYPE} to be
22417 @code{void}; otherwise, define it to be @code{int}. These days, it is
22418 portable to assume C89, and that signal handlers return @code{void},
22419 without needing to use this macro or @code{RETSIGTYPE}.
22421 When targetting older K&R C, it is possible to define signal handlers as
22422 returning type @code{RETSIGTYPE}, and omit a return statement:
22437 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
22440 @defmac AC_UNISTD_H
22442 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
22448 Define @code{USG} if the BSD string functions are defined in
22449 @file{strings.h}. You should no longer depend upon @code{USG}, but on
22450 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
22453 @defmac AC_UTIME_NULL
22454 @acindex{UTIME_NULL}
22455 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
22458 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
22459 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
22460 If the cache file is inconsistent with the current host, target and
22461 build system types, it used to execute @var{cmd} or print a default
22462 error message. This is now handled by default.
22465 @defmac AC_VERBOSE (@var{result-description})
22467 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
22472 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
22477 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
22482 This macro was renamed @code{AC_FUNC_WAIT3}. However, these days
22483 portable programs should use @code{waitpid}, not @code{wait3}, as
22484 @code{wait3} has been removed from Posix.
22489 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
22492 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
22493 @ovar{action-if-not-given})
22495 This is an obsolete version of @code{AC_ARG_WITH} that does not
22496 support providing a help string (@pxref{AC_ARG_WITH}).
22499 @defmac AC_WORDS_BIGENDIAN
22500 @acindex{WORDS_BIGENDIAN}
22501 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
22504 @defmac AC_XENIX_DIR
22505 @acindex{XENIX_DIR}
22507 This macro used to add @option{-lx} to output variable @code{LIBS} if on
22508 Xenix. Also, if @file{dirent.h} is being checked for, added
22509 @option{-ldir} to @code{LIBS}. Now it is merely an alias of
22510 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
22511 running XENIX on which you should not depend:
22514 AC_MSG_CHECKING([for Xenix])
22515 AC_EGREP_CPP([yes],
22516 [#if defined M_XENIX && !defined M_UNIX
22519 [AC_MSG_RESULT([yes]); XENIX=yes],
22520 [AC_MSG_RESULT([no]); XENIX=])
22523 Don't use this macro, the dignified means to check the nature of the
22524 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
22527 @defmac AC_YYTEXT_POINTER
22528 @acindex{YYTEXT_POINTER}
22529 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
22530 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
22534 @section Upgrading From Version 1
22535 @cindex Upgrading autoconf
22536 @cindex Autoconf upgrading
22538 Autoconf version 2 is mostly backward compatible with version 1.
22539 However, it introduces better ways to do some things, and doesn't
22540 support some of the ugly things in version 1. So, depending on how
22541 sophisticated your @file{configure.ac} files are, you might have to do
22542 some manual work in order to upgrade to version 2. This chapter points
22543 out some problems to watch for when upgrading. Also, perhaps your
22544 @command{configure} scripts could benefit from some of the new features in
22545 version 2; the changes are summarized in the file @file{NEWS} in the
22546 Autoconf distribution.
22549 * Changed File Names:: Files you might rename
22550 * Changed Makefiles:: New things to put in @file{Makefile.in}
22551 * Changed Macros:: Macro calls you might replace
22552 * Changed Results:: Changes in how to check test results
22553 * Changed Macro Writing:: Better ways to write your own macros
22556 @node Changed File Names
22557 @subsection Changed File Names
22559 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
22560 in a particular package's source directory), you must rename it to
22561 @file{acsite.m4}. @xref{autoconf Invocation}.
22563 If you distribute @file{install.sh} with your package, rename it to
22564 @file{install-sh} so @command{make} builtin rules don't inadvertently
22565 create a file called @file{install} from it. @code{AC_PROG_INSTALL}
22566 looks for the script under both names, but it is best to use the new name.
22568 If you were using @file{config.h.top}, @file{config.h.bot}, or
22569 @file{acconfig.h}, you still can, but you have less clutter if you
22570 use the @code{AH_} macros. @xref{Autoheader Macros}.
22572 @node Changed Makefiles
22573 @subsection Changed Makefiles
22575 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
22576 your @file{Makefile.in} files, so they can take advantage of the values
22577 of those variables in the environment when @command{configure} is run.
22578 Doing this isn't necessary, but it's a convenience for users.
22580 Also add @samp{@@configure_input@@} in a comment to each input file for
22581 @code{AC_OUTPUT}, so that the output files contain a comment saying
22582 they were produced by @command{configure}. Automatically selecting the
22583 right comment syntax for all the kinds of files that people call
22584 @code{AC_OUTPUT} on became too much work.
22586 Add @file{config.log} and @file{config.cache} to the list of files you
22587 remove in @code{distclean} targets.
22589 If you have the following in @file{Makefile.in}:
22592 prefix = /usr/local
22593 exec_prefix = $(prefix)
22597 you must change it to:
22600 prefix = @@prefix@@
22601 exec_prefix = @@exec_prefix@@
22605 The old behavior of replacing those variables without @samp{@@}
22606 characters around them has been removed.
22608 @node Changed Macros
22609 @subsection Changed Macros
22611 Many of the macros were renamed in Autoconf version 2. You can still
22612 use the old names, but the new ones are clearer, and it's easier to find
22613 the documentation for them. @xref{Obsolete Macros}, for a table showing the
22614 new names for the old macros. Use the @command{autoupdate} program to
22615 convert your @file{configure.ac} to using the new macro names.
22616 @xref{autoupdate Invocation}.
22618 Some macros have been superseded by similar ones that do the job better,
22619 but are not call-compatible. If you get warnings about calling obsolete
22620 macros while running @command{autoconf}, you may safely ignore them, but
22621 your @command{configure} script generally works better if you follow
22622 the advice that is printed about what to replace the obsolete macros with. In
22623 particular, the mechanism for reporting the results of tests has
22624 changed. If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
22625 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
22626 looks better if you switch to @code{AC_MSG_CHECKING} and
22627 @code{AC_MSG_RESULT}. @xref{Printing Messages}. Those macros work best
22628 in conjunction with cache variables. @xref{Caching Results}.
22632 @node Changed Results
22633 @subsection Changed Results
22635 If you were checking the results of previous tests by examining the
22636 shell variable @code{DEFS}, you need to switch to checking the values of
22637 the cache variables for those tests. @code{DEFS} no longer exists while
22638 @command{configure} is running; it is only created when generating output
22639 files. This difference from version 1 is because properly quoting the
22640 contents of that variable turned out to be too cumbersome and
22641 inefficient to do every time @code{AC_DEFINE} is called. @xref{Cache
22644 For example, here is a @file{configure.ac} fragment written for Autoconf
22648 AC_HAVE_FUNCS(syslog)
22650 *-DHAVE_SYSLOG*) ;;
22651 *) # syslog is not in the default libraries. See if it's in some other.
22653 for lib in bsd socket inet; do
22654 AC_CHECKING(for syslog in -l$lib)
22655 LIBS="-l$lib $saved_LIBS"
22656 AC_HAVE_FUNCS(syslog)
22658 *-DHAVE_SYSLOG*) break ;;
22666 Here is a way to write it for version 2:
22669 AC_CHECK_FUNCS([syslog])
22670 if test "x$ac_cv_func_syslog" = xno; then
22671 # syslog is not in the default libraries. See if it's in some other.
22672 for lib in bsd socket inet; do
22673 AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
22674 LIBS="-l$lib $LIBS"; break])
22679 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
22680 backslashes before quotes, you need to remove them. It now works
22681 predictably, and does not treat quotes (except back quotes) specially.
22682 @xref{Setting Output Variables}.
22684 All of the Boolean shell variables set by Autoconf macros now use
22685 @samp{yes} for the true value. Most of them use @samp{no} for false,
22686 though for backward compatibility some use the empty string instead. If
22687 you were relying on a shell variable being set to something like 1 or
22688 @samp{t} for true, you need to change your tests.
22690 @node Changed Macro Writing
22691 @subsection Changed Macro Writing
22693 When defining your own macros, you should now use @code{AC_DEFUN}
22694 instead of @code{define}. @code{AC_DEFUN} automatically calls
22695 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
22696 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
22697 messages on the screen. There's no actual harm in continuing to use the
22698 older way, but it's less convenient and attractive. @xref{Macro
22701 You probably looked at the macros that came with Autoconf as a guide for
22702 how to do things. It would be a good idea to take a look at the new
22703 versions of them, as the style is somewhat improved and they take
22704 advantage of some new features.
22706 If you were doing tricky things with undocumented Autoconf internals
22707 (macros, variables, diversions), check whether you need to change
22708 anything to account for changes that have been made. Perhaps you can
22709 even use an officially supported technique in version 2 instead of
22710 kludging. Or perhaps not.
22712 To speed up your locally written feature tests, add caching to them.
22713 See whether any of your tests are of general enough usefulness to
22714 encapsulate them into macros that you can share.
22717 @node Autoconf 2.13
22718 @section Upgrading From Version 2.13
22719 @cindex Upgrading autoconf
22720 @cindex Autoconf upgrading
22722 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
22723 suits this section@enddots{}
22726 Autoconf version 2.50 is mostly backward compatible with version 2.13.
22727 However, it introduces better ways to do some things, and doesn't
22728 support some of the ugly things in version 2.13. So, depending on how
22729 sophisticated your @file{configure.ac} files are, you might have to do
22730 some manual work in order to upgrade to version 2.50. This chapter
22731 points out some problems to watch for when upgrading. Also, perhaps
22732 your @command{configure} scripts could benefit from some of the new
22733 features in version 2.50; the changes are summarized in the file
22734 @file{NEWS} in the Autoconf distribution.
22738 * Changed Quotation:: Broken code which used to work
22739 * New Macros:: Interaction with foreign macros
22740 * Hosts and Cross-Compilation:: Bugward compatibility kludges
22741 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
22742 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
22745 @node Changed Quotation
22746 @subsection Changed Quotation
22748 The most important changes are invisible to you: the implementation of
22749 most macros have completely changed. This allowed more factorization of
22750 the code, better error messages, a higher uniformity of the user's
22751 interface etc. Unfortunately, as a side effect, some construct which
22752 used to (miraculously) work might break starting with Autoconf 2.50.
22753 The most common culprit is bad quotation.
22755 For instance, in the following example, the message is not properly
22760 AC_CHECK_HEADERS(foo.h, ,
22761 AC_MSG_ERROR(cannot find foo.h, bailing out))
22766 Autoconf 2.13 simply ignores it:
22769 $ @kbd{autoconf-2.13; ./configure --silent}
22770 creating cache ./config.cache
22771 configure: error: cannot find foo.h
22776 while Autoconf 2.50 produces a broken @file{configure}:
22779 $ @kbd{autoconf-2.50; ./configure --silent}
22780 configure: error: cannot find foo.h
22781 ./configure: exit: bad non-numeric arg `bailing'
22782 ./configure: exit: bad non-numeric arg `bailing'
22786 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
22790 AC_INIT([Example], [1.0], [bug-example@@example.org])
22791 AC_CHECK_HEADERS([foo.h], [],
22792 [AC_MSG_ERROR([cannot find foo.h, bailing out])])
22796 Many many (and many more) Autoconf macros were lacking proper quotation,
22797 including no less than@dots{} @code{AC_DEFUN} itself!
22800 $ @kbd{cat configure.in}
22801 AC_DEFUN([AC_PROG_INSTALL],
22802 [# My own much better version
22807 $ @kbd{autoconf-2.13}
22808 autoconf: Undefined macros:
22809 ***BUG in Autoconf--please report*** AC_FD_MSG
22810 ***BUG in Autoconf--please report*** AC_EPI
22811 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
22812 configure.in:5:AC_PROG_INSTALL
22813 $ @kbd{autoconf-2.50}
22819 @subsection New Macros
22821 @cindex undefined macro
22822 @cindex @code{_m4_divert_diversion}
22824 While Autoconf was relatively dormant in the late 1990s, Automake
22825 provided Autoconf-like macros for a while. Starting with Autoconf 2.50
22826 in 2001, Autoconf provided
22827 versions of these macros, integrated in the @code{AC_} namespace,
22828 instead of @code{AM_}. But in order to ease the upgrading via
22829 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
22831 Unfortunately older versions of Automake (e.g., Automake 1.4)
22832 did not quote the names of these macros.
22833 Therefore, when @command{m4} finds something like
22834 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
22835 @code{AM_TYPE_PTRDIFF_T} is
22836 expanded, replaced with its Autoconf definition.
22838 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
22839 complains, in its own words:
22842 $ @kbd{cat configure.ac}
22843 AC_INIT([Example], [1.0], [bug-example@@example.org])
22845 $ @kbd{aclocal-1.4}
22847 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
22848 aclocal.m4:17: the top level
22849 autom4te: m4 failed with exit status: 1
22853 Modern versions of Automake no longer define most of these
22854 macros, and properly quote the names of the remaining macros.
22855 If you must use an old Automake, do not depend upon macros from Automake
22856 as it is simply not its job
22857 to provide macros (but the one it requires itself):
22860 $ @kbd{cat configure.ac}
22861 AC_INIT([Example], [1.0], [bug-example@@example.org])
22863 $ @kbd{rm aclocal.m4}
22865 autoupdate: `configure.ac' is updated
22866 $ @kbd{cat configure.ac}
22867 AC_INIT([Example], [1.0], [bug-example@@example.org])
22868 AC_CHECK_TYPES([ptrdiff_t])
22869 $ @kbd{aclocal-1.4}
22875 @node Hosts and Cross-Compilation
22876 @subsection Hosts and Cross-Compilation
22877 @cindex Cross compilation
22879 Based on the experience of compiler writers, and after long public
22880 debates, many aspects of the cross-compilation chain have changed:
22884 the relationship between the build, host, and target architecture types,
22887 the command line interface for specifying them to @command{configure},
22890 the variables defined in @command{configure},
22893 the enabling of cross-compilation mode.
22898 The relationship between build, host, and target have been cleaned up:
22899 the chain of default is now simply: target defaults to host, host to
22900 build, and build to the result of @command{config.guess}. Nevertheless,
22901 in order to ease the transition from 2.13 to 2.50, the following
22902 transition scheme is implemented. @emph{Do not rely on it}, as it will
22903 be completely disabled in a couple of releases (we cannot keep it, as it
22904 proves to cause more problems than it cures).
22906 They all default to the result of running @command{config.guess}, unless
22907 you specify either @option{--build} or @option{--host}. In this case,
22908 the default becomes the system type you specified. If you specify both,
22909 and they're different, @command{configure} enters cross compilation
22910 mode, so it doesn't run any tests that require execution.
22912 Hint: if you mean to override the result of @command{config.guess},
22913 prefer @option{--build} over @option{--host}. In the future,
22914 @option{--host} will not override the name of the build system type.
22915 Whenever you specify @option{--host}, be sure to specify @option{--build}
22920 For backward compatibility, @command{configure} accepts a system
22921 type as an option by itself. Such an option overrides the
22922 defaults for build, host, and target system types. The following
22923 configure statement configures a cross toolchain that runs on
22924 NetBSD/alpha but generates code for GNU Hurd/sparc,
22925 which is also the build platform.
22928 ./configure --host=alpha-netbsd sparc-gnu
22933 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
22934 and @code{target} had a different semantics before and after the
22935 invocation of @code{AC_CANONICAL_BUILD} etc. Now, the argument of
22936 @option{--build} is strictly copied into @code{build_alias}, and is left
22937 empty otherwise. After the @code{AC_CANONICAL_BUILD}, @code{build} is
22938 set to the canonicalized build type. To ease the transition, before,
22939 its contents is the same as that of @code{build_alias}. Do @emph{not}
22940 rely on this broken feature.
22942 For consistency with the backward compatibility scheme exposed above,
22943 when @option{--host} is specified but @option{--build} isn't, the build
22944 system is assumed to be the same as @option{--host}, and
22945 @samp{build_alias} is set to that value. Eventually, this
22946 historically incorrect behavior will go away.
22950 The former scheme to enable cross-compilation proved to cause more harm
22951 than good, in particular, it used to be triggered too easily, leaving
22952 regular end users puzzled in front of cryptic error messages.
22953 @command{configure} could even enter cross-compilation mode only
22954 because the compiler was not functional. This is mainly because
22955 @command{configure} used to try to detect cross-compilation, instead of
22956 waiting for an explicit flag from the user.
22958 Now, @command{configure} enters cross-compilation mode if and only if
22959 @option{--host} is passed.
22961 That's the short documentation. To ease the transition between 2.13 and
22962 its successors, a more complicated scheme is implemented. @emph{Do not
22963 rely on the following}, as it will be removed in the near future.
22965 If you specify @option{--host}, but not @option{--build}, when
22966 @command{configure} performs the first compiler test it tries to run
22967 an executable produced by the compiler. If the execution fails, it
22968 enters cross-compilation mode. This is fragile. Moreover, by the time
22969 the compiler test is performed, it may be too late to modify the
22970 build-system type: other tests may have already been performed.
22971 Therefore, whenever you specify @option{--host}, be sure to specify
22972 @option{--build} too.
22975 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
22979 enters cross-compilation mode. The former interface, which
22980 consisted in setting the compiler to a cross-compiler without informing
22981 @command{configure} is obsolete. For instance, @command{configure}
22982 fails if it can't run the code generated by the specified compiler if you
22983 configure as follows:
22986 ./configure CC=m68k-coff-gcc
22990 @node AC_LIBOBJ vs LIBOBJS
22991 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
22993 Up to Autoconf 2.13, the replacement of functions was triggered via the
22994 variable @code{LIBOBJS}. Since Autoconf 2.50, the macro
22995 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
22996 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
22998 This change is mandated by the unification of the GNU Build System
22999 components. In particular, the various fragile techniques used to parse
23000 a @file{configure.ac} are all replaced with the use of traces. As a
23001 consequence, any action must be traceable, which obsoletes critical
23002 variable assignments. Fortunately, @code{LIBOBJS} was the only problem,
23003 and it can even be handled gracefully (read, ``without your having to
23004 change something'').
23006 There were two typical uses of @code{LIBOBJS}: asking for a replacement
23007 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
23011 As for function replacement, the fix is immediate: use
23012 @code{AC_LIBOBJ}. For instance:
23015 LIBOBJS="$LIBOBJS fnmatch.o"
23016 LIBOBJS="$LIBOBJS malloc.$ac_objext"
23020 should be replaced with:
23023 AC_LIBOBJ([fnmatch])
23024 AC_LIBOBJ([malloc])
23030 When used with Automake 1.10 or newer, a suitable value for
23031 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
23032 can be referenced from any @file{Makefile.am}. Even without Automake,
23033 arranging for @code{LIBOBJDIR} to be set correctly enables
23034 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
23035 The @code{LIBOBJDIR} feature is experimental.
23038 @node AC_ACT_IFELSE vs AC_TRY_ACT
23039 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
23040 @c the anchor keeps the old node name, to try to avoid breaking links
23041 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
23043 @acindex{@var{ACT}_IFELSE}
23044 @acindex{TRY_@var{ACT}}
23045 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
23046 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
23047 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
23048 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
23049 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
23050 @code{AC_TRY_RUN}. The motivations where:
23053 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
23054 quoting their arguments;
23057 the combinatoric explosion is solved by decomposing on the one hand the
23058 generation of sources, and on the other hand executing the program;
23061 this scheme helps supporting more languages than plain C and C++.
23064 In addition to the change of syntax, the philosophy has changed too:
23065 while emphasis was put on speed at the expense of accuracy, today's
23066 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
23070 As a perfect example of what is @emph{not} to be done, here is how to
23071 find out whether a header file contains a particular declaration, such
23072 as a typedef, a structure, a structure member, or a function. Use
23073 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
23074 header file; on some systems the symbol might be defined in another
23075 header file that the file you are checking includes.
23077 As a (bad) example, here is how you should not check for C preprocessor
23078 symbols, either defined by header files or predefined by the C
23079 preprocessor: using @code{AC_EGREP_CPP}:
23087 ], is_aix=yes, is_aix=no)
23091 The above example, properly written would (i) use
23092 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
23096 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
23098 error: This isn't AIX!
23107 @c ============================= Generating Test Suites with Autotest
23109 @node Using Autotest
23110 @chapter Generating Test Suites with Autotest
23115 @strong{N.B.: This section describes a feature which is still
23116 stabilizing. Although we believe that Autotest is useful as-is, this
23117 documentation describes an interface which might change in the future:
23118 do not depend upon Autotest without subscribing to the Autoconf mailing
23122 It is paradoxical that portable projects depend on nonportable tools
23123 to run their test suite. Autoconf by itself is the paragon of this
23124 problem: although it aims at perfectly portability, up to 2.13 its
23125 test suite was using DejaGNU, a rich and complex testing
23126 framework, but which is far from being standard on Posix systems.
23127 Worse yet, it was likely to be missing on the most fragile platforms,
23128 the very platforms that are most likely to torture Autoconf and
23129 exhibit deficiencies.
23131 To circumvent this problem, many package maintainers have developed their
23132 own testing framework, based on simple shell scripts whose sole outputs
23133 are exit status values describing whether the test succeeded. Most of
23134 these tests share common patterns, and this can result in lots of
23135 duplicated code and tedious maintenance.
23137 Following exactly the same reasoning that yielded to the inception of
23138 Autoconf, Autotest provides a test suite generation framework, based on
23139 M4 macros building a portable shell script. The suite itself is
23140 equipped with automatic logging and tracing facilities which greatly
23141 diminish the interaction with bug reporters, and simple timing reports.
23143 Autoconf itself has been using Autotest for years, and we do attest that
23144 it has considerably improved the strength of the test suite and the
23145 quality of bug reports. Other projects are known to use some generation
23146 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
23147 them with different needs, and this usage has validated Autotest as a general
23150 Nonetheless, compared to DejaGNU, Autotest is inadequate for
23151 interactive tool testing, which is probably its main limitation.
23154 * Using an Autotest Test Suite:: Autotest and the user
23155 * Writing Testsuites:: Autotest macros
23156 * testsuite Invocation:: Running @command{testsuite} scripts
23157 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
23160 @node Using an Autotest Test Suite
23161 @section Using an Autotest Test Suite
23164 * testsuite Scripts:: The concepts of Autotest
23165 * Autotest Logs:: Their contents
23168 @node testsuite Scripts
23169 @subsection @command{testsuite} Scripts
23171 @cindex @command{testsuite}
23173 Generating testing or validation suites using Autotest is rather easy.
23174 The whole validation suite is held in a file to be processed through
23175 @command{autom4te}, itself using GNU M4 under the scene, to
23176 produce a stand-alone Bourne shell script which then gets distributed.
23177 Neither @command{autom4te} nor GNU M4 are needed at
23178 the installer's end.
23181 Each test of the validation suite should be part of some test group. A
23182 @dfn{test group} is a sequence of interwoven tests that ought to be
23183 executed together, usually because one test in the group creates data
23184 files than a later test in the same group needs to read. Complex test
23185 groups make later debugging more tedious. It is much better to
23186 keep only a few tests per test group. Ideally there is only one test
23189 For all but the simplest packages, some file such as @file{testsuite.at}
23190 does not fully hold all test sources, as these are often easier to
23191 maintain in separate files. Each of these separate files holds a single
23192 test group, or a sequence of test groups all addressing some common
23193 functionality in the package. In such cases, @file{testsuite.at}
23194 merely initializes the validation suite, and sometimes does elementary
23195 health checking, before listing include statements for all other test
23196 files. The special file @file{package.m4}, containing the
23197 identification of the package, is automatically included if found.
23199 A convenient alternative consists in moving all the global issues
23200 (local Autotest macros, elementary health checking, and @code{AT_INIT}
23201 invocation) into the file @code{local.at}, and making
23202 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
23203 suites. In such case, generating the whole test suite or pieces of it
23204 is only a matter of choosing the @command{autom4te} command line
23207 The validation scripts that Autotest produces are by convention called
23208 @command{testsuite}. When run, @command{testsuite} executes each test
23209 group in turn, producing only one summary line per test to say if that
23210 particular test succeeded or failed. At end of all tests, summarizing
23211 counters get printed. One debugging directory is left for each test
23212 group which failed, if any: such directories are named
23213 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
23214 the test group, and they include:
23217 @item a debugging script named @file{run} which reruns the test in
23218 @dfn{debug mode} (@pxref{testsuite Invocation}). The automatic generation
23219 of debugging scripts has the purpose of easing the chase for bugs.
23221 @item all the files created with @code{AT_DATA}
23223 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
23225 @item a log of the run, named @file{testsuite.log}
23228 In the ideal situation, none of the tests fail, and consequently no
23229 debugging directory is left behind for validation.
23231 It often happens in practice that individual tests in the validation
23232 suite need to get information coming out of the configuration process.
23233 Some of this information, common for all validation suites, is provided
23234 through the file @file{atconfig}, automatically created by
23235 @code{AC_CONFIG_TESTDIR}. For configuration informations which your
23236 testing environment specifically needs, you might prepare an optional
23237 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
23238 The configuration process produces @file{atconfig} and @file{atlocal}
23239 out of these two input files, and these two produced files are
23240 automatically read by the @file{testsuite} script.
23242 Here is a diagram showing the relationship between files.
23245 Files used in preparing a software package for distribution:
23250 subfile-1.at ->. [local.at] ---->+
23252 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
23258 Files used in configuring a software package:
23263 [atlocal.in] --> config.status* --<
23269 Files created during the test suite execution:
23272 atconfig -->. .--> testsuite.log
23276 [atlocal] ->' `--> [testsuite.dir]
23280 @node Autotest Logs
23281 @subsection Autotest Logs
23283 When run, the test suite creates a log file named after itself, e.g., a
23284 test suite named @command{testsuite} creates @file{testsuite.log}. It
23285 contains a lot of information, usually more than maintainers actually
23286 need, but therefore most of the time it contains all that is needed:
23289 @item command line arguments
23290 @c akim s/to consist in/to consist of/
23291 A bad but unfortunately widespread habit consists of
23292 setting environment variables before the command, such as in
23293 @samp{CC=my-home-grown-cc ./testsuite}. The test suite does not
23294 know this change, hence (i) it cannot report it to you, and (ii)
23295 it cannot preserve the value of @code{CC} for subsequent runs.
23296 Autoconf faced exactly the same problem, and solved it by asking
23297 users to pass the variable definitions as command line arguments.
23298 Autotest requires this rule, too, but has no means to enforce it; the log
23299 then contains a trace of the variables that were changed by the user.
23301 @item @file{ChangeLog} excerpts
23302 The topmost lines of all the @file{ChangeLog} files found in the source
23303 hierarchy. This is especially useful when bugs are reported against
23304 development versions of the package, since the version string does not
23305 provide sufficient information to know the exact state of the sources
23306 the user compiled. Of course, this relies on the use of a
23309 @item build machine
23310 Running a test suite in a cross-compile environment is not an easy task,
23311 since it would mean having the test suite run on a machine @var{build},
23312 while running programs on a machine @var{host}. It is much simpler to
23313 run both the test suite and the programs on @var{host}, but then, from
23314 the point of view of the test suite, there remains a single environment,
23315 @var{host} = @var{build}. The log contains relevant information on the
23316 state of the build machine, including some important environment
23318 @c FIXME: How about having an M4sh macro to say `hey, log the value
23319 @c of `@dots{}'? This would help both Autoconf and Autotest.
23321 @item tested programs
23322 The absolute file name and answers to @option{--version} of the tested
23323 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
23325 @item configuration log
23326 The contents of @file{config.log}, as created by @command{configure},
23327 are appended. It contains the configuration flags and a detailed report
23328 on the configuration itself.
23332 @node Writing Testsuites
23333 @section Writing @file{testsuite.at}
23335 The @file{testsuite.at} is a Bourne shell script making use of special
23336 Autotest M4 macros. It often contains a call to @code{AT_INIT} near
23337 its beginning followed by one call to @code{m4_include} per source file
23338 for tests. Each such included file, or the remainder of
23339 @file{testsuite.at} if include files are not used, contain a sequence of
23340 test groups. Each test group begins with a call to @code{AT_SETUP},
23341 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
23342 and then completes with a call to @code{AT_CLEANUP}. Multiple test
23343 groups can be categorized by a call to @code{AT_BANNER}.
23345 All of the public Autotest macros have all-uppercase names in the
23346 namespace @samp{^AT_} to prevent them from accidentally conflicting with
23347 other text; Autoconf also reserves the namespace @samp{^_AT_} for
23348 internal macros. All shell variables used in the testsuite for internal
23349 purposes have mostly-lowercase names starting with @samp{at_}. Autotest
23350 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
23351 makes use of the file system namespace @samp{^at-}.
23353 Since Autoconf is built on top of M4sugar (@pxref{Programming in
23354 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
23355 of those namespaces (@samp{^_?\(m4\|AS\)_}). In general, you
23356 @emph{should not use} the namespace of a package that does not own the
23357 macro or shell code you are writing.
23359 @defmac AT_INIT (@ovar{name})
23361 @c FIXME: Not clear, plus duplication of the information.
23362 Initialize Autotest. Giving a @var{name} to the test suite is
23363 encouraged if your package includes several test suites. Before this
23364 macro is called, @code{AT_PACKAGE_STRING} and
23365 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
23366 information about the testsuite to the user. Typically, these macros
23367 are provided by a file @file{package.m4} built by @command{make}
23368 (@pxref{Making testsuite Scripts}), in order to inherit the package
23369 name, version, and bug reporting address from @file{configure.ac}.
23372 @defmac AT_COPYRIGHT (@var{copyright-notice})
23373 @atindex{COPYRIGHT}
23374 @cindex Copyright Notice
23375 State that, in addition to the Free Software Foundation's copyright on
23376 the Autotest macros, parts of your test suite are covered by
23377 @var{copyright-notice}.
23379 The @var{copyright-notice} shows up in both the head of
23380 @command{testsuite} and in @samp{testsuite --version}.
23383 @defmac AT_TESTED (@var{executables})
23385 Log the file name and answer to @option{--version} of each program in
23386 space-separated list @var{executables}. Several invocations register
23387 new executables, in other words, don't fear registering one program
23391 Autotest test suites rely on @env{PATH} to find the tested program.
23392 This avoids the need to generate absolute names of the various tools, and
23393 makes it possible to test installed programs. Therefore, knowing which
23394 programs are being exercised is crucial to understanding problems in
23395 the test suite itself, or its occasional misuses. It is a good idea to
23396 also subscribe foreign programs you depend upon, to avoid incompatible
23401 @defmac AT_BANNER (@var{test-category-name})
23403 This macro identifies the start of a category of related test groups.
23404 When the resulting @file{testsuite} is invoked with more than one test
23405 group to run, its output will include a banner containing
23406 @var{test-category-name} prior to any tests run from that category. The
23407 banner should be no more than about 40 or 50 characters. A blank banner
23408 will not print, effectively ending a category and letting subsequent
23409 test groups behave as though they are uncategorized when run in
23413 @defmac AT_SETUP (@var{test-group-name})
23415 This macro starts a group of related tests, all to be executed in the
23416 same subshell. It accepts a single argument, which holds a few words
23417 (no more than about 30 or 40 characters) quickly describing the purpose
23418 of the test group being started. @var{test-group-name} must not expand
23419 to unbalanced quotes, although quadrigraphs can be used.
23422 @defmac AT_KEYWORDS (@var{keywords})
23424 Associate the space-separated list of @var{keywords} to the enclosing
23425 test group. This makes it possible to run ``slices'' of the test suite.
23426 For instance, if some of your test groups exercise some @samp{foo}
23427 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
23428 @samp{./testsuite -k foo} to run exclusively these test groups. The
23429 @var{title} of the test group is automatically recorded to
23430 @code{AT_KEYWORDS}.
23432 Several invocations within a test group accumulate new keywords. In
23433 other words, don't fear registering the same keyword several times in a
23437 @defmac AT_CAPTURE_FILE (@var{file})
23438 @atindex{CAPTURE_FILE}
23439 If the current test group fails, log the contents of @var{file}.
23440 Several identical calls within one test group have no additional effect.
23443 @defmac AT_FAIL_IF (@var{shell-condition})
23445 Make the test group fail and skip the rest of its execution, if
23446 @var{shell-condition} is true. @var{shell-condition} is a shell expression
23447 such as a @code{test} command. Tests before @command{AT_FAIL_IF}
23448 will be executed and may still cause the test group to be skipped.
23449 You can instantiate this macro many times from within the same test group.
23451 You should use this macro only for very simple failure conditions. If the
23452 @var{shell-condition} could emit any kind of output you should instead
23453 use @command{AT_CHECK} like
23455 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
23458 so that such output is properly recorded in the @file{testsuite.log}
23462 @defmac AT_SKIP_IF (@var{shell-condition})
23464 Determine whether the test should be skipped because it requires
23465 features that are unsupported on the machine under test.
23466 @var{shell-condition} is a shell expression such as a @code{test}
23467 command. Tests before @command{AT_SKIP_IF} will be executed
23468 and may still cause the test group to fail. You can instantiate this
23469 macro many times from within the same test group.
23471 You should use this macro only for very simple skip conditions. If the
23472 @var{shell-condition} could emit any kind of output you should instead
23473 use @command{AT_CHECK} like
23475 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
23478 so that such output is properly recorded in the @file{testsuite.log}
23482 @defmac AT_XFAIL_IF (@var{shell-condition})
23484 Determine whether the test is expected to fail because it is a known
23485 bug (for unsupported features, you should skip the test).
23486 @var{shell-condition} is a shell expression such as a @code{test}
23487 command; you can instantiate this macro many times from within the
23488 same test group, and one of the conditions is enough to turn
23489 the test into an expected failure.
23494 End the current test group.
23499 @defmac AT_DATA (@var{file}, @var{contents})
23501 Initialize an input data @var{file} with given @var{contents}. Of
23502 course, the @var{contents} have to be properly quoted between square
23503 brackets to protect against included commas or spurious M4
23504 expansion. The contents must end with an end of line. @var{file} must
23505 be a single shell word that expands into a single file name.
23508 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
23509 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
23510 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
23511 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
23513 @atindex{CHECK_UNQUOTED}
23514 Execute a test by performing given shell @var{commands}. @var{commands}
23515 is output as-is, so shell expansions are honored. These commands
23516 should normally exit with @var{status}, while producing expected
23517 @var{stdout} and @var{stderr} contents. If @var{commands} exit with
23518 unexpected status 77, then the rest of the test group is skipped. If
23519 @var{commands} exit with unexpected status 99, then the test group is
23520 immediately failed. Otherwise, if this test
23521 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
23522 commands @var{run-if-pass}.
23524 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
23526 If @var{status} is the literal @samp{ignore}, then the corresponding
23527 exit status is not checked, except for the special cases of 77 (skip)
23528 and 99 (hard failure). The existence of hard failures allows one to
23529 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
23530 feature has not yet been implemented, but to still distinguish between
23531 gracefully handling the missing feature and dumping core. A hard
23532 failure also inhibits post-test actions in @var{run-if-fail}.
23534 If the value of the @var{stdout} or @var{stderr} parameter is one of the
23535 literals in the following table, then the test treats the output
23536 according to the rules of that literal. Otherwise, the value of the
23537 parameter is treated as text that must exactly match the output given by
23538 @var{commands} on standard out and standard error (including an empty
23539 parameter for no output); any differences are captured in the testsuite
23540 log and the test is failed (unless an unexpected exit status of 77
23541 skipped the test instead). The difference between @code{AT_CHECK} and
23542 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
23543 expansion (@samp{$}), command substitution (@samp{`}), and backslash
23544 escaping (@samp{\}) on comparison text given in the @var{stdout} and
23545 @var{stderr} arguments; if the text includes a trailing newline, this
23546 would be the same as if it were specified via an unquoted
23547 here-document. (However, there is no difference in the interpretation
23548 of @var{commands}).
23552 The content of the output is ignored, but still captured in the test
23553 group log (if the testsuite is run with option @option{-v}, the test
23554 group log is displayed as the test is run; if the test group later
23555 fails, the test group log is also copied into the overall testsuite
23556 log). This action is valid for both @var{stdout} and @var{stderr}.
23559 The content of the output is ignored, and nothing is captured in the log
23560 files. If @var{commands} are likely to produce binary output (including
23561 long lines) or large amounts of output, then logging the output can make
23562 it harder to locate details related to subsequent tests within the
23563 group, and could potentially corrupt terminal display of a user running
23564 @command{testsuite -v}.
23567 For the @var{stdout} parameter, capture the content of standard output
23568 to both the file @file{stdout} and the test group log. Subsequent
23569 commands in the test group can then post-process the file. This action
23570 is often used when it is desired to use @command{grep} to look for a
23571 substring in the output, or when the output must be post-processed to
23572 normalize error messages into a common form.
23575 Like @samp{stdout}, except that it only works for the @var{stderr}
23576 parameter, and the standard error capture file will be named
23580 @itemx stderr-nolog
23581 Like @samp{stdout} or @samp{stderr}, except that the captured output is
23582 not duplicated into the test group log. This action is particularly
23583 useful for an intermediate check that produces large amounts of data,
23584 which will be followed by another check that filters down to the
23585 relevant data, as it makes it easier to locate details in the log.
23588 For the @var{stdout} parameter, compare standard output contents with
23589 the previously created file @file{expout}, and list any differences in
23593 Like @samp{expout}, except that it only works for the @var{stderr}
23594 parameter, and the standard error contents are compared with
23599 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
23600 @ovar{run-if-fail}, @ovar{run-if-pass})
23601 @atindex{CHECK_EUNIT}
23602 Initialize and execute an Erlang module named @var{module} that performs
23603 tests following the @var{test-spec} EUnit test specification.
23604 @var{test-spec} must be a valid EUnit test specification, as defined in
23605 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
23606 Reference Manual}. @var{erlflags} are optional command-line options
23607 passed to the Erlang interpreter to execute the test Erlang module.
23608 Typically, @var{erlflags} defines at least the paths to directories
23609 containing the compiled Erlang modules under test, as @samp{-pa path1
23612 For example, the unit tests associated with Erlang module @samp{testme},
23613 which compiled code is in subdirectory @file{src}, can be performed
23617 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
23618 [-pa "$@{abs_top_builddir@}/src"])
23621 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
23623 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
23624 must be defined as the path of the Erlang interpreter, the path of the
23625 Erlang compiler, and the command-line flags to pass to the compiler,
23626 respectively. Those variables should be configured in
23627 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
23628 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
23629 variables are automatically defined in the testsuite. If @code{ERL} or
23630 @code{ERLC} is not defined, the test group is skipped.
23632 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
23633 be loaded, the test group is skipped. Otherwise, if @var{test-spec} is
23634 an invalid EUnit test specification, the test group fails. Otherwise,
23635 if the EUnit test passes, shell commands @var{run-if-pass} are executed
23636 or, if the EUnit test fails, shell commands @var{run-if-fail} are
23637 executed and the test group fails.
23639 Only the generated test Erlang module is automatically compiled and
23640 executed. If @var{test-spec} involves testing other Erlang modules,
23641 e.g. module @samp{testme} in the example above, those modules must be
23644 If the testsuite is run in verbose mode, with option @option{--verbose},
23645 EUnit is also run in verbose mode to output more details about
23646 individual unit tests.
23650 @node testsuite Invocation
23651 @section Running @command{testsuite} Scripts
23652 @cindex @command{testsuite}
23654 Autotest test suites support the following arguments:
23659 Display the list of options and exit successfully.
23663 Display the version of the test suite and exit successfully.
23665 @item --directory=@var{dir}
23666 @itemx -C @var{dir}
23667 Change the current directory to @var{dir} before creating any files.
23668 Useful for running the testsuite in a subdirectory from a top-level
23671 @item --jobs@r{[}=@var{n}@r{]}
23673 Run @var{n} tests in parallel, if possible. If @var{n} is not given,
23674 run all given tests in parallel. Note that there should be no space
23675 before the argument to @option{-j}, as @option{-j @var{number}} denotes
23676 the separate arguments @option{-j} and @option{@var{number}}, see below.
23678 In parallel mode, the standard input device of the testsuite script is
23679 not available to commands inside a test group. Furthermore, banner
23680 lines are not printed, and the summary line for each test group is
23681 output after the test group completes. Summary lines may appear
23682 unordered. If verbose and trace output are enabled (see below), they
23683 may appear intermixed from concurrently running tests.
23685 Parallel mode requires the @command{mkfifo} command to work, and will be
23686 silently disabled otherwise.
23690 Remove all the files the test suite might have created and exit. Meant
23691 for @code{clean} Make targets.
23695 List all the tests (or only the selection), including their possible
23701 By default all tests are performed (or described with
23702 @option{--list}) in the default environment first silently, then
23703 verbosely, but the environment, set of tests, and verbosity level can be
23707 @item @var{variable}=@var{value}
23708 Set the environment @var{variable} to @var{value}. Use this rather
23709 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
23710 different environment.
23712 @cindex @code{AUTOTEST_PATH}
23713 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
23714 to @env{PATH}. Relative directory names (not starting with
23715 @samp{/}) are considered to be relative to the top level of the
23716 package being built. All directories are made absolute, first
23717 starting from the top level @emph{build} tree, then from the
23718 @emph{source} tree. For instance @samp{./testsuite
23719 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
23720 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
23721 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
23725 @itemx @var{number}-@var{number}
23726 @itemx @var{number}-
23727 @itemx -@var{number}
23728 Add the corresponding test groups, with obvious semantics, to the
23731 @item --keywords=@var{keywords}
23732 @itemx -k @var{keywords}
23733 Add to the selection the test groups with title or keywords (arguments
23734 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
23735 of the comma separated list @var{keywords}, case-insensitively. Use
23736 @samp{!} immediately before the keyword to invert the selection for this
23737 keyword. By default, the keywords match whole words; enclose them in
23738 @samp{.*} to also match parts of words.
23740 For example, running
23743 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
23747 selects all tests tagged @samp{autoupdate} @emph{and} with tags
23748 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
23752 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
23756 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
23757 containing @samp{FUNC}.
23761 If any test fails, immediately abort testing. It implies
23762 @option{--debug}: post test group clean up, and top-level logging
23763 are inhibited. This option is meant for the full test
23764 suite, it is not really useful for generated debugging scripts.
23765 If the testsuite is run in parallel mode using @option{--jobs},
23766 then concurrently running tests will finish before exiting.
23770 Force more verbosity in the detailed output of what is being done. This
23771 is the default for debugging scripts.
23775 Do not remove the files after a test group was performed ---but they are
23776 still removed @emph{before}, therefore using this option is sane when
23777 running several test groups. Create debugging scripts. Do not
23778 overwrite the top-level
23779 log (in order to preserve supposedly existing full log file). This is
23780 the default for debugging scripts, but it can also be useful to debug
23781 the testsuite itself.
23785 Trigger shell tracing of the test groups.
23789 @node Making testsuite Scripts
23790 @section Making @command{testsuite} Scripts
23792 For putting Autotest into movement, you need some configuration and
23793 makefile machinery. We recommend, at least if your package uses deep or
23794 shallow hierarchies, that you use @file{tests/} as the name of the
23795 directory holding all your tests and their makefile. Here is a
23796 check list of things to do.
23801 @cindex @file{package.m4}
23802 @atindex{PACKAGE_STRING}
23803 @atindex{PACKAGE_BUGREPORT}
23804 @atindex{PACKAGE_NAME}
23805 @atindex{PACKAGE_TARNAME}
23806 @atindex{PACKAGE_VERSION}
23807 @atindex{PACKAGE_URL}
23808 Make sure to create the file @file{package.m4}, which defines the
23809 identity of the package. It must define @code{AT_PACKAGE_STRING}, the
23810 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
23811 address to which bug reports should be sent. For sake of completeness,
23812 we suggest that you also define @code{AT_PACKAGE_NAME},
23813 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
23814 @code{AT_PACKAGE_URL}.
23815 @xref{Initializing configure}, for a description of these variables.
23816 Be sure to distribute @file{package.m4} and to put it into the source
23817 hierarchy: the test suite ought to be shipped! See below for an example
23818 @file{Makefile} excerpt.
23821 Invoke @code{AC_CONFIG_TESTDIR}.
23823 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
23824 @acindex{CONFIG_TESTDIR}
23825 An Autotest test suite is to be configured in @var{directory}. This
23826 macro requires the instantiation of @file{@var{directory}/atconfig} from
23827 @file{@var{directory}/atconfig.in}, and sets the default
23828 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
23832 Still within @file{configure.ac}, as appropriate, ensure that some
23833 @code{AC_CONFIG_FILES} command includes substitution for
23834 @file{tests/atlocal}.
23837 The appropriate @file{Makefile} should be modified so the validation in
23838 your package is triggered by @samp{make check}. An example is provided
23842 With Automake, here is a minimal example for inclusion in
23843 @file{tests/Makefile.am}, in order to link @samp{make check} with a
23847 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
23848 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
23850 echo '# Signature of the current package.' && \
23851 echo 'm4_define([AT_PACKAGE_NAME],' && \
23852 echo ' [$(PACKAGE_NAME)])' && \
23853 echo 'm4_define([AT_PACKAGE_TARNAME],' && \
23854 echo ' [$(PACKAGE_TARNAME)])' && \
23855 echo 'm4_define([AT_PACKAGE_VERSION],' && \
23856 echo ' [$(PACKAGE_VERSION)])' && \
23857 echo 'm4_define([AT_PACKAGE_STRING],' && \
23858 echo ' [$(PACKAGE_STRING)])' && \
23859 echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
23860 echo ' [$(PACKAGE_BUGREPORT)])'; \
23861 echo 'm4_define([AT_PACKAGE_URL],' && \
23862 echo ' [$(PACKAGE_URL)])'; \
23863 @} >'$(srcdir)/package.m4'
23865 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
23866 TESTSUITE = $(srcdir)/testsuite
23868 check-local: atconfig atlocal $(TESTSUITE)
23869 $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
23871 installcheck-local: atconfig atlocal $(TESTSUITE)
23872 $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
23876 test ! -f '$(TESTSUITE)' || \
23877 $(SHELL) '$(TESTSUITE)' --clean
23879 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
23880 AUTOTEST = $(AUTOM4TE) --language=autotest
23881 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
23882 $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
23886 Note that the built testsuite is distributed; this is necessary because
23887 users might not have Autoconf installed, and thus would not be able to
23888 rebuild it. Likewise, the use of @file{missing} provides the user with
23889 a nicer error message if they modify a source file to the testsuite, and
23890 accidentally trigger the rebuild rules.
23892 You might want to list explicitly the dependencies, i.e., the list of
23893 the files @file{testsuite.at} includes.
23895 If you don't use Automake, you should include the above example in
23896 @file{tests/@/Makefile.in}, along with additional lines inspired from
23901 PACKAGE_NAME = @@PACKAGE_NAME@@
23902 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
23903 PACKAGE_VERSION = @@PACKAGE_VERSION@@
23904 PACKAGE_STRING = @@PACKAGE_STRING@@
23905 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
23906 PACKAGE_URL = @@PACKAGE_URL@@
23908 atconfig: $(top_builddir)/config.status
23909 cd $(top_builddir) && \
23910 $(SHELL) ./config.status $(subdir)/$@@
23912 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
23913 cd $(top_builddir) && \
23914 $(SHELL) ./config.status $(subdir)/$@@
23918 and manage to have @code{$(EXTRA_DIST)} distributed. You will also want
23919 to distribute the file @file{build-aux/@/missing} from the Automake
23920 project; a copy of this file resides in the Autoconf source.
23922 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
23923 within your makefile, you can fine-tune test suite execution with this
23924 variable, for example:
23927 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
23932 @c =============================== Frequent Autoconf Questions, with answers
23935 @chapter Frequent Autoconf Questions, with answers
23937 Several questions about Autoconf come up occasionally. Here some of them
23941 * Distributing:: Distributing @command{configure} scripts
23942 * Why GNU M4:: Why not use the standard M4?
23943 * Bootstrapping:: Autoconf and GNU M4 require each other?
23944 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
23945 * Defining Directories:: Passing @code{datadir} to program
23946 * Autom4te Cache:: What is it? Can I remove it?
23947 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
23948 * Expanded Before Required:: Expanded Before Required
23949 * Debugging:: Debugging @command{configure} scripts
23953 @section Distributing @command{configure} Scripts
23957 What are the restrictions on distributing @command{configure}
23958 scripts that Autoconf generates? How does that affect my
23959 programs that use them?
23962 There are no restrictions on how the configuration scripts that Autoconf
23963 produces may be distributed or used. In Autoconf version 1, they were
23964 covered by the GNU General Public License. We still encourage
23965 software authors to distribute their work under terms like those of the
23966 GPL, but doing so is not required to use Autoconf.
23968 Of the other files that might be used with @command{configure},
23969 @file{config.h.in} is under whatever copyright you use for your
23970 @file{configure.ac}. @file{config.sub} and @file{config.guess} have an
23971 exception to the GPL when they are used with an Autoconf-generated
23972 @command{configure} script, which permits you to distribute them under the
23973 same terms as the rest of your package. @file{install-sh} is from the X
23974 Consortium and is not copyrighted.
23977 @section Why Require GNU M4?
23980 Why does Autoconf require GNU M4?
23983 Many M4 implementations have hard-coded limitations on the size and
23984 number of macros that Autoconf exceeds. They also lack several
23985 builtin macros that it would be difficult to get along without in a
23986 sophisticated application like Autoconf, including:
23996 Autoconf requires version 1.4.6 or later of GNU M4.
23998 Since only software maintainers need to use Autoconf, and since GNU
23999 M4 is simple to configure and install, it seems reasonable to require
24000 GNU M4 to be installed also. Many maintainers of GNU and
24001 other free software already have most of the GNU utilities
24002 installed, since they prefer them.
24004 @node Bootstrapping
24005 @section How Can I Bootstrap?
24009 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
24010 @command{configure} script, how do I bootstrap? It seems like a chicken
24014 This is a misunderstanding. Although GNU M4 does come with a
24015 @command{configure} script produced by Autoconf, Autoconf is not required
24016 in order to run the script and install GNU M4. Autoconf is only
24017 required if you want to change the M4 @command{configure} script, which few
24018 people have to do (mainly its maintainer).
24020 @node Why Not Imake
24021 @section Why Not Imake?
24025 Why not use Imake instead of @command{configure} scripts?
24028 Several people have written addressing this question, so I include
24029 adaptations of their explanations here.
24031 The following answer is based on one written by Richard Pixley:
24034 Autoconf generated scripts frequently work on machines that it has
24035 never been set up to handle before. That is, it does a good job of
24036 inferring a configuration for a new system. Imake cannot do this.
24038 Imake uses a common database of host specific data. For X11, this makes
24039 sense because the distribution is made as a collection of tools, by one
24040 central authority who has control over the database.
24042 GNU tools are not released this way. Each GNU tool has a
24043 maintainer; these maintainers are scattered across the world. Using a
24044 common database would be a maintenance nightmare. Autoconf may appear
24045 to be this kind of database, but in fact it is not. Instead of listing
24046 host dependencies, it lists program requirements.
24048 If you view the GNU suite as a collection of native tools, then the
24049 problems are similar. But the GNU development tools can be
24050 configured as cross tools in almost any host+target permutation. All of
24051 these configurations can be installed concurrently. They can even be
24052 configured to share host independent files across hosts. Imake doesn't
24053 address these issues.
24055 Imake templates are a form of standardization. The GNU coding
24056 standards address the same issues without necessarily imposing the same
24061 Here is some further explanation, written by Per Bothner:
24064 One of the advantages of Imake is that it easy to generate large
24065 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
24066 However, @code{cpp} is not programmable: it has limited conditional
24067 facilities, and no looping. And @code{cpp} cannot inspect its
24070 All of these problems are solved by using @code{sh} instead of
24071 @code{cpp}. The shell is fully programmable, has macro substitution,
24072 can execute (or source) other shell scripts, and can inspect its
24077 Paul Eggert elaborates more:
24080 With Autoconf, installers need not assume that Imake itself is already
24081 installed and working well. This may not seem like much of an advantage
24082 to people who are accustomed to Imake. But on many hosts Imake is not
24083 installed or the default installation is not working well, and requiring
24084 Imake to install a package hinders the acceptance of that package on
24085 those hosts. For example, the Imake template and configuration files
24086 might not be installed properly on a host, or the Imake build procedure
24087 might wrongly assume that all source files are in one big directory
24088 tree, or the Imake configuration might assume one compiler whereas the
24089 package or the installer needs to use another, or there might be a
24090 version mismatch between the Imake expected by the package and the Imake
24091 supported by the host. These problems are much rarer with Autoconf,
24092 where each package comes with its own independent configuration
24095 Also, Imake often suffers from unexpected interactions between
24096 @command{make} and the installer's C preprocessor. The fundamental problem
24097 here is that the C preprocessor was designed to preprocess C programs,
24098 not makefiles. This is much less of a problem with Autoconf,
24099 which uses the general-purpose preprocessor M4, and where the
24100 package's author (rather than the installer) does the preprocessing in a
24105 Finally, Mark Eichin notes:
24108 Imake isn't all that extensible, either. In order to add new features to
24109 Imake, you need to provide your own project template, and duplicate most
24110 of the features of the existing one. This means that for a sophisticated
24111 project, using the vendor-provided Imake templates fails to provide any
24112 leverage---since they don't cover anything that your own project needs
24113 (unless it is an X11 program).
24115 On the other side, though:
24117 The one advantage that Imake has over @command{configure}:
24118 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
24119 than @file{Makefile.in} files. There is a fix to this, however---at least
24120 for the Kerberos V5 tree, we've modified things to call in common
24121 @file{post.in} and @file{pre.in} makefile fragments for the
24122 entire tree. This means that a lot of common things don't have to be
24123 duplicated, even though they normally are in @command{configure} setups.
24127 @node Defining Directories
24128 @section How Do I @code{#define} Installation Directories?
24131 My program needs library files, installed in @code{datadir} and
24135 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
24136 [Define to the read-only architecture-independent
24144 #define DATADIR "$@{prefix@}/share"
24148 As already explained, this behavior is on purpose, mandated by the
24149 GNU Coding Standards, see @ref{Installation Directory
24150 Variables}. There are several means to achieve a similar goal:
24154 Do not use @code{AC_DEFINE} but use your makefile to pass the
24155 actual value of @code{datadir} via compilation flags.
24156 @xref{Installation Directory Variables}, for the details.
24159 This solution can be simplified when compiling a program: you may either
24160 extend the @code{CPPFLAGS}:
24163 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
24167 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
24170 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
24174 Alternatively, create a dedicated header file:
24177 DISTCLEANFILES = myprog-paths.h
24178 myprog-paths.h: Makefile
24179 echo '#define DATADIR "$(datadir)"' >$@@
24183 Use @code{AC_DEFINE} but have @command{configure} compute the literal
24184 value of @code{datadir} and others. Many people have wrapped macros to
24185 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
24186 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
24189 This solution does not conform to the GNU Coding Standards.
24192 Note that all the previous solutions hard wire the absolute name of
24193 these directories in the executables, which is not a good property. You
24194 may try to compute the names relative to @code{prefix}, and try to
24195 find @code{prefix} at runtime, this way your package is relocatable.
24199 @node Autom4te Cache
24200 @section What is @file{autom4te.cache}?
24203 What is this directory @file{autom4te.cache}? Can I safely remove it?
24206 In the GNU Build System, @file{configure.ac} plays a central
24207 role and is read by many tools: @command{autoconf} to create
24208 @file{configure}, @command{autoheader} to create @file{config.h.in},
24209 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
24210 check the completeness of @file{configure.ac}, @command{autoreconf} to
24211 check the GNU Build System components that are used. To
24212 ``read @file{configure.ac}'' actually means to compile it with M4,
24213 which can be a long process for complex @file{configure.ac}.
24215 This is why all these tools, instead of running directly M4, invoke
24216 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
24217 a specific demand, stores additional information in
24218 @file{autom4te.cache} for future runs. For instance, if you run
24219 @command{autoconf}, behind the scenes, @command{autom4te} also
24220 stores information for the other tools, so that when you invoke
24221 @command{autoheader} or @command{automake} etc., reprocessing
24222 @file{configure.ac} is not needed. The speed up is frequently 30%,
24223 and is increasing with the size of @file{configure.ac}.
24225 But it is and remains being simply a cache: you can safely remove it.
24230 Can I permanently get rid of it?
24233 The creation of this cache can be disabled from
24234 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
24235 details. You should be aware that disabling the cache slows down the
24236 Autoconf test suite by 40%. The more GNU Build System
24237 components are used, the more the cache is useful; for instance
24238 running @samp{autoreconf -f} on the Core Utilities is twice slower without
24239 the cache @emph{although @option{--force} implies that the cache is
24240 not fully exploited}, and eight times slower than without
24244 @node Present But Cannot Be Compiled
24245 @section Header Present But Cannot Be Compiled
24247 The most important guideline to bear in mind when checking for
24248 features is to mimic as much as possible the intended use.
24249 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
24250 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
24251 the preprocessor, instead of the compiler, to check for headers. As a
24252 result, incompatibilities between headers went unnoticed during
24253 configuration, and maintainers finally had to deal with this issue
24256 The transition began with Autoconf 2.56. As of Autoconf 2.64 both
24257 checks are performed, and @command{configure} complains loudly if the
24258 compiler and the preprocessor do not agree. However, only the compiler
24259 result is considered.
24261 Consider the following example:
24264 $ @kbd{cat number.h}
24265 typedef int number;
24267 const number pi = 3;
24268 $ @kbd{cat configure.ac}
24269 AC_INIT([Example], [1.0], [bug-example@@example.org])
24270 AC_CHECK_HEADERS([pi.h])
24271 $ @kbd{autoconf -Wall}
24272 $ @kbd{./configure}
24273 checking for gcc... gcc
24274 checking for C compiler default output file name... a.out
24275 checking whether the C compiler works... yes
24276 checking whether we are cross compiling... no
24277 checking for suffix of executables...
24278 checking for suffix of object files... o
24279 checking whether we are using the GNU C compiler... yes
24280 checking whether gcc accepts -g... yes
24281 checking for gcc option to accept ISO C89... none needed
24282 checking how to run the C preprocessor... gcc -E
24283 checking for grep that handles long lines and -e... grep
24284 checking for egrep... grep -E
24285 checking for ANSI C header files... yes
24286 checking for sys/types.h... yes
24287 checking for sys/stat.h... yes
24288 checking for stdlib.h... yes
24289 checking for string.h... yes
24290 checking for memory.h... yes
24291 checking for strings.h... yes
24292 checking for inttypes.h... yes
24293 checking for stdint.h... yes
24294 checking for unistd.h... yes
24295 checking pi.h usability... no
24296 checking pi.h presence... yes
24297 configure: WARNING: pi.h: present but cannot be compiled
24298 configure: WARNING: pi.h: check for missing prerequisite headers?
24299 configure: WARNING: pi.h: see the Autoconf documentation
24300 configure: WARNING: pi.h: section "Present But Cannot Be Compiled"
24301 configure: WARNING: pi.h: proceeding with the compiler's result
24302 configure: WARNING: ## -------------------------------------- ##
24303 configure: WARNING: ## Report this to bug-example@@example.org ##
24304 configure: WARNING: ## -------------------------------------- ##
24305 checking for pi.h... yes
24309 The proper way the handle this case is using the fourth argument
24310 (@pxref{Generic Headers}):
24313 $ @kbd{cat configure.ac}
24314 AC_INIT([Example], [1.0], [bug-example@@example.org])
24315 AC_CHECK_HEADERS([number.h pi.h], [], [],
24316 [[#ifdef HAVE_NUMBER_H
24317 # include <number.h>
24320 $ @kbd{autoconf -Wall}
24321 $ @kbd{./configure}
24322 checking for gcc... gcc
24323 checking for C compiler default output... a.out
24324 checking whether the C compiler works... yes
24325 checking whether we are cross compiling... no
24326 checking for suffix of executables...
24327 checking for suffix of object files... o
24328 checking whether we are using the GNU C compiler... yes
24329 checking whether gcc accepts -g... yes
24330 checking for gcc option to accept ANSI C... none needed
24331 checking for number.h... yes
24332 checking for pi.h... yes
24335 See @ref{Particular Headers}, for a list of headers with their
24338 @node Expanded Before Required
24339 @section Expanded Before Required
24341 @cindex expanded before required
24342 Older versions of Autoconf silently built files with incorrect ordering
24343 between dependent macros if an outer macro first expanded, then later
24344 indirectly required, an inner macro. Starting with Autoconf 2.64, this
24345 situation no longer generates out-of-order code, but results in
24346 duplicate output and a syntax warning:
24349 $ @kbd{cat configure.ac}
24350 @result{}AC_DEFUN([TESTA], [[echo in A
24351 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
24352 @result{}SEEN_A=:]])
24353 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
24354 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
24355 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
24356 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
24363 @result{}configure.ac:11: warning: AC_REQUIRE:
24364 @result{} `TESTA' was expanded before it was required
24365 @result{}configure.ac:4: TESTB is expanded from...
24366 @result{}configure.ac:6: TESTC is expanded from...
24367 @result{}configure.ac:7: OUTER is expanded from...
24368 @result{}configure.ac:11: the top level
24372 To avoid this warning, decide what purpose the macro in question serves.
24373 If it only needs to be expanded once (for example, if it provides
24374 initialization text used by later macros), then the simplest fix is to
24375 change the macro to be declared with @code{AC_DEFUN_ONCE}
24376 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
24377 newer. A more portable fix is to change all
24378 instances of direct calls to instead go through @code{AC_REQUIRE}
24379 (@pxref{Prerequisite Macros}). If, instead, the macro is parameterized
24380 by arguments or by the current definition of other macros in the m4
24381 environment, then the macro should always be directly expanded instead
24384 For another case study, consider this example trimmed down from an
24385 actual package. Originally, the package contained shell code and
24386 multiple macro invocations at the top level of @file{configure.ac}:
24389 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24396 but that was getting complex, so the author wanted to offload some of
24397 the text into a new macro in another file included via
24398 @file{aclocal.m4}. The na@"ive approach merely wraps the text in a new
24402 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24412 With older versions of Autoconf, the setting of @samp{foobar=} occurs
24413 before the single compiler check, as the author intended. But with
24414 Autoconf 2.64, this issues the ``expanded before it was required''
24415 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
24416 check, one before @samp{foobar=}, and one after. To understand why this
24417 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
24418 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood. According to
24419 the documented semantics of @code{AC_REQUIRE}, this means that
24420 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
24421 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
24422 use of @samp{foobar=}. The older versions of Autoconf were broken with
24423 regards to the rules of @code{AC_REQUIRE}, which explains why the code
24424 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
24425 autoconf. In other words, the author was unknowingly relying on a bug
24426 exploit to get the desired results, and that exploit broke once the bug
24429 So, what recourse does the author have, to restore their intended
24430 semantics of setting @samp{foobar=} prior to a single compiler check,
24431 regardless of whether Autoconf 2.63 or 2.64 is used? One idea is to
24432 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
24433 there is always the possibility of using the lower-level
24437 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24447 This works great if everything is in the same file. However, it does
24448 not help in the case where the author wants to have @command{aclocal}
24449 find the definition of @code{BAR} from its own file, since
24450 @command{aclocal} requires the use of @code{AC_DEFUN}. In this case, a
24451 better fix is to recognize that if @code{BAR} also uses
24452 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
24453 to a subsequent require. Then, by creating yet another helper macro,
24454 the author can once again guarantee a single invocation of
24455 @code{AC_PROG_CC}, which will still occur after @code{foobar=}. The
24456 author can also use @code{AC_BEFORE} to make sure no other macro
24457 appearing before @code{BAR} has triggered an unwanted expansion of
24461 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24462 AC_DEFUN([BEFORE_CC], [
24466 AC_BEFORE([$0], [AC_PROG_CC])dnl
24467 AC_REQUIRE([BEFORE_CC])dnl
24468 AC_REQUIRE([AC_PROG_CC])dnl
24476 @section Debugging @command{configure} scripts
24478 While in general, @command{configure} scripts generated by Autoconf
24479 strive to be fairly portable to various systems, compilers, shells, and
24480 other tools, it may still be necessary to debug a failing test, broken
24481 script or makefile, or fix or override an incomplete, faulty, or erroneous
24482 test, especially during macro development. Failures can occur at all levels,
24483 in M4 syntax or semantics, shell script issues, or due to bugs in the
24484 test or the tools invoked by @command{configure}. Together with the
24485 rather arcane error message that @command{m4} and @command{make} may
24486 produce when their input contains syntax errors, this can make debugging
24489 Nevertheless, here is a list of hints and strategies that may help:
24493 When @command{autoconf} fails, common causes for error include:
24497 mismatched or unbalanced parentheses or braces (@pxref{Balancing
24500 @item under- or overquoted macro arguments (@pxref{Autoconf
24501 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
24504 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
24508 Typically, it helps to go back to the last working version of the input
24509 and compare the differences for each of these errors. Another
24510 possibility is to sprinkle pairs of @code{m4_traceon} and
24511 @code{m4_traceoff} judiciously in the code, either without a parameter
24512 or listing some macro names and watch @command{m4} expand its input
24513 verbosely (@pxref{Debugging via autom4te}).
24516 Sometimes @command{autoconf} succeeds but the generated
24517 @command{configure} script has invalid shell syntax. You can detect this
24518 case by running @samp{bash -n configure} or @samp{sh -n configure}.
24519 If this command fails, the same tips apply, as if @command{autoconf} had
24523 Debugging @command{configure} script execution may be done by sprinkling
24524 pairs of @code{set -x} and @code{set +x} into the shell script before
24525 and after the region that contains a bug. Running the whole script with
24526 @samp{@var{shell} ./configure -vx 2>&1 | tee @var{log-file}} with a decent
24527 @var{shell} may work, but produces lots of output. Here, it can help to
24528 search for markers like @samp{checking for} a particular test in the
24532 When @command{configure} tests produce invalid results for your system,
24533 it may be necessary to override them:
24537 For programs, tools or libraries variables, preprocessor, compiler, or
24538 linker flags, it is often sufficient to override them at @command{make}
24539 run time with some care (@pxref{Macros and Submakes}). Since this
24540 normally won't cause @command{configure} to be run again with these
24541 changed settings, it may fail if the changed variable would have caused
24542 different test results from @command{configure}, so this may work only
24543 for simple differences.
24546 Most tests which produce their result in a substituted variable allow to
24547 override the test by setting the variable on the @command{configure}
24548 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
24549 @pxref{Particular Systems}).
24552 Many tests store their result in a cache variable (@pxref{Caching
24553 Results}). This lets you override them either on the
24554 @command{configure} command line as above, or through a primed cache or
24555 site file (@pxref{Cache Files}, @pxref{Site Defaults}). The name of a
24556 cache variable is documented with a test macro or may be inferred from
24557 @ref{Cache Variable Names}; the precise semantics of undocumented
24558 variables are often internal details, subject to change.
24562 Alternatively, @command{configure} may produce invalid results because
24563 of uncaught programming errors, in your package or in an upstream
24564 library package. For example, when @code{AC_CHECK_LIB} fails to find a
24565 library with a specified function, always check @file{config.log}. This
24566 will reveal the exact error that produced the failing result: the
24567 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
24570 Conversely, as macro author, you can make it easier for users of your
24575 by minimizing dependencies between tests and between test results as far
24579 by using @command{make} variables to factorize and allow
24580 override of settings at @command{make} run time,
24583 by honoring the GNU Coding Standards and not overriding flags
24584 reserved for the user except temporarily during @command{configure}
24588 by not requiring users of your macro to use the cache variables.
24589 Instead, expose the result of the test via @var{run-if-true} and
24590 @var{run-if-false} parameters. If the result is not a boolean,
24591 then provide it through documented shell variables.
24595 @c ===================================================== History of Autoconf.
24598 @chapter History of Autoconf
24599 @cindex History of autoconf
24601 You may be wondering, Why was Autoconf originally written? How did it
24602 get into its present form? (Why does it look like gorilla spit?) If
24603 you're not wondering, then this chapter contains no information useful
24604 to you, and you might as well skip it. If you @emph{are} wondering,
24605 then let there be light@enddots{}
24608 * Genesis:: Prehistory and naming of @command{configure}
24609 * Exodus:: The plagues of M4 and Perl
24610 * Leviticus:: The priestly code of portability arrives
24611 * Numbers:: Growth and contributors
24612 * Deuteronomy:: Approaching the promises of easy configuration
24618 In June 1991 I was maintaining many of the GNU utilities for the
24619 Free Software Foundation. As they were ported to more platforms and
24620 more programs were added, the number of @option{-D} options that users
24621 had to select in the makefile (around 20) became burdensome.
24622 Especially for me---I had to test each new release on a bunch of
24623 different systems. So I wrote a little shell script to guess some of
24624 the correct settings for the fileutils package, and released it as part
24625 of fileutils 2.0. That @command{configure} script worked well enough that
24626 the next month I adapted it (by hand) to create similar @command{configure}
24627 scripts for several other GNU utilities packages. Brian Berliner
24628 also adapted one of my scripts for his CVS revision control system.
24630 Later that summer, I learned that Richard Stallman and Richard Pixley
24631 were developing similar scripts to use in the GNU compiler tools;
24632 so I adapted my @command{configure} scripts to support their evolving
24633 interface: using the file name @file{Makefile.in} as the templates;
24634 adding @samp{+srcdir}, the first option (of many); and creating
24635 @file{config.status} files.
24640 As I got feedback from users, I incorporated many improvements, using
24641 Emacs to search and replace, cut and paste, similar changes in each of
24642 the scripts. As I adapted more GNU utilities packages to use
24643 @command{configure} scripts, updating them all by hand became impractical.
24644 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
24645 mail saying that the @command{configure} scripts were great, and asking if
24646 I had a tool for generating them that I could send him. No, I thought,
24647 but I should! So I started to work out how to generate them. And the
24648 journey from the slavery of hand-written @command{configure} scripts to the
24649 abundance and ease of Autoconf began.
24651 Cygnus @command{configure}, which was being developed at around that time,
24652 is table driven; it is meant to deal mainly with a discrete number of
24653 system types with a small number of mainly unguessable features (such as
24654 details of the object file format). The automatic configuration system
24655 that Brian Fox had developed for Bash takes a similar approach. For
24656 general use, it seems to me a hopeless cause to try to maintain an
24657 up-to-date database of which features each variant of each operating
24658 system has. It's easier and more reliable to check for most features on
24659 the fly---especially on hybrid systems that people have hacked on
24660 locally or that have patches from vendors installed.
24662 I considered using an architecture similar to that of Cygnus
24663 @command{configure}, where there is a single @command{configure} script that
24664 reads pieces of @file{configure.in} when run. But I didn't want to have
24665 to distribute all of the feature tests with every package, so I settled
24666 on having a different @command{configure} made from each
24667 @file{configure.in} by a preprocessor. That approach also offered more
24668 control and flexibility.
24670 I looked briefly into using the Metaconfig package, by Larry Wall,
24671 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
24672 reasons. The @command{Configure} scripts it produces are interactive,
24673 which I find quite inconvenient; I didn't like the ways it checked for
24674 some features (such as library functions); I didn't know that it was
24675 still being maintained, and the @command{Configure} scripts I had
24676 seen didn't work on many modern systems (such as System V R4 and NeXT);
24677 it wasn't flexible in what it could do in response to a feature's
24678 presence or absence; I found it confusing to learn; and it was too big
24679 and complex for my needs (I didn't realize then how much Autoconf would
24680 eventually have to grow).
24682 I considered using Perl to generate my style of @command{configure}
24683 scripts, but decided that M4 was better suited to the job of simple
24684 textual substitutions: it gets in the way less, because output is
24685 implicit. Plus, everyone already has it. (Initially I didn't rely on
24686 the GNU extensions to M4.) Also, some of my friends at the
24687 University of Maryland had recently been putting M4 front ends on
24688 several programs, including @code{tvtwm}, and I was interested in trying
24689 out a new language.
24694 Since my @command{configure} scripts determine the system's capabilities
24695 automatically, with no interactive user intervention, I decided to call
24696 the program that generates them Autoconfig. But with a version number
24697 tacked on, that name would be too long for old Unix file systems,
24698 so I shortened it to Autoconf.
24700 In the fall of 1991 I called together a group of fellow questers after
24701 the Holy Grail of portability (er, that is, alpha testers) to give me
24702 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
24703 and continued to add features and improve the techniques used in the
24704 checks. Prominent among the testers were Fran@,{c}ois Pinard, who came up
24705 with the idea of making an Autoconf shell script to run M4
24706 and check for unresolved macro calls; Richard Pixley, who suggested
24707 running the compiler instead of searching the file system to find
24708 include files and symbols, for more accurate results; Karl Berry, who
24709 got Autoconf to configure @TeX{} and added the macro index to the
24710 documentation; and Ian Lance Taylor, who added support for creating a C
24711 header file as an alternative to putting @option{-D} options in a
24712 makefile, so he could use Autoconf for his UUCP package.
24713 The alpha testers cheerfully adjusted their files again and again as the
24714 names and calling conventions of the Autoconf macros changed from
24715 release to release. They all contributed many specific checks, great
24716 ideas, and bug fixes.
24721 In July 1992, after months of alpha testing, I released Autoconf 1.0,
24722 and converted many GNU packages to use it. I was surprised by how
24723 positive the reaction to it was. More people started using it than I
24724 could keep track of, including people working on software that wasn't
24725 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
24726 Autoconf continued to improve rapidly, as many people using the
24727 @command{configure} scripts reported problems they encountered.
24729 Autoconf turned out to be a good torture test for M4 implementations.
24730 Unix M4 started to dump core because of the length of the
24731 macros that Autoconf defined, and several bugs showed up in GNU
24732 M4 as well. Eventually, we realized that we needed to use some
24733 features that only GNU M4 has. 4.3BSD M4, in
24734 particular, has an impoverished set of builtin macros; the System V
24735 version is better, but still doesn't provide everything we need.
24737 More development occurred as people put Autoconf under more stresses
24738 (and to uses I hadn't anticipated). Karl Berry added checks for X11.
24739 david zuhn contributed C++ support. Fran@,{c}ois Pinard made it diagnose
24740 invalid arguments. Jim Blandy bravely coerced it into configuring
24741 GNU Emacs, laying the groundwork for several later improvements.
24742 Roland McGrath got it to configure the GNU C Library, wrote the
24743 @command{autoheader} script to automate the creation of C header file
24744 templates, and added a @option{--verbose} option to @command{configure}.
24745 Noah Friedman added the @option{--autoconf-dir} option and
24746 @code{AC_MACRODIR} environment variable. (He also coined the term
24747 @dfn{autoconfiscate} to mean ``adapt a software package to use
24748 Autoconf''.) Roland and Noah improved the quoting protection in
24749 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
24750 dealing with portability problems from February through June, 1993.
24753 @section Deuteronomy
24755 A long wish list for major features had accumulated, and the effect of
24756 several years of patching by various people had left some residual
24757 cruft. In April 1994, while working for Cygnus Support, I began a major
24758 revision of Autoconf. I added most of the features of the Cygnus
24759 @command{configure} that Autoconf had lacked, largely by adapting the
24760 relevant parts of Cygnus @command{configure} with the help of david zuhn
24761 and Ken Raeburn. These features include support for using
24762 @file{config.sub}, @file{config.guess}, @option{--host}, and
24763 @option{--target}; making links to files; and running @command{configure}
24764 scripts in subdirectories. Adding these features enabled Ken to convert
24765 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
24768 I added more features in response to other peoples' requests. Many
24769 people had asked for @command{configure} scripts to share the results of
24770 the checks between runs, because (particularly when configuring a large
24771 source tree, like Cygnus does) they were frustratingly slow. Mike
24772 Haertel suggested adding site-specific initialization scripts. People
24773 distributing software that had to unpack on MS-DOS asked for a way to
24774 override the @file{.in} extension on the file names, which produced file
24775 names like @file{config.h.in} containing two dots. Jim Avera did an
24776 extensive examination of the problems with quoting in @code{AC_DEFINE}
24777 and @code{AC_SUBST}; his insights led to significant improvements.
24778 Richard Stallman asked that compiler output be sent to @file{config.log}
24779 instead of @file{/dev/null}, to help people debug the Emacs
24780 @command{configure} script.
24782 I made some other changes because of my dissatisfaction with the quality
24783 of the program. I made the messages showing results of the checks less
24784 ambiguous, always printing a result. I regularized the names of the
24785 macros and cleaned up coding style inconsistencies. I added some
24786 auxiliary utilities that I had developed to help convert source code
24787 packages to use Autoconf. With the help of Fran@,{c}ois Pinard, I made
24788 the macros not interrupt each others' messages. (That feature revealed
24789 some performance bottlenecks in GNU M4, which he hastily
24790 corrected!) I reorganized the documentation around problems people want
24791 to solve. And I began a test suite, because experience had shown that
24792 Autoconf has a pronounced tendency to regress when we change it.
24794 Again, several alpha testers gave invaluable feedback, especially
24795 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
24798 Finally, version 2.0 was ready. And there was much rejoicing. (And I
24799 have free time again. I think. Yeah, right.)
24802 @c ========================================================== Appendices
24805 @node GNU Free Documentation License
24806 @appendix GNU Free Documentation License
24814 * Environment Variable Index:: Index of environment variables used
24815 * Output Variable Index:: Index of variables set in output files
24816 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
24817 * Cache Variable Index:: Index of documented cache variables
24818 * Autoconf Macro Index:: Index of Autoconf macros
24819 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
24820 * Autotest Macro Index:: Index of Autotest macros
24821 * Program & Function Index:: Index of those with portability problems
24822 * Concept Index:: General index
24825 @node Environment Variable Index
24826 @appendixsec Environment Variable Index
24828 This is an alphabetical list of the environment variables that might
24829 influence Autoconf checks.
24833 @node Output Variable Index
24834 @appendixsec Output Variable Index
24836 This is an alphabetical list of the variables that Autoconf can
24837 substitute into files that it creates, typically one or more
24838 makefiles. @xref{Setting Output Variables}, for more information
24839 on how this is done.
24843 @node Preprocessor Symbol Index
24844 @appendixsec Preprocessor Symbol Index
24846 This is an alphabetical list of the C preprocessor symbols that the
24847 Autoconf macros define. To work with Autoconf, C source code needs to
24848 use these names in @code{#if} or @code{#ifdef} directives.
24852 @node Cache Variable Index
24853 @appendixsec Cache Variable Index
24855 This is an alphabetical list of documented cache variables used
24856 by macros defined in Autoconf. Autoconf macros may use additional cache
24857 variables internally.
24858 @ifset shortindexflag
24859 To make the list easier to use, the variables are listed without their
24860 preceding @samp{ac_cv_}.
24865 @node Autoconf Macro Index
24866 @appendixsec Autoconf Macro Index
24868 This is an alphabetical list of the Autoconf macros.
24869 @ifset shortindexflag
24870 To make the list easier to use, the macros are listed without their
24871 preceding @samp{AC_}.
24876 @node M4 Macro Index
24877 @appendixsec M4 Macro Index
24879 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
24880 @ifset shortindexflag
24881 To make the list easier to use, the macros are listed without their
24882 preceding @samp{m4_} or @samp{AS_}.
24887 @node Autotest Macro Index
24888 @appendixsec Autotest Macro Index
24890 This is an alphabetical list of the Autotest macros.
24891 @ifset shortindexflag
24892 To make the list easier to use, the macros are listed without their
24893 preceding @samp{AT_}.
24898 @node Program & Function Index
24899 @appendixsec Program and Function Index
24901 This is an alphabetical list of the programs and functions whose
24902 portability is discussed in this document.
24906 @node Concept Index
24907 @appendixsec Concept Index
24909 This is an alphabetical list of the files, tools, and concepts
24910 introduced in this document.
24916 @c LocalWords: texinfo setfilename autoconf texi settitle setchapternewpage
24917 @c LocalWords: setcontentsaftertitlepage finalout ARG ovar varname dvar acx
24918 @c LocalWords: makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
24919 @c LocalWords: shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
24920 @c LocalWords: asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
24921 @c LocalWords: msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
24922 @c LocalWords: direntry autoscan autoreconf autoheader autoupdate config FDs
24923 @c LocalWords: testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
24924 @c LocalWords: insertcopying Autoconf's detailmenu Automake Libtool Posix ois
24925 @c LocalWords: Systemology Checkpointing Changequote INTERCAL changequote dfn
24926 @c LocalWords: Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
24927 @c LocalWords: LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
24928 @c LocalWords: distclean uninstall noindent versioning Tromey dir
24929 @c LocalWords: SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
24930 @c LocalWords: evindex automake Gettext autopoint gettext symlink libtoolize
24931 @c LocalWords: defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
24932 @c LocalWords: SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
24933 @c LocalWords: builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
24934 @c LocalWords: CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
24935 @c LocalWords: datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
24936 @c LocalWords: includedir infodir libexecdir localedir localstatedir mandir
24937 @c LocalWords: oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
24938 @c LocalWords: sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
24939 @c LocalWords: undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
24940 @c LocalWords: PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
24941 @c LocalWords: inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
24942 @c LocalWords: LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
24943 @c LocalWords: inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
24944 @c LocalWords: NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
24945 @c LocalWords: ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
24946 @c LocalWords: snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
24947 @c LocalWords: strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
24948 @c LocalWords: PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
24949 @c LocalWords: closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
24950 @c LocalWords: largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
24951 @c LocalWords: SETGID getloadavg nlist GETMNTENT irix
24952 @c LocalWords: getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
24953 @c LocalWords: lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
24954 @c LocalWords: localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
24955 @c LocalWords: SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
24956 @c LocalWords: STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
24957 @c LocalWords: DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
24958 @c LocalWords: linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
24959 @c LocalWords: NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
24960 @c LocalWords: inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
24961 @c LocalWords: STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
24962 @c LocalWords: ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
24963 @c LocalWords: WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
24964 @c LocalWords: DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
24965 @c LocalWords: passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
24966 @c LocalWords: gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
24967 @c LocalWords: ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
24968 @c LocalWords: varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
24969 @c LocalWords: const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
24970 @c LocalWords: xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
24971 @c LocalWords: ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
24972 @c LocalWords: fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
24973 @c LocalWords: statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
24974 @c LocalWords: GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
24975 @c LocalWords: changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
24976 @c LocalWords: Aas Wcross sep args namespace undefine bpatsubst popdef dquote
24977 @c LocalWords: bregexp Overquote overquotation meisch maisch meische maische
24978 @c LocalWords: miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
24979 @c LocalWords: EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
24980 @c LocalWords: pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
24981 @c LocalWords: drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
24982 @c LocalWords: yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
24983 @c LocalWords: CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
24984 @c LocalWords: MAILPATH scanset arg NetBSD Almquist printf expr cp
24985 @c LocalWords: Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
24986 @c LocalWords: sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
24987 @c LocalWords: mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
24988 @c LocalWords: fooXXXXXX Unicos utimes hpux hppa unescaped
24989 @c LocalWords: pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
24990 @c LocalWords: dec ultrix cpu wildcards rpcc rdtsc powerpc readline
24991 @c LocalWords: withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
24992 @c LocalWords: cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
24993 @c LocalWords: lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
24994 @c LocalWords: intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
24995 @c LocalWords: fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
24996 @c LocalWords: ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
24997 @c LocalWords: installcheck autotest indir Pixley Bothner Eichin Kerberos adl
24998 @c LocalWords: DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
24999 @c LocalWords: Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
25000 @c LocalWords: autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
25001 @c LocalWords: printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
25002 @c LocalWords: VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
25003 @c LocalWords: GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
25004 @c LocalWords: esyscmd len maketemp pushdef substr syscmd sysval translit txt
25005 @c LocalWords: sinclude foreach myvar tolower toupper uniq BASENAME STDIN
25006 @c LocalWords: Dynix descrips basename aname cname macroexpands xno xcheck
25007 @c LocalWords: LIBREADLINE lreadline lncurses libreadline
25009 @c Local Variables:
25011 @c ispell-local-dictionary: "american"
25012 @c indent-tabs-mode: nil
25013 @c whitespace-check-buffer-indent: nil