1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
7 @documentencoding UTF-8
8 @set txicodequoteundirected
9 @set txicodequotebacktick
10 @setchapternewpage odd
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{]}
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{]}
29 @c @dvarv(ARG, DEFAULT-VAR)
30 @c ------------------------
31 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
32 @c around DEFAULT-VAR.
33 @macro dvarv{varname, default}
34 @r{[}@var{\varname\} = @var{\default\}@r{]}
37 @c Handling the indexes with Texinfo yields several different problems.
39 @c Because we want to drop out the AC_ part of the macro names in the
40 @c printed manual, but not in the other outputs, we need a layer above
41 @c the usual @acindex{} etc. That's why we first define indexes such as
42 @c acx meant to become the macro @acindex. First of all, using 'ac_'
43 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
44 @c So use something more regular 'acx'. Then you finish with a printed
45 @c index saying 'index is not existent'. Of course: you ought to use
46 @c two letters :( So you use capitals.
48 @c Second, when defining a macro in the TeX world, following spaces are
49 @c eaten. But then, since we embed @acxindex commands that use the end
50 @c of line as an end marker, the whole things wrecks itself. So make
51 @c sure you do *force* an additional end of line, add a '@c'.
53 @c Finally, you might want to get rid of TeX expansion, using --expand
54 @c with texi2dvi. But then you wake up an old problem: we use macros
55 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
57 @c Define an environment variable index, for variables users may set
58 @c in their environment or on the configure command line.
60 @c Define an output variable index, for commonly AC_SUBST'ed variables.
62 @c Define a cache variable index, for variables matching *_cv_*.
64 @c Other shell variables not fitting the above categories should be
65 @c listed in the predefined vrindex, which we merge in the concept index.
67 @c Define a CPP preprocessor macro index, for #define'd strings.
69 @c Define an Autoconf macro index that @defmac doesn't write to.
71 @c Define an Autotest macro index that @defmac doesn't write to.
73 @c Define an M4sugar macro index that @defmac doesn't write to.
75 @c Define an index for *foreign* programs: 'mv' etc. Used for the
76 @c portability sections and so on.
81 @c Shall we factor AC_ out of the Autoconf macro index etc.?
88 @c Registering an AC_\MACRO\.
95 @ifclear shortindexflag
103 @c Registering an AH_\MACRO\.
104 @macro ahindex{macro}
111 @c Registering an AS_\MACRO\.
112 @ifset shortindexflag
113 @macro asindex{macro}
118 @ifclear shortindexflag
119 @macro asindex{macro}
126 @c Registering an AT_\MACRO\.
127 @ifset shortindexflag
128 @macro atindex{macro}
133 @ifclear shortindexflag
134 @macro atindex{macro}
141 @c Registering an AU_\MACRO\.
142 @macro auindex{macro}
149 @c Indexing a header.
150 @macro hdrindex{macro}
151 @prindex @file{\macro\}
157 @c Registering an m4_\MACRO\.
158 @ifset shortindexflag
159 @macro msindex{macro}
164 @ifclear shortindexflag
165 @macro msindex{macro}
171 @c @caindex{VARIABLE}
172 @c ------------------
173 @c Registering an ac_cv_\VARIABLE\ cache variable.
174 @ifset shortindexflag
175 @macro caindex{macro}
179 @ifclear shortindexflag
180 @macro caindex{macro}
181 @CAindex ac_cv_\macro\
185 @c Define an index for functions: 'alloca' etc. Used for the
186 @c portability sections and so on. We can't use 'fn' (aka 'fnindex'),
187 @c since '@defmac' goes into it => we'd get all the macros too.
189 @c FIXME: Aaarg! It seems there are too many indices for TeX :(
191 @c ! No room for a new @write .
192 @c l.112 @defcodeindex fu
194 @c so don't define yet another one :( Just put some tags before each
195 @c @prindex which is actually a @funindex.
200 @c @c Put the programs and functions into their own index.
201 @c @syncodeindex fu pr
203 @comment %**end of header
204 @comment ========================================================
208 This manual (@value{UPDATED}) is for GNU Autoconf
209 (version @value{VERSION}),
210 a package for creating scripts to configure source code packages using
211 templates and an M4 macro package.
213 Copyright @copyright{} 1992--1996, 1998--2017, 2020--2024 Free Software
217 Permission is granted to copy, distribute and/or modify this document
218 under the terms of the GNU Free Documentation License,
219 Version 1.3 or any later version published by the Free Software
220 Foundation; with no Invariant Sections, no Front-Cover texts, and
221 no Back-Cover Texts. A copy of the license is included in the section
222 entitled ``GNU Free Documentation License.''
228 @dircategory Software development
230 * Autoconf: (autoconf). Create source code configuration scripts.
233 @dircategory Individual utilities
235 * autoscan: (autoconf)autoscan Invocation.
236 Semi-automatic @file{configure.ac} writing
237 * ifnames: (autoconf)ifnames Invocation. Listing conditionals in source.
238 * autoconf-invocation: (autoconf)autoconf Invocation.
239 How to create configuration scripts
240 * autoreconf: (autoconf)autoreconf Invocation.
241 Remaking multiple @command{configure} scripts
242 * autoheader: (autoconf)autoheader Invocation.
243 How to create configuration templates
244 * autom4te: (autoconf)autom4te Invocation.
245 The Autoconf executables backbone
246 * configure: (autoconf)configure Invocation. Configuring a package.
247 * autoupdate: (autoconf)autoupdate Invocation.
248 Automatic update of @file{configure.ac}
249 * config.status: (autoconf)config.status Invocation. Recreating configurations.
250 * testsuite: (autoconf)testsuite Invocation. Running an Autotest test suite.
255 @subtitle Creating Automatic Configuration Scripts
256 @subtitle for version @value{VERSION}, @value{UPDATED}
257 @author David MacKenzie
259 @author Akim Demaille
261 @vskip 0pt plus 1filll
274 @c The master menu, created with texinfo-master-menu, goes here.
277 * Introduction:: Autoconf's purpose, strengths, and weaknesses
278 * The GNU Build System:: A set of tools for portable software packages
279 * Making configure Scripts:: How to organize and produce Autoconf scripts
280 * Setup:: Initialization and output
281 * Existing Tests:: Macros that check for particular features
282 * Writing Tests:: How to write new feature checks
283 * Results:: What to do with results from feature checks
284 * Programming in M4:: Layers on top of which Autoconf is written
285 * Programming in M4sh:: Shell portability layer
286 * Writing Autoconf Macros:: Adding new macros to Autoconf
287 * Portable Shell:: Shell script portability pitfalls
288 * Portable Make:: Makefile portability pitfalls
289 * Portable C and C++:: C and C++ portability pitfalls
290 * Manual Configuration:: Selecting features that can't be guessed
291 * Site Configuration:: Local defaults for @command{configure}
292 * Running configure Scripts:: How to use the Autoconf output
293 * config.status Invocation:: Recreating a configuration
294 * Obsolete Constructs:: Kept for backward compatibility
295 * Using Autotest:: Creating portable test suites
296 * FAQ:: Frequent Autoconf Questions, with answers
297 * History:: History of Autoconf
298 * GNU Free Documentation License:: License for copying this manual
299 * Indices:: Indices of symbols, concepts, etc.
302 --- The Detailed Node Listing ---
306 * Automake:: Escaping makefile hell
307 * Gnulib:: The GNU portability library
308 * Libtool:: Building libraries portably
309 * Pointers:: More info on the GNU build system
311 Making @command{configure} Scripts
313 * Writing Autoconf Input:: What to put in an Autoconf input file
314 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
315 * ifnames Invocation:: Listing the conditionals in source code
316 * autoconf Invocation:: How to create configuration scripts
317 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
319 Writing @file{configure.ac}
321 * Shell Script Compiler:: Autoconf as solution of a problem
322 * Autoconf Language:: Programming in Autoconf
323 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
325 Initialization and Output Files
327 * Initializing configure:: Option processing etc.
328 * Versioning:: Dealing with Autoconf versions
329 * Notices:: Copyright, version numbers in @command{configure}
330 * Input:: Where Autoconf should find files
331 * Output:: Outputting results from the configuration
332 * Configuration Actions:: Preparing the output based on results
333 * Configuration Files:: Creating output files
334 * Makefile Substitutions:: Using output variables in makefiles
335 * Configuration Headers:: Creating a configuration header file
336 * Configuration Commands:: Running arbitrary instantiation commands
337 * Configuration Links:: Links depending on the configuration
338 * Subdirectories:: Configuring independent packages together
339 * Default Prefix:: Changing the default installation prefix
341 Substitutions in Makefiles
343 * Preset Output Variables:: Output variables that are always set
344 * Installation Directory Variables:: Other preset output variables
345 * Changed Directory Variables:: Warnings about @file{datarootdir}
346 * Build Directories:: Supporting multiple concurrent compiles
347 * Automatic Remaking:: Makefile rules for configuring
349 Configuration Header Files
351 * Header Templates:: Input for the configuration headers
352 * autoheader Invocation:: How to create configuration templates
353 * Autoheader Macros:: How to specify CPP templates
357 * Common Behavior:: Macros' standard schemes
358 * Alternative Programs:: Selecting between alternative programs
359 * Files:: Checking for the existence of files
360 * Libraries:: Library archives that might be missing
361 * Library Functions:: C library functions that might be missing
362 * Header Files:: Header files that might be missing
363 * Declarations:: Declarations that may be missing
364 * Structures:: Structures or members that might be missing
365 * Types:: Types that might be missing
366 * Compilers and Preprocessors:: Checking for compiling programs
367 * System Services:: Operating system services
368 * C and POSIX Variants:: Kludges for C and POSIX variants
369 * Erlang Libraries:: Checking for the existence of Erlang libraries
373 * Standard Symbols:: Symbols defined by the macros
374 * Default Includes:: Includes used by the generic macros
378 * Particular Programs:: Special handling to find certain programs
379 * Generic Programs:: How to find other programs
383 * Function Portability:: Pitfalls with usual functions
384 * Particular Functions:: Special handling to find certain functions
385 * Generic Functions:: How to find other functions
389 * Header Portability:: Collected knowledge on common headers
390 * Particular Headers:: Special handling to find certain headers
391 * Generic Headers:: How to find other headers
395 * Particular Declarations:: Macros to check for certain declarations
396 * Generic Declarations:: How to find other declarations
400 * Particular Structures:: Macros to check for certain structure members
401 * Generic Structures:: How to find other structure members
405 * Particular Types:: Special handling to find certain types
406 * Generic Types:: How to find other types
408 Compilers and Preprocessors
410 * Specific Compiler Characteristics:: Some portability issues
411 * Generic Compiler Characteristics:: Language independent tests and features
412 * C Compiler:: Checking its characteristics
413 * C++ Compiler:: Likewise
414 * Objective C Compiler:: Likewise
415 * Objective C++ Compiler:: Likewise
416 * Erlang Compiler and Interpreter:: Likewise
417 * Fortran Compiler:: Likewise
418 * Go Compiler:: Likewise
422 * Language Choice:: Selecting which language to use for testing
423 * Writing Test Programs:: Forging source files for compilers
424 * Running the Preprocessor:: Detecting preprocessor symbols
425 * Running the Compiler:: Detecting language or header features
426 * Running the Linker:: Detecting library features
427 * Runtime:: Testing for runtime features
428 * Multiple Cases:: Tests for several possible values
430 Writing Test Programs
432 * Guidelines:: General rules for writing test programs
433 * Test Functions:: Avoiding pitfalls in test programs
434 * Generating Sources:: Source program boilerplate
438 * Defining Symbols:: Defining C preprocessor symbols
439 * Setting Output Variables:: Replacing variables in output files
440 * Special Chars in Variables:: Characters to beware of in variables
441 * Caching Results:: Speeding up subsequent @command{configure} runs
442 * Printing Messages:: Notifying @command{configure} users
446 * Cache Variable Names:: Shell variables used in caches
447 * Cache Files:: Files @command{configure} uses for caching
448 * Cache Checkpointing:: Loading and saving the cache file
452 * M4 Quotation:: Protecting macros from unwanted expansion
453 * Using autom4te:: The Autoconf executables backbone
454 * Programming in M4sugar:: Convenient pure M4 macros
455 * Debugging via autom4te:: Figuring out what M4 was doing
459 * Active Characters:: Characters that change the behavior of M4
460 * One Macro Call:: Quotation and one macro call
461 * Quoting and Parameters:: M4 vs. shell parameters
462 * Quotation and Nested Macros:: Macros calling macros
463 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
464 * Quadrigraphs:: Another way to escape special characters
465 * Balancing Parentheses:: Dealing with unbalanced parentheses
466 * Quotation Rule Of Thumb:: One parenthesis, one quote
468 Using @command{autom4te}
470 * autom4te Invocation:: A GNU M4 wrapper
471 * Customizing autom4te:: Customizing the Autoconf package
473 Programming in M4sugar
475 * Redefined M4 Macros:: M4 builtins changed in M4sugar
476 * Diagnostic Macros:: Diagnostic messages from M4sugar
477 * Diversion support:: Diversions in M4sugar
478 * Conditional constructs:: Conditions in M4
479 * Looping constructs:: Iteration in M4
480 * Evaluation Macros:: More quotation and evaluation control
481 * Text processing Macros:: String manipulation in M4
482 * Number processing Macros:: Arithmetic computation in M4
483 * Set manipulation Macros:: Set manipulation in M4
484 * Forbidden Patterns:: Catching unexpanded macros
488 * Common Shell Constructs:: Portability layer for common shell constructs
489 * Polymorphic Variables:: Support for indirect variable names
490 * Initialization Macros:: Macros to establish a sane shell environment
491 * File Descriptor Macros:: File descriptor macros for input and output
493 Writing Autoconf Macros
495 * Macro Definitions:: Basic format of an Autoconf macro
496 * Macro Names:: What to call your new macros
497 * Dependencies Between Macros:: What to do when macros depend on other macros
498 * Obsoleting Macros:: Warning about old ways of doing things
499 * Coding Style:: Writing Autoconf macros à la Autoconf
501 Dependencies Between Macros
503 * Prerequisite Macros:: Ensuring required information
504 * Suggested Ordering:: Warning about possible ordering problems
505 * One-Shot Macros:: Ensuring a macro is called only once
507 Portable Shell Programming
509 * Systemology:: A zoology of operating systems
510 * Shellology:: A zoology of shells
511 * Invoking the Shell:: Invoking the shell as a command
512 * Here-Documents:: Quirks and tricks
513 * File Descriptors:: FDs and redirections
514 * Signal Handling:: Shells, signals, and headaches
515 * File System Conventions:: File names
516 * Shell Pattern Matching:: Pattern matching
517 * Shell Substitutions:: Variable and command expansions
518 * Assignments:: Varying side effects of assignments
519 * Parentheses:: Parentheses in shell scripts
520 * Special Shell Variables:: Variables you should not change
521 * Shell Functions:: What to look out for if you use them
522 * Limitations of Builtins:: Portable use of not so portable /bin/sh
523 * Limitations of Usual Tools:: Portable use of portable tools
525 Portable Make Programming
527 * $< in Ordinary Make Rules:: $< in ordinary rules
528 * Failure in Make Rules:: Failing portably in rules
529 * Command Line Prefixes:: What's at the start of makefile command lines
530 * Special Chars in Names:: Special characters in macro names
531 * Backslash-Newline-Empty:: Empty lines after backslash-newline
532 * Backslash-Newline Comments:: Spanning comments across line boundaries
533 * Macros and Submakes:: @code{make macro=value} and submakes
534 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
535 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
536 * Parallel Make:: Parallel @command{make} quirks
537 * Comments in Make Rules:: Other problems with Make comments
538 * Newlines in Make Rules:: Using literal newlines in rules
539 * Comments in Make Macros:: Other problems with Make comments in macros
540 * Trailing whitespace in Make Macros:: Macro substitution problems
541 * Command-line Macros and whitespace:: Whitespace trimming of values
542 * obj/ and Make:: Don't name a subdirectory @file{obj}
543 * make -k Status:: Exit status of @samp{make -k}
544 * VPATH and Make:: @code{VPATH} woes
545 * Single Suffix Rules:: Single suffix rules and separated dependencies
546 * Timestamps and Make:: Sub-second timestamp resolution
548 @code{VPATH} and Make
550 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
551 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
552 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
553 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
554 * Make Target Lookup:: More details about @code{VPATH} lookup
556 Portable C and C++ Programming
558 * Varieties of Unportability:: How to make your programs unportable
559 * Integer Overflow:: When integers get too large
560 * Preprocessor Arithmetic:: @code{#if} expression problems
561 * Null Pointers:: Properties of null pointers
562 * Buffer Overruns:: Subscript errors and the like
563 * Volatile Objects:: @code{volatile} and signals
564 * Floating Point Portability:: Portable floating-point arithmetic
565 * Exiting Portably:: Exiting and the exit status
569 * Integer Overflow Basics:: Why integer overflow is a problem
570 * Signed Overflow Examples:: Examples of code assuming wraparound
571 * Optimization and Wraparound:: Optimizations that break uses of wraparound
572 * Signed Overflow Advice:: Practical advice for signed overflow issues
573 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
577 * Specifying Target Triplets:: Specifying target triplets
578 * Canonicalizing:: Getting the canonical system type
579 * Using System Type:: What to do with the system type
583 * Help Formatting:: Customizing @samp{configure --help}
584 * External Software:: Working with other optional software
585 * Package Options:: Selecting optional features
586 * Pretty Help Strings:: Formatting help string
587 * Option Checking:: Controlling checking of @command{configure} options
588 * Site Details:: Configuring site details
589 * Transforming Names:: Changing program names when installing
590 * Site Defaults:: Giving @command{configure} local defaults
592 Transforming Program Names When Installing
594 * Transformation Options:: @command{configure} options to transform names
595 * Transformation Examples:: Sample uses of transforming names
596 * Transformation Rules:: Makefile uses of transforming names
598 Running @command{configure} Scripts
600 * Basic Installation:: Instructions for typical cases
601 * Compilers and Options:: Selecting compilers and optimization
602 * Multiple Architectures:: Compiling for multiple architectures at once
603 * Installation Names:: Installing in different directories
604 * Optional Features:: Selecting optional features
605 * System Types:: Specifying a system type
606 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
607 * Defining Variables:: Specifying the compiler etc.
608 * configure Invocation:: Changing how @command{configure} runs
612 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
613 * acconfig Header:: Additional entries in @file{config.h.in}
614 * autoupdate Invocation:: Automatic update of @file{configure.ac}
615 * Obsolete Macros:: Backward compatibility macros
616 * Autoconf 1:: Tips for upgrading your files
617 * Autoconf 2.13:: Some fresher tips
619 Upgrading From Version 1
621 * Changed File Names:: Files you might rename
622 * Changed Makefiles:: New things to put in @file{Makefile.in}
623 * Changed Macros:: Macro calls you might replace
624 * Changed Results:: Changes in how to check test results
625 * Changed Macro Writing:: Better ways to write your own macros
627 Upgrading From Version 2.13
629 * Changed Quotation:: Broken code which used to work
630 * New Macros:: Interaction with foreign macros
631 * Hosts and Cross-Compilation:: Bugward compatibility kludges
632 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
633 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
635 Generating Test Suites with Autotest
637 * Using an Autotest Test Suite:: Autotest and the user
638 * Writing Testsuites:: Autotest macros
639 * testsuite Invocation:: Running @command{testsuite} scripts
640 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
642 Using an Autotest Test Suite
644 * testsuite Scripts:: The concepts of Autotest
645 * Autotest Logs:: Their contents
647 Frequent Autoconf Questions, with answers
649 * Distributing:: Distributing @command{configure} scripts
650 * Why GNU M4:: Why not use the standard M4?
651 * Bootstrapping:: Autoconf and GNU M4 require each other?
652 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
653 * Defining Directories:: Passing @code{datadir} to program
654 * Autom4te Cache:: What is it? Can I remove it?
655 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
656 * Expanded Before Required:: Expanded Before Required
657 * Debugging:: Debugging @command{configure} scripts
661 * Genesis:: Prehistory and naming of @command{configure}
662 * Exodus:: The plagues of M4 and Perl
663 * Leviticus:: The priestly code of portability arrives
664 * Numbers:: Growth and contributors
665 * Deuteronomy:: Approaching the promises of easy configuration
669 * Environment Variable Index:: Index of environment variables used
670 * Output Variable Index:: Index of variables set in output files
671 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
672 * Cache Variable Index:: Index of documented cache variables
673 * Autoconf Macro Index:: Index of Autoconf macros
674 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
675 * Autotest Macro Index:: Index of Autotest macros
676 * Program & Function Index:: Index of those with portability problems
677 * Concept Index:: General index
682 @c ============================================================= Introduction.
685 @chapter Introduction
689 A physicist, an engineer, and a computer scientist were discussing the
690 nature of God. ``Surely a Physicist,'' said the physicist, ``because
691 early in the Creation, God made Light; and you know, Maxwell's
692 equations, the dual nature of electromagnetic waves, the relativistic
693 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
694 before making Light, God split the Chaos into Land and Water; it takes
695 a hell of an engineer to handle that big amount of mud, and orderly
696 separation of solids from liquids@enddots{}'' The computer scientist
697 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
701 @c (via François Pinard)
703 Autoconf is a tool for producing shell scripts that automatically
704 configure software source code packages to adapt to many kinds of
705 POSIX-like systems. The configuration scripts produced by Autoconf
706 are independent of Autoconf when they are run, so their users do not
707 need to have Autoconf.
709 The configuration scripts produced by Autoconf require no manual user
710 intervention when run; they do not normally even need an argument
711 specifying the system type. Instead, they individually test for the
712 presence of each feature that the software package they are for might need.
713 (Before each check, they print a one-line message stating what they are
714 checking for, so the user doesn't get too bored while waiting for the
715 script to finish.) As a result, they deal well with systems that are
716 hybrids or customized from the more common POSIX variants. There is
717 no need to maintain files that list the features supported by each
718 release of each variant of POSIX.
720 For each software package that Autoconf is used with, it creates a
721 configuration script from a template file that lists the system features
722 that the package needs or can use. After the shell code to recognize
723 and respond to a system feature has been written, Autoconf allows it to
724 be shared by many software packages that can use (or need) that feature.
725 If it later turns out that the shell code needs adjustment for some
726 reason, it needs to be changed in only one place; all of the
727 configuration scripts can be regenerated automatically to take advantage
730 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
731 @c --Henry Spencer, 1987 (see https://en.wikipedia.org/wiki/Unix_philosophy)
732 Those who do not understand Autoconf are condemned to reinvent it, poorly.
733 The primary goal of Autoconf is making the @emph{user's} life easier;
734 making the @emph{maintainer's} life easier is only a secondary goal.
735 Put another way, the primary goal is not to make the generation of
736 @file{configure} automatic for package maintainers (although patches
737 along that front are welcome, since package maintainers form the user
738 base of Autoconf); rather, the goal is to make @file{configure}
739 painless, portable, and predictable for the end user of each
740 @dfn{autoconfiscated} package. And to this degree, Autoconf is highly
741 successful at its goal---most complaints to the Autoconf list are
742 about difficulties in writing Autoconf input, and not in the behavior of
743 the resulting @file{configure}. Even packages that don't use Autoconf
744 will generally provide a @file{configure} script, and the most common
745 complaint about these alternative home-grown scripts is that they fail
746 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
747 standards, The GNU Coding Standards}) that users
748 have come to expect from Autoconf-generated @file{configure} scripts.
750 The Metaconfig package is similar in purpose to Autoconf, but the
751 scripts it produces require manual user intervention, which is quite
752 inconvenient when configuring large source trees. Unlike Metaconfig
753 scripts, Autoconf scripts can support cross-compiling, if some care is
754 taken in writing them.
756 Autoconf does not solve all problems related to making portable
757 software packages---for a more complete solution, it should be used in
758 concert with other GNU build tools like Automake and
759 Libtool. These other tools take on jobs like the creation of a
760 portable, recursive makefile with all of the standard targets,
761 linking of shared libraries, and so on. @xref{The GNU Build System},
762 for more information.
764 Autoconf imposes some restrictions on the names of macros used with
765 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
767 Autoconf requires GNU M4 version 1.4.8 or later in order to
768 generate the scripts. It uses features that some versions of M4,
769 including GNU M4 1.3, do not have. Autoconf works better
770 with GNU M4 version 1.4.16 or later, though this is not
773 @xref{Autoconf 1}, for information about upgrading from version 1.
774 @xref{History}, for the story of Autoconf's development. @xref{FAQ},
775 for answers to some common questions about Autoconf.
777 See the @uref{https://@/www.gnu.org/@/software/@/autoconf/,
778 Autoconf web page} for up-to-date information, details on the mailing
779 lists, pointers to a list of known bugs, etc.
781 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
782 list}. Past suggestions are
783 @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
785 Mail bug reports to @email{bug-autoconf@@gnu.org, the
786 Autoconf Bugs mailing list}. Past bug reports are
787 @uref{https://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
789 If possible, first check that your bug is
790 not already solved in current development versions, and that it has not
791 been reported yet. Be sure to include all the needed information and a
792 short @file{configure.ac} that demonstrates the problem.
794 Autoconf's development tree is accessible via @command{git}; see the
795 @uref{https://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
796 Summary} for details, or view
797 @uref{https://@/git.savannah.gnu.org/@/cgit/@/autoconf.git, the actual
798 repository}. Patches relative to the current @command{git} version can
799 be sent for review to the @email{autoconf-patches@@gnu.org, Autoconf
800 Patches mailing list}, with discussion on prior patches
801 @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
802 archived}; and all commits are posted in the read-only
803 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
804 also @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
807 Because of its mission, the Autoconf package itself
808 includes only a set of often-used
809 macros that have already demonstrated their usefulness. Nevertheless,
810 if you wish to share your macros, or find existing ones, see the
811 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
812 Archive}, which is kindly run by @email{simons@@cryp.to,
816 @c ================================================= The GNU Build System
818 @node The GNU Build System
819 @chapter The GNU Build System
820 @cindex GNU build system
822 Autoconf solves an important problem---reliable discovery of
823 system-specific build and runtime information---but this is only one
824 piece of the puzzle for the development of portable software. To this
825 end, the GNU project has developed a suite of integrated
826 utilities to finish the job Autoconf started: the GNU build
827 system, whose most important components are Autoconf, Automake, and
828 Libtool. In this chapter, we introduce you to those tools, point you
829 to sources of more information, and try to convince you to use the
830 entire GNU build system for your software.
833 * Automake:: Escaping makefile hell
834 * Gnulib:: The GNU portability library
835 * Libtool:: Building libraries portably
836 * Pointers:: More info on the GNU build system
842 The ubiquity of @command{make} means that a makefile is almost the
843 only viable way to distribute automatic build rules for software, but
844 one quickly runs into its numerous limitations. Its lack of
845 support for automatic dependency tracking, recursive builds in
846 subdirectories, reliable timestamps (e.g., for network file systems), and
847 so on, mean that developers must painfully (and often incorrectly)
848 reinvent the wheel for each project. Portability is non-trivial, thanks
849 to the quirks of @command{make} on many systems. On top of all this is the
850 manual labor required to implement the many standard targets that users
851 have come to expect (@code{make install}, @code{make distclean},
852 @code{make uninstall}, etc.). Since you are, of course, using Autoconf,
853 you also have to insert repetitive code in your @file{Makefile.in} to
854 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
855 provided by @command{configure}. Into this mess steps @dfn{Automake}.
858 Automake allows you to specify your build needs in a @file{Makefile.am}
859 file with a vastly simpler and more powerful syntax than that of a plain
860 makefile, and then generates a portable @file{Makefile.in} for
861 use with Autoconf. For example, the @file{Makefile.am} to build and
862 install a simple ``Hello world'' program might look like:
866 hello_SOURCES = hello.c
870 The resulting @file{Makefile.in} (~400 lines) automatically supports all
871 the standard targets, the substitutions provided by Autoconf, automatic
872 dependency tracking, @code{VPATH} building, and so on. @command{make}
873 builds the @code{hello} program, and @code{make install} installs it
874 in @file{/usr/local/bin} (or whatever prefix was given to
875 @command{configure}, if not @file{/usr/local}).
877 The benefits of Automake increase for larger packages (especially ones
878 with subdirectories), but even for small programs the added convenience
879 and portability can be substantial. And that's not all@enddots{}
884 GNU software has a well-deserved reputation for running on
885 many different types of systems. While our primary goal is to write
886 software for the GNU system, many users and developers have
887 been introduced to us through the systems that they were already using.
890 Gnulib is a central location for common GNU code, intended to
891 be shared among free software packages. Its components are typically
892 shared at the source level, rather than being a library that gets built,
893 installed, and linked against. The idea is to copy files from Gnulib
894 into your own source tree. There is no distribution tarball; developers
895 should just grab source modules from the repository. The source files
896 are available online, under various licenses, mostly GNU
899 Gnulib modules typically contain C source code along with Autoconf
900 macros used to configure the source code. For example, the Gnulib
901 @code{stdckdint} module implements a @file{stdckdint.h} header that nearly
902 conforms to C23, even on older hosts that lack @file{stdckdint.h}.
903 This module contains a source file for the replacement header, along
904 with an Autoconf macro that arranges to use the replacement header on
907 For more information, consult the Gnulib website,
908 @uref{https://@/www.gnu.org/@/software/@/gnulib/}.
913 Often, one wants to build not only programs, but libraries, so that
914 other programs can benefit from the fruits of your labor. Ideally, one
915 would like to produce @emph{shared} (dynamically linked) libraries,
916 which can be used by multiple programs without duplication on disk or in
917 memory and can be updated independently of the linked programs.
918 Producing shared libraries portably, however, is the stuff of
919 nightmares---each system has its own incompatible tools, compiler flags,
920 and magic incantations. Fortunately, GNU provides a solution:
924 Libtool handles all the requirements of building shared libraries for
925 you, and at this time seems to be the @emph{only} way to do so with any
926 portability. It also handles many other headaches, such as: the
927 interaction of Make rules with the variable suffixes of
928 shared libraries, linking reliably with shared libraries before they are
929 installed by the superuser, and supplying a consistent versioning system
930 (so that different versions of a library can be installed or upgraded
931 without breaking binary compatibility). Although Libtool, like
932 Autoconf, can be used without Automake, it is most simply utilized in
933 conjunction with Automake---there, Libtool is used automatically
934 whenever shared libraries are needed, and you need not know its syntax.
939 Developers who are used to the simplicity of @command{make} for small
940 projects on a single system might be daunted at the prospect of
941 learning to use Automake and Autoconf. As your software is
942 distributed to more and more users, however, you otherwise
943 quickly find yourself putting lots of effort into reinventing the
944 services that the GNU build tools provide, and making the
945 same mistakes that they once made and overcame. (Besides, since
946 you're already learning Autoconf, Automake is a piece of cake.)
948 There are a number of places that you can go to for more information on
955 The project home pages for
956 @uref{https://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
957 @uref{https://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
958 @uref{https://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
959 @uref{https://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
961 @item Automake Manual
963 @xref{Top, , Automake, automake, GNU Automake}, for more
964 information on Automake.
968 The book @cite{GNU Autoconf, Automake and
969 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
970 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor. SAMS (originally
971 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
972 build environment. You can also find
973 @uref{https://@/www.sourceware.org/@/autobook/, the entire book on-line}.
977 @c ================================================= Making configure Scripts.
979 @node Making configure Scripts
980 @chapter Making @command{configure} Scripts
981 @cindex @file{aclocal.m4}
982 @cindex @command{configure}
984 The configuration scripts that Autoconf produces are by convention
985 called @command{configure}. When run, @command{configure} creates several
986 files, replacing configuration parameters in them with appropriate
987 values. The files that @command{configure} creates are:
991 one or more @file{Makefile} files, usually one in each subdirectory of the
992 package (@pxref{Makefile Substitutions});
995 optionally, a C header file, the name of which is configurable,
996 containing @code{#define} directives (@pxref{Configuration Headers});
999 a shell script called @file{config.status} that, when run, recreates
1000 the files listed above (@pxref{config.status Invocation});
1003 an optional shell script normally called @file{config.cache}
1004 (created when using @samp{configure --config-cache}) that
1005 saves the results of running many of the tests (@pxref{Cache Files});
1008 a file called @file{config.log} containing any messages produced by
1009 compilers, to help debugging if @command{configure} makes a mistake.
1012 @cindex @file{configure.ac}
1013 To create a @command{configure} script with Autoconf, you need
1014 to write an Autoconf input file @file{configure.ac} and run
1015 @command{autoconf} on it. If you write your own feature tests to
1016 supplement those that come with Autoconf, you might also write files
1017 called @file{aclocal.m4} and @file{acsite.m4}. If you use a C header
1018 file to contain @code{#define} directives, you might also run
1019 @command{autoheader}, and you can distribute the generated file
1020 @file{config.h.in} with the package.
1022 Here is a diagram showing how the files that can be used in
1023 configuration are produced. Programs that are executed are suffixed by
1024 @samp{*}. Optional files are enclosed in square brackets (@samp{[]}).
1025 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1026 macro files (by reading @file{autoconf.m4}).
1029 Files used in preparing a software package for distribution, when using
1032 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1036 | .------> autoconf* -----> configure
1037 [aclocal.m4] --+---+
1038 | `-----> [autoheader*] --> [config.h.in]
1046 Additionally, if you use Automake, the following additional productions
1053 [local macros] --+--> aclocal* --> aclocal.m4
1060 +--> automake* --> Makefile.in
1066 Files used in configuring a software package:
1069 .-------------> [config.cache]
1070 configure* ------------+-------------> config.log
1072 [config.h.in] -. v .-> [config.h] -.
1073 +--> config.status* -+ +--> make*
1074 Makefile.in ---' `-> Makefile ---'
1079 * Writing Autoconf Input:: What to put in an Autoconf input file
1080 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
1081 * ifnames Invocation:: Listing the conditionals in source code
1082 * autoconf Invocation:: How to create configuration scripts
1083 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
1086 @node Writing Autoconf Input
1087 @section Writing @file{configure.ac}
1089 To produce a @command{configure} script for a software package, create a
1090 file called @file{configure.ac} that contains invocations of the
1091 Autoconf macros that test the system features your package needs or can
1092 use. Autoconf macros already exist to check for many features; see
1093 @ref{Existing Tests}, for their descriptions. For most other features,
1094 you can use Autoconf template macros to produce custom checks; see
1095 @ref{Writing Tests}, for information about them. For especially tricky
1096 or specialized features, @file{configure.ac} might need to contain some
1097 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1098 Programming}. The @command{autoscan} program can give you a good start
1099 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1102 @cindex @file{configure.in}
1103 Previous versions of Autoconf promoted the name @file{configure.in},
1104 which is somewhat ambiguous (the tool needed to process this file is not
1105 described by its extension), and introduces a slight confusion with
1106 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1107 processed by @command{configure}''). Using @file{configure.ac} is now
1108 preferred, while the use of @file{configure.in} will cause warnings
1109 from @command{autoconf}.
1112 * Shell Script Compiler:: Autoconf as solution of a problem
1113 * Autoconf Language:: Programming in Autoconf
1114 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
1117 @node Shell Script Compiler
1118 @subsection A Shell Script Compiler
1120 Just as for any other computer language, in order to properly program
1121 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1122 the language tries to address and @emph{how} it does so.
1124 The problem Autoconf addresses is that the world is a mess. After all,
1125 you are using Autoconf in order to have your package compile easily on
1126 all sorts of different systems, some of them being extremely hostile.
1127 Autoconf itself bears the price for these differences: @command{configure}
1128 must run on all those systems, and thus @command{configure} must limit itself
1129 to their lowest common denominator of features.
1131 Naturally, you might then think of shell scripts; who needs
1132 @command{autoconf}? A set of properly written shell functions is enough to
1133 make it easy to write @command{configure} scripts by hand. Sigh!
1134 Unfortunately, even in 2008, where shells without any function support are
1135 far and few between, there are pitfalls to avoid when making use of them.
1136 Also, finding a Bourne shell that accepts shell functions is not trivial,
1137 even though there is almost always one on interesting porting targets.
1139 So, what is really needed is some kind of compiler, @command{autoconf},
1140 that takes an Autoconf program, @file{configure.ac}, and transforms it
1141 into a portable shell script, @command{configure}.
1143 How does @command{autoconf} perform this task?
1145 There are two obvious possibilities: creating a brand new language or
1146 extending an existing one. The former option is attractive: all
1147 sorts of optimizations could easily be implemented in the compiler and
1148 many rigorous checks could be performed on the Autoconf program
1149 (e.g., rejecting any non-portable construct). Alternatively, you can
1150 extend an existing language, such as the @code{sh} (Bourne shell)
1153 Autoconf does the latter: it is a layer on top of @code{sh}. It was
1154 therefore most convenient to implement @command{autoconf} as a macro
1155 expander: a program that repeatedly performs @dfn{macro expansions} on
1156 text input, replacing macro calls with macro bodies and producing a pure
1157 @code{sh} script in the end. Instead of implementing a dedicated
1158 Autoconf macro expander, it is natural to use an existing
1159 general-purpose macro language, such as M4, and implement the extensions
1160 as a set of M4 macros.
1163 @node Autoconf Language
1164 @subsection The Autoconf Language
1167 The Autoconf language differs from many other computer
1168 languages because it treats actual code the same as plain text. Whereas
1169 in C, for instance, data and instructions have different syntactic
1170 status, in Autoconf their status is rigorously the same. Therefore, we
1171 need a means to distinguish literal strings from text to be expanded:
1174 When calling macros that take arguments, there must not be any white
1175 space between the macro name and the open parenthesis.
1178 AC_INIT ([oops], [1.0]) # incorrect
1179 AC_INIT([hello], [1.0]) # good
1183 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1184 separated by commas. Any leading blanks or newlines in arguments are ignored,
1185 unless they are quoted. You should always quote an argument that
1186 might contain a macro name, comma, parenthesis, or a leading blank or
1187 newline. This rule applies recursively for every macro
1188 call, including macros called from other macros. For more details on
1189 quoting rules, see @ref{Programming in M4}.
1194 AC_CHECK_HEADER([stdio.h],
1195 [AC_DEFINE([HAVE_STDIO_H], [1],
1196 [Define to 1 if you have <stdio.h>.])],
1197 [AC_MSG_ERROR([sorry, can't do anything for you])])
1201 is quoted properly. You may safely simplify its quotation to:
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 because @samp{1} cannot contain a macro call. Here, the argument of
1212 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1213 interpreted as an argument separator. Also, the second and third arguments
1214 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1215 macro calls. The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1216 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1217 if you unwisely defined a macro with a name like @samp{Define} or
1218 @samp{stdio} then they would need quoting. Cautious Autoconf users
1219 would keep the quotes, but many Autoconf users find such precautions
1220 annoying, and would rewrite the example as follows:
1223 AC_CHECK_HEADER(stdio.h,
1224 [AC_DEFINE(HAVE_STDIO_H, 1,
1225 [Define to 1 if you have <stdio.h>.])],
1226 [AC_MSG_ERROR([sorry, can't do anything for you])])
1230 This is safe, so long as you adopt good naming conventions and do not
1231 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1232 @samp{h}. Though it is also safe here to omit the quotes around
1233 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1234 message strings are more likely to inadvertently contain commas.
1236 The following example is wrong and dangerous, as it is underquoted:
1239 AC_CHECK_HEADER(stdio.h,
1240 AC_DEFINE(HAVE_STDIO_H, 1,
1241 Define to 1 if you have <stdio.h>.),
1242 AC_MSG_ERROR([sorry, can't do anything for you]))
1245 In other cases, you may want to use text that also resembles a macro
1246 call. You must quote that text (whether just the potential problem, or
1247 the entire line) even when it is not passed as a macro argument; and you
1248 may also have to use @code{m4_pattern_allow} (@pxref{Forbidden
1249 Patterns}), to declare your intention that the resulting configure file
1250 will have a literal that resembles what would otherwise be reserved for
1251 a macro name. For example:
1254 dnl Simulate a possible future autoconf macro
1255 m4_define([AC_DC], [oops])
1257 echo "Hard rock was here! --AC_DC"
1258 dnl Correctly quoted:
1259 m4_pattern_allow([AC_DC])
1260 echo "Hard rock was here! --[AC_DC]"
1261 [echo "Hard rock was here! --AC_DC"]
1265 which results in this text in @file{configure}:
1268 echo "Hard rock was here! --oops"
1269 echo "Hard rock was here! --AC_DC"
1270 echo "Hard rock was here! --AC_DC"
1274 When you use the same text in a macro argument, you must therefore have
1275 an extra quotation level (since one is stripped away by the macro
1276 substitution). In general, then, it is a good idea to @emph{use double
1277 quoting for all literal string arguments}, either around just the
1278 problematic portions, or over the entire argument:
1281 m4_pattern_allow([AC_DC])
1282 AC_MSG_WARN([[AC_DC] stinks --Iron Maiden])
1283 AC_MSG_WARN([[AC_DC stinks --Iron Maiden]])
1286 It is also possible to avoid the problematic patterns in the first
1287 place, by the use of additional escaping (either a quadrigraph, or
1288 creative shell constructs), in which case it is no longer necessary to
1289 use @code{m4_pattern_allow}:
1292 echo "Hard rock was here! --AC""_DC"
1293 AC_MSG_WARN([[AC@@&t@@_DC stinks --Iron Maiden]])
1296 You are now able to understand one of the constructs of Autoconf that
1297 has been continually misunderstood@enddots{} The rule of thumb is that
1298 @emph{whenever you expect macro expansion, expect quote expansion};
1299 i.e., expect one level of quotes to be lost. For instance:
1302 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1303 [AC_MSG_ERROR([you lose])])
1307 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1308 @samp{char b[10];} and is expanded once, which results in
1309 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1310 to being passed to @code{AC_COMPILE_IFELSE}. (There was an idiom common
1311 in Autoconf's past to
1312 address this issue via the M4 @code{changequote} primitive, but do not
1313 use it!) Let's take a closer look: the author meant the first argument
1314 to be understood as a literal, and therefore it must be quoted twice;
1315 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1316 once so that it is only expanded after the rest of the body of
1317 @code{AC_COMPILE_IFELSE} is in place:
1320 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1321 [AC_MSG_ERROR([you lose])])
1325 Voilà , you actually produce @samp{char b[10];} this time!
1327 On the other hand, descriptions (e.g., the last parameter of
1328 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1329 are subject to line breaking, for example---and should not be double quoted.
1330 Even if these descriptions are short and are not actually broken, double
1331 quoting them yields weird results.
1333 Some macros take optional arguments, which this documentation represents
1334 as @ovar{arg} (not to be confused with the quote characters). You may
1335 just leave them empty, or use @samp{[]} to make the emptiness of the
1336 argument explicit, or you may simply omit the trailing commas. The
1337 three lines below are equivalent:
1340 AC_CHECK_HEADERS([stdio.h], [], [], [])
1341 AC_CHECK_HEADERS([stdio.h],,,)
1342 AC_CHECK_HEADERS([stdio.h])
1345 It is best to put each macro call on its own line in
1346 @file{configure.ac}. Most of the macros don't add extra newlines; they
1347 rely on the newline after the macro call to terminate the commands.
1348 This approach makes the generated @command{configure} script a little
1349 easier to read by not inserting lots of blank lines. It is generally
1350 safe to set shell variables on the same line as a macro call, because
1351 the shell allows assignments without intervening newlines.
1353 You can include comments in @file{configure.ac} files by starting them
1354 with the @samp{#}. For example, it is helpful to begin
1355 @file{configure.ac} files with a line like this:
1358 # Process this file with autoconf to produce a configure script.
1361 @node Autoconf Input Layout
1362 @subsection Standard @file{configure.ac} Layout
1364 The order in which @file{configure.ac} calls the Autoconf macros is not
1365 important, with a few exceptions. Every @file{configure.ac} must
1366 contain a call to @code{AC_INIT} before the checks, and a call to
1367 @code{AC_OUTPUT} at the end (@pxref{Output}). Additionally, some macros
1368 rely on other macros having been called first, because they check
1369 previously set values of some variables to decide what to do. These
1370 macros are noted in the individual descriptions (@pxref{Existing
1371 Tests}), and they also warn you when @command{configure} is created if they
1372 are called out of order.
1374 To encourage consistency, here is a suggested order for calling the
1375 Autoconf macros. Generally speaking, the things near the end of this
1376 list are those that could depend on things earlier in it. For example,
1377 library functions could be affected by types and libraries.
1381 Autoconf requirements
1382 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1383 information on the package
1385 checks for libraries
1386 checks for header files
1388 checks for structures
1389 checks for compiler characteristics
1390 checks for library functions
1391 checks for system services
1392 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1398 @node autoscan Invocation
1399 @section Using @command{autoscan} to Create @file{configure.ac}
1400 @cindex @command{autoscan}
1402 The @command{autoscan} program can help you create and/or maintain a
1403 @file{configure.ac} file for a software package. @command{autoscan}
1404 examines source files in the directory tree rooted at a directory given
1405 as a command line argument, or the current directory if none is given.
1406 It searches the source files for common portability problems and creates
1407 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1408 for that package, and checks a possibly existing @file{configure.ac} for
1411 When using @command{autoscan} to create a @file{configure.ac}, you
1412 should manually examine @file{configure.scan} before renaming it to
1413 @file{configure.ac}; it probably needs some adjustments.
1414 Occasionally, @command{autoscan} outputs a macro in the wrong order
1415 relative to another macro, so that @command{autoconf} produces a warning;
1416 you need to move such macros manually. Also, if you want the package to
1417 use a configuration header file, you must add a call to
1418 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}). You might
1419 also have to change or add some @code{#if} directives to your program in
1420 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1421 information about a program that can help with that job).
1423 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1424 consider adding its suggestions. The file @file{autoscan.log}
1425 contains detailed information on why a macro is requested.
1427 @command{autoscan} uses several data files (installed along with Autoconf)
1428 to determine which macros to output when it finds particular symbols in
1429 a package's source files. These data files all have the same format:
1430 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1431 output if that symbol is encountered. Lines starting with @samp{#} are
1434 @command{autoscan} accepts the following options:
1439 Print a summary of the command line options and exit.
1443 Print the version number of Autoconf and exit.
1447 Print the names of the files it examines and the potentially interesting
1448 symbols it finds in them. This output can be voluminous.
1452 Don't remove temporary files.
1454 @item --include=@var{dir}
1456 Append @var{dir} to the include path. Multiple invocations accumulate.
1458 @item --prepend-include=@var{dir}
1460 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1463 @node ifnames Invocation
1464 @section Using @command{ifnames} to List Conditionals
1465 @cindex @command{ifnames}
1467 @command{ifnames} can help you write @file{configure.ac} for a software
1468 package. It prints the identifiers that the package already uses in C
1469 preprocessor conditionals. If a package has already been set up to have
1470 some portability, @command{ifnames} can thus help you figure out what its
1471 @command{configure} needs to check for. It may help fill in some gaps in a
1472 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1475 @command{ifnames} scans all of the C source files named on the command line
1476 (or the standard input, if none are given) and writes to the standard
1477 output a sorted list of all the identifiers that appear in those files
1478 in @code{#if}, @code{#ifdef}, @code{#ifndef}, @code{#elif},
1479 @code{#elifdef}, or @code{#elifndef} directives.
1480 It prints each identifier on a line, followed by a
1481 space-separated list of the files in which that identifier occurs.
1484 @command{ifnames} accepts the following options:
1489 Print a summary of the command line options and exit.
1493 Print the version number of Autoconf and exit.
1496 @node autoconf Invocation
1497 @section Using @command{autoconf} to Create @command{configure}
1498 @cindex @command{autoconf}
1500 To create @command{configure} from @file{configure.ac}, run the
1501 @command{autoconf} program with no arguments. @command{autoconf} processes
1502 @file{configure.ac} with the M4 macro processor, using the
1503 Autoconf macros. If you give @command{autoconf} an argument, it reads that
1504 file instead of @file{configure.ac} and writes the configuration script
1505 to the standard output instead of to @command{configure}. If you give
1506 @command{autoconf} the argument @option{-}, it reads from the standard
1507 input instead of @file{configure.ac} and writes the configuration script
1508 to the standard output.
1510 The Autoconf macros are defined in several files. Some of the files are
1511 distributed with Autoconf; @command{autoconf} reads them first. Then it
1512 looks for the optional file @file{acsite.m4} in the directory that
1513 contains the distributed Autoconf macro files, and for the optional file
1514 @file{aclocal.m4} in the current directory. Those files can contain
1515 your site's or the package's own Autoconf macro definitions
1516 (@pxref{Writing Autoconf Macros}, for more information). If a macro is
1517 defined in more than one of the files that @command{autoconf} reads, the
1518 last definition it reads overrides the earlier ones.
1520 @command{autoconf} accepts the following options:
1525 Print a summary of the command line options and exit.
1529 Print the version number of Autoconf and exit.
1533 Report processing steps.
1537 Don't remove the temporary files.
1541 Remake @file{configure} even if newer than its input files.
1543 @item --include=@var{dir}
1545 Append @var{dir} to the include path. Multiple invocations accumulate.
1547 @item --prepend-include=@var{dir}
1549 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1551 @item --output=@var{file}
1552 @itemx -o @var{file}
1553 Save output (script or trace) to @var{file}. The file @option{-} stands
1554 for the standard output.
1556 @item --warnings=@var{category}[,@var{category}...]
1557 @itemx -W@var{category}[,@var{category}...]
1559 Enable or disable warnings related to each @var{category}.
1560 @xref{m4_warn}, for a comprehensive list of categories.
1561 Special values include:
1565 Enable all categories of warnings.
1568 Disable all categories of warnings.
1571 Treat all warnings as errors.
1573 @item no-@var{category}
1574 Disable warnings falling into @var{category}.
1577 The environment variable @env{WARNINGS} may also be set to a
1578 comma-separated list of warning categories to enable or disable.
1579 It is interpreted exactly the same way as the argument of
1580 @option{--warnings}, but unknown categories are silently ignored.
1581 The command line takes precedence; for instance, if @env{WARNINGS}
1582 is set to @code{obsolete}, but @option{-Wnone} is given on the
1583 command line, no warnings will be issued.
1585 Some categories of warnings are on by default.
1586 Again, for details see @ref{m4_warn}.
1588 @item --trace=@var{macro}[:@var{format}]
1589 @itemx -t @var{macro}[:@var{format}]
1590 Do not create the @command{configure} script, but list the calls to
1591 @var{macro} according to the @var{format}. Multiple @option{--trace}
1592 arguments can be used to list several macros. Multiple @option{--trace}
1593 arguments for a single macro are not cumulative; instead, you should
1594 just make @var{format} as long as needed.
1596 The @var{format} is a regular string, with newlines if desired, and
1597 several special escape codes. It defaults to @samp{$f:$l:$n:$%}; see
1598 @ref{autom4te Invocation}, for details on the @var{format}.
1600 @item --initialization
1602 By default, @option{--trace} does not trace the initialization of the
1603 Autoconf macros (typically the @code{AC_DEFUN} definitions). This
1604 results in a noticeable speedup, but can be disabled by this option.
1608 It is often necessary to check the content of a @file{configure.ac}
1609 file, but parsing it yourself is extremely fragile and error-prone. It
1610 is suggested that you rely upon @option{--trace} to scan
1611 @file{configure.ac}. For instance, to find the list of variables that
1612 are substituted, use:
1616 $ @kbd{autoconf -t AC_SUBST}
1617 configure.ac:28:AC_SUBST:SHELL
1618 configure.ac:28:AC_SUBST:PATH_SEPARATOR
1619 @i{More traces deleted}
1624 The example below highlights the difference between @samp{$@@},
1625 @samp{$*}, and @samp{$%}.
1629 $ @kbd{cat configure.ac}
1630 AC_DEFINE(This, is, [an
1632 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1639 %: This:is:an [example]
1644 The @var{format} gives you a lot of freedom:
1648 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1649 $ac_subst@{"SHELL"@} = "configure.ac:28";
1650 $ac_subst@{"PATH_SEPARATOR"@} = "configure.ac:28";
1651 @i{More traces deleted}
1656 A long @var{separator} can be used to improve the readability of complex
1657 structures, and to ease their parsing (for instance when no single
1658 character is suitable as a separator):
1662 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1663 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1664 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1665 AUTOMAKE|:::::|automake|:::::|$missing_dir
1666 @i{More traces deleted}
1670 @node autoreconf Invocation
1671 @section Using @command{autoreconf} to Update @command{configure} Scripts
1672 @cindex @command{autoreconf}
1674 Installing the various components of the GNU Build System can be
1675 tedious: running @command{autopoint} for Gettext, @command{automake} for
1676 @file{Makefile.in} etc.@: in each directory. It may be needed either
1677 because some tools such as @command{automake} have been updated on your
1678 system, or because some of the sources such as @file{configure.ac} have
1679 been updated, or finally, simply in order to install the GNU Build
1680 System in a fresh tree.
1682 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1683 @command{aclocal}, @command{automake}, @command{libtoolize}, @command{intltoolize},
1684 @command{gtkdocize}, and @command{autopoint} (when appropriate) repeatedly
1685 to update the GNU Build System in the specified directories and their
1686 subdirectories (@pxref{Subdirectories}). By default, it only remakes
1687 those files that are older than their sources. The environment variables
1688 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1689 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{INTLTOOLIZE}, @env{GTKDOCIZE}, @env{M4},
1690 and @env{MAKE} may be used to override the invocation of the respective tools.
1692 If you install a new version of some tool, you can make
1693 @command{autoreconf} remake @emph{all} of the files by giving it the
1694 @option{--force} option.
1696 @xref{Automatic Remaking}, for Make rules to automatically
1697 rebuild @command{configure} scripts when their source files change. That
1698 method handles the timestamps of configuration header templates
1699 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1700 @option{--localdir=@var{dir}}.
1703 @cindex @command{autopoint}
1704 Gettext supplies the @command{autopoint} command to add translation
1705 infrastructure to a source package. If you use @command{autopoint},
1706 your @file{configure.ac} should invoke @code{AM_GNU_GETTEXT} and
1707 one of @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})} or
1708 @code{AM_GNU_GETTEXT_REQUIRE_VERSION(@var{min-gettext-version})}.
1709 @xref{autopoint Invocation, , Invoking the @code{autopoint} Program,
1710 gettext, GNU @code{gettext} utilities}, for further details.
1713 @command{autoreconf} accepts the following options:
1718 Print a summary of the command line options and exit.
1722 Print the version number of Autoconf and exit.
1726 Print the name of each directory @command{autoreconf} examines and the
1727 commands it runs. If given two or more times, pass @option{--verbose}
1728 to subordinate tools that support it.
1732 Don't remove the temporary files.
1736 Consider all generated and standard auxiliary files to be obsolete.
1737 This remakes even @file{configure} scripts and configuration headers
1738 that are newer than their input files (@file{configure.ac} and, if
1739 present, @file{aclocal.m4}).
1741 If deemed appropriate, this option triggers calls to @samp{automake
1742 --force-missing}. Passing both @option{--force} and @option{--install}
1743 to @command{autoreconf} will in turn undo any customizations to standard
1744 files. Note that the macro @code{AM_INIT_AUTOMAKE} has some options
1745 which change the set of files considered to be standard.
1749 Install any missing standard auxiliary files in the package. By
1750 default, files are copied; this can be changed with @option{--symlink}.
1752 If deemed appropriate, this option triggers calls to
1753 @samp{automake --add-missing},
1754 @samp{libtoolize}, @samp{autopoint}, etc.
1756 @item --no-recursive
1757 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1758 macro @code{AC_CONFIG_SUBDIRS}).
1762 When used with @option{--install}, install symbolic links to the missing
1763 auxiliary files instead of copying them.
1767 When the directories were configured, update the configuration by
1768 running @samp{./config.status --recheck && ./config.status}, and then
1771 @item --include=@var{dir}
1773 Append @var{dir} to the include path. Multiple invocations accumulate.
1774 Passed on to @command{aclocal}, @command{autoconf} and
1775 @command{autoheader} internally.
1777 @item --prepend-include=@var{dir}
1779 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1780 Passed on to @command{autoconf} and @command{autoheader} internally.
1782 @item --warnings=@var{category}[,@var{category}...]
1783 @itemx -W@var{category}[,@var{category}...]
1785 Enable or disable warnings related to each @var{category}.
1786 @xref{m4_warn}, for a comprehensive list of categories.
1787 Special values include:
1791 Enable all categories of warnings.
1794 Disable all categories of warnings.
1797 Treat all warnings as errors.
1799 @item no-@var{category}
1800 Disable warnings falling into @var{category}.
1803 The environment variable @env{WARNINGS} may also be set to a
1804 comma-separated list of warning categories to enable or disable.
1805 It is interpreted exactly the same way as the argument of
1806 @option{--warnings}, but unknown categories are silently ignored.
1807 The command line takes precedence; for instance, if @env{WARNINGS}
1808 is set to @code{obsolete}, but @option{-Wnone} is given on the
1809 command line, no warnings will be issued.
1811 Some categories of warnings are on by default.
1812 Again, for details see @ref{m4_warn}.
1815 If you want @command{autoreconf} to pass flags that are not listed here
1816 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1817 Due to a limitation in the Autoconf implementation these flags currently
1818 must be set on a single line in @file{Makefile.am}, without any
1819 backslash-newlines or makefile comments.
1820 Also, be aware that future Automake releases might
1821 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1824 @c ========================================= Initialization and Output Files.
1827 @chapter Initialization and Output Files
1829 Autoconf-generated @command{configure} scripts need some information about
1830 how to initialize, such as how to find the package's source files and
1831 about the output files to produce. The following sections describe the
1832 initialization and the creation of output files.
1835 * Initializing configure:: Option processing etc.
1836 * Versioning:: Dealing with Autoconf versions
1837 * Notices:: Copyright, version numbers in @command{configure}
1838 * Input:: Where Autoconf should find files
1839 * Output:: Outputting results from the configuration
1840 * Configuration Actions:: Preparing the output based on results
1841 * Configuration Files:: Creating output files
1842 * Makefile Substitutions:: Using output variables in makefiles
1843 * Configuration Headers:: Creating a configuration header file
1844 * Configuration Commands:: Running arbitrary instantiation commands
1845 * Configuration Links:: Links depending on the configuration
1846 * Subdirectories:: Configuring independent packages together
1847 * Default Prefix:: Changing the default installation prefix
1850 @node Initializing configure
1851 @section Initializing @command{configure}
1853 Every @command{configure} script must call @code{AC_INIT} before doing
1854 anything else that produces output. Calls to silent macros, such as
1855 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1856 are generally used via @file{aclocal.m4}, since that is implicitly
1857 included before the start of @file{configure.ac}. The only other
1858 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1861 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1862 @ovar{tarname}, @ovar{url})
1864 Process any command-line arguments and perform initialization
1867 Set the name of the @var{package} and its @var{version}. These are
1868 typically used in @option{--version} support, including that of
1869 @command{configure}. The optional argument @var{bug-report} should be
1870 the email to which users should send bug reports. The package
1871 @var{tarname} differs from @var{package}: the latter designates the full
1872 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1873 distribution tar ball names (e.g., @samp{autoconf}). It defaults to
1874 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1875 other than alphanumerics and underscores are changed to @samp{-}. If
1876 provided, @var{url} should be the home page for the package.
1878 Leading and trailing whitespace is stripped from all the arguments to
1879 @code{AC_INIT}, and interior whitespace is collapsed to a single space.
1880 This means that, for instance, if you want to put several email
1881 addresses in @var{bug-report}, you can put each one on its own line:
1885 # We keep having problems with the mail hosting for
1886 # gnomovision.example, so give people an alternative.
1887 AC_INIT([Gnomovision], [17.0.1], [
1888 bugs@@gnomovision.example
1889 or gnomo-bugs@@reliable-email.example
1894 The arguments to @code{AC_INIT} may be computed by M4, when
1895 @command{autoconf} is run. For instance, if you want to include the
1896 package's version number in the @var{tarname}, but you don't want to
1897 repeat it, you can use a helper macro:
1901 m4_define([gnomo_VERSION], [17.0.1])
1902 AC_INIT([Gnomovision],
1903 m4_defn([gnomo_VERSION]),
1904 [bugs@@gnomovision.example],
1905 [gnomo-]m4_defn([gnomo_VERSION]))
1909 This uses @code{m4_defn} to produce the expansion of
1910 @code{gnomo_VERSION} @emph{as a quoted string}, so that if there happen
1911 to be any more M4 macro names in @code{gnomo_VERSION}, they will not be
1912 expanded. @xref{Defn,,Renaming Macros,m4,GNU m4 macro processor}.
1914 Continuing this example, if you don't want to embed the version number
1915 in @file{configure.ac} at all, you can use @code{m4_esyscmd} to look it
1916 up somewhere else when @command{autoconf} is run:
1920 m4_define([gnomo_VERSION],
1921 m4_esyscmd([build-aux/git-version-gen .tarball-version]))
1922 AC_INIT([Gnomovision],
1923 m4_defn([gnomo_VERSION]),
1924 [bugs@@gnomovision.example],
1925 [gnomo-]m4_defn([gnomo_VERSION]))
1929 This uses the utility script @command{git-version-gen} to look up
1930 the package's version in its version control metadata. This script
1931 is part of Gnulib (@pxref{Gnulib}).
1933 The arguments to @code{AC_INIT} are written into @file{configure} in
1934 several different places. Therefore, we strongly recommend that you
1935 write any M4 logic in @code{AC_INIT} arguments to be evaluated
1936 @emph{before} @code{AC_INIT} itself is evaluated. For instance, in the
1937 above example, the second argument to @code{m4_define} is @emph{not}
1938 quoted, so the @code{m4_esyscmd} is evaluated only once, and
1939 @code{gnomo_VERSION} is defined to the output of the command. If the
1940 second argument to @code{m4_define} were quoted, @code{m4_esyscmd} would
1941 be evaluated each time the @var{version} or @var{tarname} arguments were
1942 written to @file{configure}, and the command would be run repeatedly.
1944 In some of the places where the arguments to @code{AC_INIT} are used,
1945 within @file{configure}, shell evaluation cannot happen. Therefore, the
1946 arguments to @code{AC_INIT} may @emph{not} be computed when
1947 @command{configure} is run. If they contain any construct that isn't
1948 always treated as literal by the shell (e.g.@: variable expansions),
1949 @command{autoconf} will issue an error.
1951 The @var{tarname} argument is used to construct filenames. It should
1952 not contain wildcard characters, white space, or anything else that
1953 could be troublesome as part of a file or directory name.
1955 Some of M4's active characters (notably parentheses, square brackets,
1956 @samp{,} and @samp{#}) commonly appear in URLs and lists of email
1957 addresses. If any of these characters appear in an argument to AC_INIT,
1958 that argument will probably need to be double-quoted to avoid errors
1959 and mistranscriptions. @xref{M4 Quotation}.
1961 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1962 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1963 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1966 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1967 @acindex{PACKAGE_NAME}
1968 @ovindex PACKAGE_NAME
1969 @cvindex PACKAGE_NAME
1970 Exactly @var{package}.
1972 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1973 @acindex{PACKAGE_TARNAME}
1974 @ovindex PACKAGE_TARNAME
1975 @cvindex PACKAGE_TARNAME
1976 Exactly @var{tarname}, possibly generated from @var{package}.
1978 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1979 @acindex{PACKAGE_VERSION}
1980 @ovindex PACKAGE_VERSION
1981 @cvindex PACKAGE_VERSION
1982 Exactly @var{version}.
1984 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1985 @acindex{PACKAGE_STRING}
1986 @ovindex PACKAGE_STRING
1987 @cvindex PACKAGE_STRING
1988 Exactly @samp{@var{package} @var{version}}.
1990 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1991 @acindex{PACKAGE_BUGREPORT}
1992 @ovindex PACKAGE_BUGREPORT
1993 @cvindex PACKAGE_BUGREPORT
1994 Exactly @var{bug-report}, if one was provided. Typically an email
1995 address, or URL to a bug management web page.
1997 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1998 @acindex{PACKAGE_URL}
1999 @ovindex PACKAGE_URL
2000 @cvindex PACKAGE_URL
2001 Exactly @var{url}, if one was provided. If @var{url} was empty, but
2002 @var{package} begins with @samp{GNU }, then this defaults to
2003 @samp{https://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
2008 If your @command{configure} script does its own option processing, it
2009 should inspect @samp{$@@} or @samp{$*} immediately after calling
2010 @code{AC_INIT}, because other Autoconf macros liberally use the
2011 @command{set} command to process strings, and this has the side effect
2012 of updating @samp{$@@} and @samp{$*}. However, we suggest that you use
2013 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
2014 implement your own option processing. @xref{Site Configuration}.
2017 @section Dealing with Autoconf versions
2018 @cindex Autoconf version
2019 @cindex version, Autoconf
2021 The following optional macros can be used to help choose the minimum
2022 version of Autoconf that can successfully compile a given
2023 @file{configure.ac}.
2025 @defmac AC_PREREQ (@var{version})
2028 Ensure that a recent enough version of Autoconf is being used. If the
2029 version of Autoconf being used to create @command{configure} is
2030 earlier than @var{version}, print an error message to the standard
2031 error output and exit with failure (exit status is 63). For example:
2034 AC_PREREQ([@value{VERSION}])
2037 This macro may be used before @code{AC_INIT}.
2040 @defmac AC_AUTOCONF_VERSION
2041 @acindex{AUTOCONF_VERSION}
2042 This macro was introduced in Autoconf 2.62. It identifies the version
2043 of Autoconf that is currently parsing the input file, in a format
2044 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
2045 other words, for this release of Autoconf, its value is
2046 @samp{@value{VERSION}}. One potential use of this macro is for writing
2047 conditional fallbacks based on when a feature was added to Autoconf,
2048 rather than using @code{AC_PREREQ} to require the newer version of
2049 Autoconf. However, remember that the Autoconf philosophy favors feature
2050 checks over version checks.
2052 You should not expand this macro directly; use
2053 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead. This is because some
2055 have a beta version of Autoconf installed, with arbitrary letters
2056 included in its version string. This means it is possible for the
2057 version string to contain the name of a defined macro, such that
2058 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
2059 macro during rescanning, and change the version string to be different
2060 than what you intended to check.
2064 @section Notices in @command{configure}
2065 @cindex Notices in @command{configure}
2067 The following macros manage version numbers for @command{configure}
2068 scripts. Using them is optional.
2070 @defmac AC_COPYRIGHT (@var{copyright-notice})
2072 @cindex Copyright Notice
2073 State that, in addition to the Free Software Foundation's copyright on
2074 the Autoconf macros, parts of your @command{configure} are covered by the
2075 @var{copyright-notice}.
2077 The @var{copyright-notice} shows up in both the head of
2078 @command{configure} and in @samp{configure --version}.
2082 @defmac AC_REVISION (@var{revision-info})
2085 Copy revision stamp @var{revision-info} into the @command{configure}
2086 script, with any dollar signs or double-quotes removed. This macro lets
2087 you put a revision stamp from @file{configure.ac} into @command{configure}
2088 that the traditional version control systems RCS and CVS can update,
2089 without these systems changing it again when you check in the resulting
2090 @command{configure}. That way, you can determine easily which revision of
2091 @file{configure.ac} a particular @command{configure} corresponds to.
2093 For example, this line in @file{configure.ac}:
2096 AC_REVISION([$Revision: 1.30 $])
2100 produces this in @command{configure}:
2104 # From configure.ac Revision: 1.30
2110 @section Configure Input: Source Code, Macros, and Auxiliary Files
2112 The following macros help you manage the contents of your source tree.
2114 @anchor{AC_CONFIG_SRCDIR}
2115 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2116 @acindex{CONFIG_SRCDIR}
2117 Distinguish this package's source directory from other source
2118 directories that might happen to exist in the file system.
2119 @var{unique-file-in-source-dir} should name a file that is unique to
2120 this package. @command{configure} will verify that this file exists in
2121 @file{@var{srcdir}}, before it runs any other checks.
2123 Use of this macro is strongly recommended. It protects against people
2124 accidentally specifying the wrong directory with @option{--srcdir}.
2125 @xref{configure Invocation}, for more information.
2128 Packages that use @command{aclocal} to generate @file{aclocal.m4}
2129 should declare where local macros can be found using
2130 @code{AC_CONFIG_MACRO_DIRS}.
2132 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2133 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2134 @acindex{CONFIG_MACRO_DIRS}
2135 @acindex{CONFIG_MACRO_DIR}
2136 @acindex{CONFIG_MACRO_DIR_TRACE}
2137 Specify the given directories as the location of additional local Autoconf
2138 macros. These macros are intended for use by commands like
2139 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2140 be called directly from @file{configure.ac} so that tools that install
2141 macros for @command{aclocal} can find the macros' declarations. Tools
2142 that want to learn which directories have been selected should trace
2143 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2145 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2146 times and with multiple arguments; in such cases, directories in earlier
2147 calls are expected to be searched before directories in later calls, and
2148 directories appearing in the same call are expected to be searched in
2149 the order in which they appear in the call. For historical reasons, the
2150 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2151 for tools such as older @command{libtool} that weren't prepared to
2152 handle multiple directories. For example, a usage like
2155 AC_CONFIG_MACRO_DIR([dir1])
2156 AC_CONFIG_MACRO_DIRS([dir2])
2157 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2160 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2161 and should cause the directories to be searched in this order:
2162 @samp{dir1 dir2 dir3 dir4}.
2164 Note that if you use @command{aclocal} from an Automake release prior to
2165 1.13 to generate @file{aclocal.m4}, you must also set
2166 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2167 in your top-level @file{Makefile.am}. Due to a limitation in
2168 the Autoconf implementation of @command{autoreconf}, these include
2169 directives currently must be set on a single line in @file{Makefile.am},
2170 without any backslash-newlines or makefile comments.
2173 @prindex @command{config.guess}
2174 @prindex @command{config.sub}
2175 @prindex @command{install-sh}
2177 Some Autoconf macros require auxiliary scripts. @code{AC_PROG_INSTALL}
2178 (@pxref{Particular Programs}) requires a
2179 fallback implementation of @command{install} called @file{install-sh},
2180 and the @code{AC_CANONICAL} macros (@pxref{Manual Configuration})
2181 require the system-identification scripts @file{config.sub} and
2182 @file{config.guess}. Third-party tools, such as Automake and Libtool,
2183 may require additional auxiliary scripts.
2185 By default, @command{configure} looks for these scripts next to itself,
2186 in @file{@var{srcdir}}. For convenience when working with subdirectories
2187 with their own configure scripts (@pxref{Subdirectories}), if the
2188 scripts are not in @file{@var{srcdir}} it will also look in
2189 @file{@var{srcdir}/..} and @file{@var{srcdir}/../..}. All of the
2190 scripts must be found in the same directory.
2192 If these default locations are not adequate, or simply to reduce clutter
2193 at the top level of the source tree, packages can use
2194 @code{AC_CONFIG_AUX_DIR} to declare where to look for auxiliary scripts.
2196 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2197 @acindex{CONFIG_AUX_DIR}
2198 Look for auxiliary scripts in @var{dir}. Normally, @var{dir} should be a
2199 relative path, which is taken as relative to @file{@var{srcdir}}.
2200 If @var{dir} is an absolute path or contains shell variables, however,
2203 When the goal of using @code{AC_CONFIG_AUX_DIR} is to reduce clutter at
2204 the top level of the source tree, the conventional name for @var{dir} is
2205 @file{build-aux}. If you need portability to DOS variants, do not name
2206 the auxiliary directory @file{aux}. @xref{File System Conventions}.
2209 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2210 @acindex{REQUIRE_AUX_FILE}
2212 Declare that @var{file} is an auxiliary script needed by this configure
2213 script, and set the shell variable @code{ac_aux_dir} to the directory
2214 where it can be found. The value of @code{ac_aux_dir} is guaranteed to
2215 end with a @samp{/}.
2217 Macros that need auxiliary scripts must use this macro to register each
2221 @command{configure} checks for all the auxiliary scripts it needs on
2222 startup, and exits with an error if any are missing.
2224 @command{autoreconf} also detects missing auxiliary scripts. When used
2225 with the @option{--install} option, @command{autoreconf} will try to add
2226 missing scripts to the directory specified by @code{AC_CONFIG_AUX_DIR},
2227 or to the top level of the source tree if @code{AC_CONFIG_AUX_DIR} was
2228 not used. It can always do this for the scripts needed by Autoconf core
2229 macros: @file{install-sh}, @file{config.sub}, and @file{config.guess}.
2230 Many other commonly-needed scripts are installed by the third-party
2231 tools that @command{autoreconf} knows how to run, such as @file{missing}
2232 for Automake and @file{ltmain.sh} for Libtool.
2234 If you are using Automake, auxiliary scripts will automatically be
2235 included in the tarball created by @command{make dist}. If you are
2236 not using Automake you will need to arrange for auxiliary scripts to
2237 be included in tarballs yourself. Auxiliary scripts should normally
2238 @emph{not} be checked into a version control system, for the same
2239 reasons that @command{configure} shouldn't be.
2241 The scripts needed by Autoconf core macros can be found in
2242 @file{$(datadir)/autoconf/build-aux} of the Autoconf installation
2243 (@pxref{Installation Directory Variables}).
2244 @file{install-sh} can be downloaded from
2245 @url{https://git.savannah.gnu.org/cgit/automake.git/plain/lib/install-sh}.
2246 @file{config.sub} and @file{config.guess} can be downloaded from
2247 @url{https://git.savannah.gnu.org/cgit/config.git/tree/}.
2250 @section Outputting Files
2251 @cindex Outputting files
2253 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2254 calling @code{AC_OUTPUT}. That is the macro that generates and runs
2255 @file{config.status}, which in turn creates the makefiles and any
2256 other files resulting from configuration. This is the only required
2257 macro besides @code{AC_INIT} (@pxref{Input}).
2262 @cindex Instantiation
2263 Generate @file{config.status} and launch it. Call this macro once, at
2264 the end of @file{configure.ac}.
2266 @file{config.status} performs all the configuration actions: all the
2267 output files (see @ref{Configuration Files}, macro
2268 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2269 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2270 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2271 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2272 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2275 The location of your @code{AC_OUTPUT} invocation is the exact point
2276 where configuration actions are taken: any code afterwards is
2277 executed by @command{configure} once @command{config.status} was run. If
2278 you want to bind actions to @command{config.status} itself
2279 (independently of whether @command{configure} is being run), see
2280 @ref{Configuration Commands, , Running Arbitrary Configuration
2284 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2285 @xref{Obsolete Macros}, for a description of the arguments that
2286 @code{AC_OUTPUT} used to support.
2289 If you run @command{make} in subdirectories, you should run it using the
2290 @command{make} variable @code{MAKE}. Most versions of @command{make} set
2291 @code{MAKE} to the name of the @command{make} program plus any options it
2292 was given. (But many do not include in it the values of any variables
2293 set on the command line, so those are not passed on automatically.)
2294 Some old versions of @command{make} do not set this variable. The
2295 following macro allows you to use it even with those versions.
2297 @anchor{AC_PROG_MAKE_SET}
2298 @defmac AC_PROG_MAKE_SET
2299 @acindex{PROG_MAKE_SET}
2301 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2302 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2303 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2304 @code{$(MAKE)}, such as @samp{MAKE=make}. Calls @code{AC_SUBST} for
2308 If you use this macro, place a line like this in each @file{Makefile.in}
2309 that runs @command{MAKE} on other directories:
2317 @node Configuration Actions
2318 @section Performing Configuration Actions
2319 @cindex Configuration actions
2321 @file{configure} is designed so that it appears to do everything itself,
2322 but there is actually a hidden slave: @file{config.status}.
2323 @file{configure} is in charge of examining your system, but it is
2324 @file{config.status} that actually takes the proper actions based on the
2325 results of @file{configure}. The most typical task of
2326 @file{config.status} is to @emph{instantiate} files.
2328 @acindex{CONFIG_@var{ITEMS}}
2329 This section describes the common behavior of the four standard
2330 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2331 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}. They all
2332 have this prototype:
2334 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2337 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2341 where the arguments are:
2345 A blank-or-newline-separated list of tags, which are typically the names of
2346 the files to instantiate.
2348 You are encouraged to use literals as @var{tags}. In particular, you
2352 AS_IF([@dots{}], [my_foos="$my_foos fooo"])
2353 AS_IF([@dots{}], [my_foos="$my_foos foooo"])
2354 AC_CONFIG_@var{ITEMS}([$my_foos])
2358 and use this instead:
2361 AS_IF([@dots{}], [AC_CONFIG_@var{ITEMS}([fooo])])
2362 AS_IF([@dots{}], [AC_CONFIG_@var{ITEMS}([foooo])])
2365 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2366 special @var{tag} values: they may have the form @samp{@var{output}} or
2367 @samp{@var{output}:@var{inputs}}. The file @var{output} is instantiated
2368 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2370 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2371 for example, asks for
2372 the creation of the file @file{Makefile} that contains the expansion of the
2373 output variables in the concatenation of @file{boiler/top.mk} and
2374 @file{boiler/bot.mk}.
2376 The special value @samp{-} might be used to denote the standard output
2377 when used in @var{output}, or the standard input when used in the
2378 @var{inputs}. You most probably don't need to use this in
2379 @file{configure.ac}, but it is convenient when using the command line
2380 interface of @file{./config.status}, see @ref{config.status Invocation},
2383 The @var{inputs} may be absolute or relative file names. In the latter
2384 case they are first looked for in the build tree, and then in the source
2385 tree. Input files should be text files, and a line length below 2000
2386 bytes should be safe.
2389 Shell commands output literally into @file{config.status}, and
2390 associated with a tag that the user can use to tell @file{config.status}
2391 which commands to run. The commands are run each time a @var{tag}
2392 request is given to @file{config.status}, typically each time the file
2393 @file{@var{tag}} is created.
2395 The variables set during the execution of @command{configure} are
2396 @emph{not} available here: you first need to set them via the
2397 @var{init-cmds}. Nonetheless the following variables are pre-computed:
2402 The name of the top source directory, assuming that the working
2403 directory is the top build directory. This
2404 is what @command{configure}'s @option{--srcdir} option sets.
2407 @vrindex ac_top_srcdir
2408 The name of the top source directory, assuming that the working
2409 directory is the current build directory.
2411 @item ac_top_build_prefix
2412 @vrindex ac_top_build_prefix
2413 The name of the top build directory, assuming that the working
2414 directory is the current build directory.
2415 It can be empty, or else ends with a slash, so that you may concatenate
2420 The name of the corresponding source directory, assuming that the
2421 working directory is the current build directory.
2425 The name of a temporary directory within the build tree, which you
2426 can use if you need to create additional temporary files. The
2427 directory is cleaned up when @command{config.status} is done or
2428 interrupted. Please use package-specific file name prefixes to
2429 avoid clashing with files that @command{config.status} may use
2434 The @dfn{current} directory refers to the directory (or
2435 pseudo-directory) containing the input part of @var{tags}. For
2439 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2443 with @option{--srcdir=../package} produces the following values:
2446 # Argument of --srcdir
2448 # Reversing deep/dir
2449 ac_top_build_prefix='../../'
2450 # Concatenation of $ac_top_build_prefix and srcdir
2451 ac_top_srcdir='../../../package'
2452 # Concatenation of $ac_top_srcdir and deep/dir
2453 ac_srcdir='../../../package/deep/dir'
2457 independently of @samp{in/in.in}.
2460 Shell commands output @emph{unquoted} near the beginning of
2461 @file{config.status}, and executed each time @file{config.status} runs
2462 (regardless of the tag). Because they are unquoted, for example,
2463 @samp{$var} is output as the value of @code{var}. @var{init-cmds}
2464 is typically used by @file{configure} to give @file{config.status} some
2465 variables it needs to run the @var{commands}.
2467 You should be extremely cautious in your variable names: all the
2468 @var{init-cmds} share the same name space and may overwrite each other
2469 in unpredictable ways. Sorry@enddots{}
2472 All these macros can be called multiple times, with different
2473 @var{tag} values, of course!
2476 @node Configuration Files
2477 @section Creating Configuration Files
2478 @cindex Creating configuration files
2479 @cindex Configuration file creation
2481 Be sure to read the previous section, @ref{Configuration Actions}.
2483 @anchor{AC_CONFIG_FILES}
2484 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2485 @acindex{CONFIG_FILES}
2486 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2487 file (by default @file{@var{file}.in}), substituting the output variable
2489 @c Before we used to have this feature, which was later rejected
2490 @c because it complicates the writing of makefiles:
2491 @c If the file would be unchanged, it is left untouched, to preserve
2493 This macro is one of the instantiating macros; see @ref{Configuration
2494 Actions}. @xref{Makefile Substitutions}, for more information on using
2495 output variables. @xref{Setting Output Variables}, for more information
2496 on creating them. This macro creates the directory that the file is in
2497 if it doesn't exist. Usually, makefiles are created this way,
2498 but other files, such as @file{.gdbinit}, can be specified as well.
2500 Typical calls to @code{AC_CONFIG_FILES} look like this:
2503 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2504 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2507 You can override an input file name by appending to @var{file} a
2508 colon-separated list of input files. Examples:
2511 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2512 [lib/Makefile:boiler/lib.mk])
2516 Doing this allows you to keep your file names acceptable to
2518 to prepend and/or append boilerplate to the file.
2520 The @var{file} names should not contain shell metacharacters.
2521 @xref{Special Chars in Variables}.
2526 @node Makefile Substitutions
2527 @section Substitutions in Makefiles
2528 @cindex Substitutions in makefiles
2529 @cindex Makefile substitutions
2531 Each subdirectory in a distribution that contains something to be
2532 compiled or installed should come with a file @file{Makefile.in}, from
2533 which @command{configure} creates a file @file{Makefile} in that directory.
2534 To create @file{Makefile}, @command{configure} performs a simple variable
2535 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2536 @file{Makefile.in} with the value that @command{configure} has determined
2537 for that variable. Variables that are substituted into output files in
2538 this way are called @dfn{output variables}. They are ordinary shell
2539 variables that are set in @command{configure}. To make @command{configure}
2540 substitute a particular variable into the output files, the macro
2541 @code{AC_SUBST} must be called with that variable name as an argument.
2542 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2543 left unchanged. @xref{Setting Output Variables}, for more information
2544 on creating output variables with @code{AC_SUBST}.
2546 A software package that uses a @command{configure} script should be
2547 distributed with a file @file{Makefile.in}, but no makefile; that
2548 way, the user has to properly configure the package for the local system
2549 before compiling it.
2551 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2552 GNU Coding Standards}, for more information on what to put in
2556 * Preset Output Variables:: Output variables that are always set
2557 * Installation Directory Variables:: Other preset output variables
2558 * Changed Directory Variables:: Warnings about @file{datarootdir}
2559 * Build Directories:: Supporting multiple concurrent compiles
2560 * Automatic Remaking:: Makefile rules for configuring
2563 @node Preset Output Variables
2564 @subsection Preset Output Variables
2565 @cindex Output variables
2567 Some output variables are preset by the Autoconf macros. Some of the
2568 Autoconf macros set additional output variables, which are mentioned in
2569 the descriptions for those macros. @xref{Output Variable Index}, for a
2570 complete list of output variables. @xref{Installation Directory
2571 Variables}, for the list of the preset ones related to installation
2572 directories. Below are listed the other preset ones, many of which are
2573 precious variables (@pxref{Setting Output Variables},
2576 The preset variables which are available during @file{config.status}
2577 (@pxref{Configuration Actions}) may also be used during
2578 @command{configure} tests. For example, it is permissible to reference
2579 @samp{$srcdir} when constructing a list of directories to pass via
2580 the @option{-I} option during a compiler feature check. When used in this
2581 manner, coupled with the fact that @command{configure} is always run
2582 from the top build directory, it is sufficient to use just
2583 @samp{$srcdir} instead of @samp{$top_srcdir}.
2585 @c Just say no to ASCII sorting! We're humans, not computers.
2586 @c These variables are listed as they would be in a dictionary:
2594 Debugging and optimization options for the C compiler. If it is not set
2595 in the environment when @command{configure} runs, the default value is set
2596 when you call @code{AC_PROG_CC} (or empty if you don't). @command{configure}
2597 uses this variable when compiling or linking programs to test for C features.
2599 If a compiler option affects only the behavior of the preprocessor
2600 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2601 instead. If it affects only the linker (e.g., @option{-L@var{directory}}),
2602 it should be put into @code{LDFLAGS} instead. If it
2603 affects only the compiler proper, @code{CFLAGS} is the natural home for
2604 it. If an option affects multiple phases of the compiler, though,
2609 If an option selects a 32-bit or 64-bit build on a bi-arch system, it
2610 must be put direcly into @code{CC}, e.g., @code{CC='gcc -m64'}. This is
2611 necessary for @code{config.guess} to work right.
2613 Otherwise one approach is to put the option into @code{CC}. Another is
2614 to put it into both @code{CPPFLAGS} and @code{LDFLAGS}, but not into
2618 However, remember that some @file{Makefile} variables are reserved by
2619 the GNU Coding Standards for the use of the ``user''---the person
2620 building the package. For instance, @code{CFLAGS} is one such variable.
2622 Sometimes package developers are tempted to set user variables such as
2623 @code{CFLAGS} because it appears to make their job easier. However, the
2624 package itself should never set a user variable, particularly not to
2625 include switches that are required for proper compilation of the
2626 package. Since these variables are documented as being for the package
2627 builder, that person rightfully expects to be able to override any of
2628 these variables at build time. If the package developer needs to add
2629 switches without interfering with the user, the proper way to do that is
2630 to introduce an additional variable. Automake makes this easy by
2631 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2632 automake, GNU Automake}), but the concept is the same even if
2633 Automake is not used.
2636 @defvar configure_input
2637 @ovindex configure_input
2638 A comment saying that the file was generated automatically by
2639 @command{configure} and giving the name of the input file.
2640 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2641 of every makefile it creates. For other files, you should
2642 reference this variable in a comment at the top of each input file. For
2643 example, an input shell script should begin like this:
2647 # @@configure_input@@
2651 The presence of that line also reminds people editing the file that it
2652 needs to be processed by @command{configure} in order to be used.
2658 Preprocessor options for the C, C++, Objective C, and Objective C++
2659 preprocessors and compilers. If
2660 it is not set in the environment when @command{configure} runs, the default
2661 value is empty. @command{configure} uses this variable when preprocessing
2662 or compiling programs to test for C, C++, Objective C, and Objective C++
2665 This variable's contents should contain options like @option{-I},
2666 @option{-D}, and @option{-U} that affect only the behavior of the
2667 preprocessor. Please see the explanation of @code{CFLAGS} for what you
2668 can do if an option affects other phases of the compiler as well.
2670 Currently, @command{configure} always links as part of a single
2671 invocation of the compiler that also preprocesses and compiles, so it
2672 uses this variable also when linking programs. However, it is unwise to
2673 depend on this behavior because the GNU Coding Standards do
2674 not require it and many packages do not use @code{CPPFLAGS} when linking
2677 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2684 Debugging and optimization options for the C++ compiler. It acts like
2685 @code{CFLAGS}, but for C++ instead of C.
2690 @option{-D} options to pass to the C compiler. If @code{AC_CONFIG_HEADERS}
2691 is called, @command{configure} replaces @samp{@@DEFS@@} with
2692 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}). This
2693 variable is not defined while @command{configure} is performing its tests,
2694 only when creating the output files. @xref{Setting Output Variables}, for
2695 how to check the results of previous tests.
2704 These obsolescent variables let you suppress the trailing newline from
2705 @command{echo} for question-answer message pairs.
2706 Nowadays it is better to use @code{AS_ECHO_N}.
2712 Debugging and optimization options for the Erlang compiler. If it is not set
2713 in the environment when @command{configure} runs, the default value is empty.
2714 @command{configure} uses this variable when compiling
2715 programs to test for Erlang features.
2721 Debugging and optimization options for the Fortran compiler. If it
2722 is not set in the environment when @command{configure} runs, the default
2723 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2724 @command{configure} uses this variable when compiling or linking
2725 programs to test for Fortran features.
2731 Debugging and optimization options for the Fortran 77 compiler. If it
2732 is not set in the environment when @command{configure} runs, the default
2733 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2734 @command{configure} uses this variable when compiling or linking
2735 programs to test for Fortran 77 features.
2741 Options for the linker. If it is not set
2742 in the environment when @command{configure} runs, the default value is empty.
2743 @command{configure} uses this variable when linking programs to test for
2744 C, C++, Objective C, Objective C++, Fortran, and Go features.
2746 This variable's contents should contain options like @option{-s} and
2747 @option{-L} that affect only the behavior of the linker. Please see the
2748 explanation of @code{CFLAGS} for what you can do if an option also
2749 affects other phases of the compiler.
2751 Don't use this variable to pass library names
2752 (@option{-l}) to the linker; use @code{LIBS} instead.
2758 @option{-l} options to pass to the linker. The default value is empty,
2759 but some Autoconf macros may prepend extra libraries to this variable if
2760 those libraries are found and provide necessary functions, see
2761 @ref{Libraries}. @command{configure} uses this variable when linking
2762 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2769 Debugging and optimization options for the Objective C compiler. It
2770 acts like @code{CFLAGS}, but for Objective C instead of C.
2774 @evindex OBJCXXFLAGS
2775 @ovindex OBJCXXFLAGS
2776 Debugging and optimization options for the Objective C++ compiler. It
2777 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2783 Debugging and optimization options for the Go compiler. It acts like
2784 @code{CFLAGS}, but for Go instead of C.
2789 Rigorously equal to @samp{.}. Added for symmetry only.
2792 @defvar abs_builddir
2793 @ovindex abs_builddir
2794 Absolute name of @code{builddir}.
2797 @defvar top_builddir
2798 @ovindex top_builddir
2799 The relative name of the top level of the current build tree. In the
2800 top-level directory, this is the same as @code{builddir}.
2803 @defvar top_build_prefix
2804 @ovindex top_build_prefix
2805 The relative name of the top level of the current build tree with final
2806 slash if nonempty. This is the same as @code{top_builddir}, except that
2807 it contains zero or more runs of @code{../}, so it should not be
2808 appended with a slash for concatenation. This helps for @command{make}
2809 implementations that otherwise do not treat @file{./file} and @file{file}
2810 as equal in the top-level build directory.
2813 @defvar abs_top_builddir
2814 @ovindex abs_top_builddir
2815 Absolute name of @code{top_builddir}.
2820 The name of the directory that contains the source code for
2826 Absolute name of @code{srcdir}.
2831 The name of the top-level source code directory for the
2832 package. In the top-level directory, this is the same as @code{srcdir}.
2835 @defvar abs_top_srcdir
2836 @ovindex abs_top_srcdir
2837 Absolute name of @code{top_srcdir}.
2840 @node Installation Directory Variables
2841 @subsection Installation Directory Variables
2842 @cindex Installation directories
2843 @cindex Directories, installation
2845 The following variables specify the directories for
2846 package installation, see @ref{Directory Variables, , Variables for
2847 Installation Directories, standards, The GNU Coding
2848 Standards}, for more information. Each variable corresponds to an
2849 argument of @command{configure}; trailing slashes are stripped so that
2850 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2851 between directory names. See the end of this section for
2852 details on when and how to use these variables.
2856 The directory for installing executables that users run.
2861 The directory for installing idiosyncratic read-only
2862 architecture-independent data.
2866 @ovindex datarootdir
2867 The root of the directory tree for read-only architecture-independent
2873 The directory for installing documentation files (other than Info and
2879 The directory for installing documentation files in DVI format.
2883 @ovindex exec_prefix
2884 The installation prefix for architecture-dependent files. By default
2885 it's the same as @code{prefix}. You should avoid installing anything
2886 directly to @code{exec_prefix}. However, the default value for
2887 directories containing architecture-dependent files should be relative
2888 to @code{exec_prefix}.
2893 The directory for installing HTML documentation.
2898 The directory for installing C header files.
2903 The directory for installing documentation in Info format.
2908 The directory for installing object code libraries.
2913 The directory for installing executables that other programs run.
2918 The directory for installing locale-dependent but
2919 architecture-independent data, such as message catalogs. This directory
2920 usually has a subdirectory per locale.
2923 @defvar localstatedir
2924 @ovindex localstatedir
2925 The directory for installing modifiable single-machine data. Content in
2926 this directory typically survives a reboot.
2930 @ovindex runstatedir
2931 The directory for installing temporary modifiable single-machine data.
2932 Content in this directory survives as long as the process is running
2933 (such as pid files), as contrasted with @file{/tmp} that may be
2934 periodically cleaned. Conversely, this directory is typically cleaned
2935 on a reboot. By default, this is a subdirectory of
2936 @code{localstatedir}.
2941 The top-level directory for installing documentation in man format.
2944 @defvar oldincludedir
2945 @ovindex oldincludedir
2946 The directory for installing C header files for non-GCC compilers.
2951 The directory for installing PDF documentation.
2956 The common installation prefix for all files. If @code{exec_prefix}
2957 is defined to a different value, @code{prefix} is used only for
2958 architecture-independent files.
2963 The directory for installing PostScript documentation.
2968 The directory for installing executables that system
2972 @defvar sharedstatedir
2973 @ovindex sharedstatedir
2974 The directory for installing modifiable architecture-independent data.
2979 The directory for installing read-only single-machine data.
2983 Most of these variables have values that rely on @code{prefix} or
2984 @code{exec_prefix}. It is deliberate that the directory output
2985 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2986 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2987 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2989 This behavior is mandated by the GNU Coding Standards, so that when
2994 she can still specify a different prefix from the one specified to
2995 @command{configure}, in which case, if needed, the package should hard
2996 code dependencies corresponding to the make-specified prefix.
2999 she can specify a different installation location, in which case the
3000 package @emph{must} still depend on the location which was compiled in
3001 (i.e., never recompile when @samp{make install} is run). This is an
3002 extremely important feature, as many people may decide to install all
3003 the files of a package grouped together, and then install links from
3004 the final locations to there.
3007 In order to support these features, it is essential that
3008 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
3009 so that its value can be expanded based
3010 on the current value of @code{prefix}.
3012 A corollary is that you should not use these variables except in
3013 makefiles. For instance, instead of trying to evaluate @code{datadir}
3014 in @file{configure} and hard-coding it in makefiles using
3015 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
3017 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
3018 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
3020 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
3021 @code{bindir} and friends in your shell scripts and other files; instead,
3022 let @command{make} manage their replacement. For instance Autoconf
3023 ships templates of its shell scripts ending with @samp{.in}, and uses a
3024 makefile snippet similar to the following to build scripts like
3025 @command{autoheader} and @command{autom4te}:
3030 -e 's|@@bindir[@@]|$(bindir)|g' \
3031 -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
3032 -e 's|@@prefix[@@]|$(prefix)|g'
3036 autoheader autom4te: Makefile
3039 test -f ./$@@.in || srcdir=$(srcdir)/; \
3040 $(edit) $$@{srcdir@}$@@.in >$@@.tmp
3041 @c $$ restore font-lock
3048 autoheader: $(srcdir)/autoheader.in
3049 autom4te: $(srcdir)/autom4te.in
3053 Some details are noteworthy:
3056 @item @samp{@@bindir[@@]}
3057 The brackets prevent @command{configure} from replacing
3058 @samp{@@bindir@@} in the Sed expression itself.
3059 Brackets are preferable to a backslash here, since
3060 POSIX says @samp{\@@} is not portable.
3062 @item @samp{$(bindir)}
3063 Don't use @samp{@@bindir@@}! Use the matching makefile variable
3066 @item @samp{$(pkgdatadir)}
3067 The example takes advantage of the variable @samp{$(pkgdatadir)}
3068 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
3071 Don't use @samp{/} in the Sed expressions that replace file names since
3073 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
3074 Use a shell metacharacter instead, such as @samp{|}.
3076 @item special characters
3077 File names, file name components, and the value of @code{VPATH} should
3078 not contain shell metacharacters or white
3079 space. @xref{Special Chars in Variables}.
3081 @item dependency on @file{Makefile}
3082 Since @code{edit} uses values that depend on the configuration specific
3083 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
3084 the output depends on @file{Makefile}, not @file{configure.ac}.
3087 The main rule is generic, and uses @samp{$@@} extensively to
3088 avoid the need for multiple copies of the rule.
3090 @item Separated dependencies and single suffix rules
3091 You can't use them! The above snippet cannot be (portably) rewritten
3095 autoconf autoheader: Makefile
3105 @xref{Single Suffix Rules}, for details.
3107 @item @samp{$(srcdir)}
3108 Be sure to specify the name of the source directory,
3109 otherwise the package won't support separated builds.
3112 For the more specific installation of Erlang libraries, the following variables
3115 @defvar ERLANG_INSTALL_LIB_DIR
3116 @ovindex ERLANG_INSTALL_LIB_DIR
3117 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3118 The common parent directory of Erlang library installation directories.
3119 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3120 macro in @file{configure.ac}.
3123 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3124 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3125 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3126 The installation directory for Erlang library @var{library}.
3127 This variable is set by using the
3128 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3129 macro in @file{configure.ac}.
3132 @xref{Erlang Libraries}, for details.
3135 @node Changed Directory Variables
3136 @subsection Changed Directory Variables
3137 @cindex @file{datarootdir}
3139 In Autoconf 2.60, the set of directory variables has changed, and the
3140 defaults of some variables have been adjusted
3141 (@pxref{Installation Directory Variables}) to changes in the
3142 GNU Coding Standards. Notably, @file{datadir}, @file{infodir}, and
3143 @file{mandir} are now expressed in terms of @file{datarootdir}. If you are
3144 upgrading from an earlier Autoconf version, you may need to adjust your files
3145 to ensure that the directory variables are substituted correctly
3146 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3147 in place. For example, in a @file{Makefile.in}, adding
3150 datarootdir = @@datarootdir@@
3154 is usually sufficient. If you use Automake to create @file{Makefile.in},
3155 it will add this for you.
3157 To help with the transition, Autoconf warns about files that seem to use
3158 @code{datarootdir} without defining it. In some cases, it then expands
3159 the value of @code{$datarootdir} in substitutions of the directory
3160 variables. The following example shows such a warning:
3163 $ @kbd{cat configure.ac}
3165 AC_CONFIG_FILES([Makefile])
3167 $ @kbd{cat Makefile.in}
3169 datadir = @@datadir@@
3172 configure: creating ./config.status
3173 config.status: creating Makefile
3174 config.status: WARNING:
3175 Makefile.in seems to ignore the --datarootdir setting
3176 $ @kbd{cat Makefile}
3178 datadir = $@{prefix@}/share
3181 Usually one can easily change the file to accommodate both older and newer
3185 $ @kbd{cat Makefile.in}
3187 datarootdir = @@datarootdir@@
3188 datadir = @@datadir@@
3190 configure: creating ./config.status
3191 config.status: creating Makefile
3192 $ @kbd{cat Makefile}
3194 datarootdir = $@{prefix@}/share
3195 datadir = $@{datarootdir@}
3198 @acindex{DATAROOTDIR_CHECKED}
3199 In some cases, however, the checks may not be able to detect that a suitable
3200 initialization of @code{datarootdir} is in place, or they may fail to detect
3201 that such an initialization is necessary in the output file. If, after
3202 auditing your package, there are still spurious @file{configure} warnings about
3203 @code{datarootdir}, you may add the line
3206 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3210 to your @file{configure.ac} to disable the warnings. This is an exception
3211 to the usual rule that you should not define a macro whose name begins with
3212 @code{AC_} (@pxref{Macro Names}).
3216 @node Build Directories
3217 @subsection Build Directories
3218 @cindex Build directories
3219 @cindex Directories, build
3221 You can support compiling a software package for several architectures
3222 simultaneously from the same copy of the source code. The object files
3223 for each architecture are kept in their own directory.
3225 To support doing this, @command{make} uses the @code{VPATH} variable to
3226 find the files that are in the source directory. GNU Make
3227 can do this. Most other recent @command{make} programs can do this as
3228 well, though they may have difficulties and it is often simpler to
3229 recommend GNU @command{make} (@pxref{VPATH and Make}). Older
3230 @command{make} programs do not support @code{VPATH}; when using them, the
3231 source code must be in the same directory as the object files.
3233 If you are using GNU Automake, the remaining details in this
3234 section are already covered for you, based on the contents of your
3235 @file{Makefile.am}. But if you are using Autoconf in isolation, then
3236 supporting @code{VPATH} requires the following in your
3244 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3247 @command{configure} substitutes the correct value for @code{srcdir} when
3248 it produces @file{Makefile}.
3250 Do not use the @command{make} variable @code{$<}, which expands to the
3251 file name of the file in the source directory (found with @code{VPATH}),
3252 except in implicit rules. (An implicit rule is one such as @samp{.c.o},
3253 which tells how to create a @file{.o} file from a @file{.c} file.) Some
3254 versions of @command{make} do not set @code{$<} in explicit rules; they
3255 expand it to an empty value.
3257 Instead, Make command lines should always refer to source
3258 files by prefixing them with @samp{$(srcdir)/}. It's safer
3259 to quote the source directory name, in case it contains characters that
3260 are special to the shell. Because @samp{$(srcdir)} is expanded by Make,
3261 single-quoting works and is safer than double-quoting. For example:
3264 time.info: time.texinfo
3265 $(MAKEINFO) '$(srcdir)/time.texinfo'
3268 @node Automatic Remaking
3269 @subsection Automatic Remaking
3270 @cindex Automatic remaking
3271 @cindex Remaking automatically
3273 You can put rules like the following in the top-level @file{Makefile.in}
3274 for a package to automatically update the configuration information when
3275 you change the configuration files. This example includes all of the
3276 optional files, such as @file{aclocal.m4} and those related to
3277 configuration header files. Omit from the @file{Makefile.in} rules for
3278 any of these files that your package does not use.
3280 The @samp{$(srcdir)/} prefix is included because of limitations in the
3281 @code{VPATH} mechanism.
3283 The @file{stamp-} files are necessary because the timestamps of
3284 @file{config.h.in} and @file{config.h} are not changed if remaking
3285 them does not change their contents. This feature avoids unnecessary
3286 recompilation. You should include the file @file{stamp-h.in} in your
3287 package's distribution, so that @command{make} considers
3288 @file{config.h.in} up to date. Don't use @command{touch}
3289 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3290 @command{echo} (using
3291 @command{date} would cause needless output differences).
3295 $(srcdir)/configure: configure.ac aclocal.m4
3296 cd '$(srcdir)' && autoconf
3298 # autoheader might not change config.h.in, so touch a stamp file.
3299 $(srcdir)/config.h.in: stamp-h.in ;
3300 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3301 cd '$(srcdir)' && autoheader
3302 echo timestamp > '$(srcdir)/stamp-h.in'
3305 stamp-h: config.h.in config.status
3308 Makefile: Makefile.in config.status
3311 config.status: configure
3312 ./config.status --recheck
3317 (Be careful if you copy these lines directly into your makefile, as you
3318 need to convert the indented lines to start with the tab character.)
3320 In addition, you should use
3323 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3327 so @file{config.status} ensures that @file{config.h} is considered up to
3328 date. @xref{Output}, for more information about @code{AC_OUTPUT}.
3330 @xref{config.status Invocation}, for more examples of handling
3331 configuration-related dependencies.
3333 @node Configuration Headers
3334 @section Configuration Header Files
3335 @cindex Configuration Header
3336 @cindex @file{config.h}
3338 When a package contains more than a few tests that define C preprocessor
3339 symbols, the command lines to pass @option{-D} options to the compiler
3340 can get quite long. This causes two problems. One is that the
3341 @command{make} output is hard to visually scan for errors. More
3342 seriously, the command lines can exceed the length limits of some
3343 operating systems. As an alternative to passing @option{-D} options to
3344 the compiler, @command{configure} scripts can create a C header file
3345 containing @samp{#define} directives. The @code{AC_CONFIG_HEADERS}
3346 macro selects this kind of output. Though it can be called anywhere
3347 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3348 it right after @code{AC_INIT}.
3350 The package should @samp{#include} the configuration header file before
3351 any other header files, to prevent inconsistencies in declarations (for
3352 example, if it redefines @code{const}, or if it defines a macro like
3353 @code{_FILE_OFFSET_BITS} that affects the behavior of system
3354 headers). Note that it is okay to only include @file{config.h} from
3355 @file{.c} files; the project's @file{.h} files can rely on
3356 @file{config.h} already being included first by the corresponding
3359 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3360 option (or @option{-I..}; whichever directory contains @file{config.h}).
3361 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3362 the directory of the currently read file, i.e., the source directory, not
3363 the build directory.
3365 With the appropriate @option{-I} option, you can use
3366 @samp{#include <config.h>}. Actually, it's a good habit to use it,
3367 because in the rare case when the source directory contains another
3368 @file{config.h}, the build directory should be searched first.
3371 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3372 @acindex{CONFIG_HEADERS}
3373 @cvindex HAVE_CONFIG_H
3374 This macro is one of the instantiating macros; see @ref{Configuration
3375 Actions}. Make @code{AC_OUTPUT} create the file(s) in the
3376 blank-or-newline-separated list @var{header} containing C preprocessor
3377 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3378 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3379 The usual name for @var{header} is @file{config.h};
3380 @var{header} should not contain shell metacharacters.
3381 @xref{Special Chars in Variables}.
3383 If @var{header} already exists and its contents are identical to what
3384 @code{AC_OUTPUT} would put in it, it is left alone. Doing this allows
3385 making some changes in the configuration without needlessly causing
3386 object files that depend on the header file to be recompiled.
3388 Usually the input file is named @file{@var{header}.in}; however, you can
3389 override the input file name by appending to @var{header} a
3390 colon-separated list of input files. For example, you might need to make
3391 the input file name acceptable to DOS variants:
3394 AC_CONFIG_HEADERS([config.h:config.hin])
3401 This macro is defined as the name of the first declared config header
3402 and undefined if no config headers have been declared up to this point.
3403 A third-party macro may, for example, require use of a config header
3404 without invoking AC_CONFIG_HEADERS twice, like this:
3407 AC_CONFIG_COMMANDS_PRE(
3408 [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3413 @xref{Configuration Actions}, for more details on @var{header}.
3416 * Header Templates:: Input for the configuration headers
3417 * autoheader Invocation:: How to create configuration templates
3418 * Autoheader Macros:: How to specify CPP templates
3421 @node Header Templates
3422 @subsection Configuration Header Templates
3423 @cindex Configuration Header Template
3424 @cindex Header templates
3425 @cindex @file{config.h.in}
3427 Your distribution should contain a template file that looks as you want
3428 the final header file to look, including comments, with @code{#undef}
3429 statements which are used as hooks. For example, suppose your
3430 @file{configure.ac} makes these calls:
3433 AC_CONFIG_HEADERS([conf.h])
3434 AC_CHECK_HEADERS([unistd.h])
3438 Then you could have code like the following in @file{conf.h.in}.
3439 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3440 to 1, if and only if the system has @file{unistd.h}.
3444 /* Define as 1 if you have unistd.h. */
3445 #undef HAVE_UNISTD_H
3449 The format of the template file is stricter than what the C preprocessor
3450 is required to accept. A directive line should contain only whitespace,
3451 @samp{#undef}, and @samp{HAVE_UNISTD_H}. The use of @samp{#define}
3452 instead of @samp{#undef}, or of comments on the same line as
3453 @samp{#undef}, is strongly discouraged. Each hook should only be listed
3454 once. Other preprocessor lines, such as @samp{#ifdef} or
3455 @samp{#include}, are copied verbatim from the template into the
3458 Since it is a tedious task to keep a template header up to date, you may
3459 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3461 During the instantiation of the header, each @samp{#undef} line in the
3462 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3463 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3464 been executed during the @command{configure} run, the @samp{#undef} line is
3465 commented out. (This is important, e.g., for @samp{_POSIX_SOURCE}:
3466 on many systems, it can be implicitly defined by the compiler, and
3467 undefining it in the header would then break compilation of subsequent
3470 Currently, @emph{all} remaining @samp{#undef} lines in the header
3471 template are commented out, whether or not there was a corresponding
3472 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3473 for future releases of Autoconf.
3475 Generally speaking, since you should not use @samp{#define}, and you
3476 cannot guarantee whether a @samp{#undef} directive in the header
3477 template will be converted to a @samp{#define} or commented out in the
3478 generated header file, the template file cannot be used for conditional
3479 definition effects. Consequently, if you need to use the construct
3490 you must place it outside of the template.
3491 If you absolutely need to hook it to the config header itself, please put
3492 the directives to a separate file, and @samp{#include} that file from the
3493 config header template. If you are using @command{autoheader}, you would
3494 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3497 @node autoheader Invocation
3498 @subsection Using @command{autoheader} to Create @file{config.h.in}
3499 @cindex @command{autoheader}
3501 The @command{autoheader} program can create a template file of C
3502 @samp{#define} statements for @command{configure} to use.
3503 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3504 @file{configure} sources to determine the name of the template.
3505 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3506 input file name, @command{autoheader} uses the first one.)
3508 It is recommended that only one input file is used. If you want to append
3509 a boilerplate code, it is preferable to use
3510 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3511 File @file{conf_post.h} is not processed during the configuration then,
3512 which make things clearer. Analogically, @code{AH_TOP} can be used to
3513 prepend a boilerplate code.
3515 In order to do its job, @command{autoheader} needs you to document all
3516 of the symbols that you might use. Typically this is done via an
3517 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3518 is a literal symbol and whose third argument describes the symbol
3519 (@pxref{Defining Symbols}). Alternatively, you can use
3520 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3521 suitable input file for a subsequent configuration header file.
3522 Symbols defined by Autoconf's builtin tests are already documented properly;
3523 you need to document only those that you
3526 You might wonder why @command{autoheader} is needed: after all, why
3527 would @command{configure} need to ``patch'' a @file{config.h.in} to
3528 produce a @file{config.h} instead of just creating @file{config.h} from
3529 scratch? Well, when everything rocks, the answer is just that we are
3530 wasting our time maintaining @command{autoheader}: generating
3531 @file{config.h} directly is all that is needed. When things go wrong,
3532 however, you'll be thankful for the existence of @command{autoheader}.
3534 The fact that the symbols are documented is important in order to
3535 @emph{check} that @file{config.h} makes sense. The fact that there is a
3536 well-defined list of symbols that should be defined (or not) is
3537 also important for people who are porting packages to environments where
3538 @command{configure} cannot be run: they just have to @emph{fill in the
3541 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3543 If you give @command{autoheader} an argument, it uses that file instead
3544 of @file{configure.ac} and writes the header file to the standard output
3545 instead of to @file{config.h.in}. If you give @command{autoheader} an
3546 argument of @option{-}, it reads the standard input instead of
3547 @file{configure.ac} and writes the header file to the standard output.
3549 @command{autoheader} accepts the following options:
3554 Print a summary of the command line options and exit.
3558 Print the version number of Autoconf and exit.
3562 Report processing steps.
3566 Don't remove the temporary files.
3570 Remake the template file even if newer than its input files.
3572 @item --include=@var{dir}
3574 Append @var{dir} to the include path. Multiple invocations accumulate.
3576 @item --prepend-include=@var{dir}
3578 Prepend @var{dir} to the include path. Multiple invocations accumulate.
3580 @item --warnings=@var{category}[,@var{category}...]
3581 @itemx -W@var{category}[,@var{category}...]
3583 Enable or disable warnings related to each @var{category}.
3584 @xref{m4_warn}, for a comprehensive list of categories.
3585 Special values include:
3589 Enable all categories of warnings.
3592 Disable all categories of warnings.
3595 Treat all warnings as errors.
3597 @item no-@var{category}
3598 Disable warnings falling into @var{category}.
3601 The environment variable @env{WARNINGS} may also be set to a
3602 comma-separated list of warning categories to enable or disable.
3603 It is interpreted exactly the same way as the argument of
3604 @option{--warnings}, but unknown categories are silently ignored.
3605 The command line takes precedence; for instance, if @env{WARNINGS}
3606 is set to @code{obsolete}, but @option{-Wnone} is given on the
3607 command line, no warnings will be issued.
3609 Some categories of warnings are on by default.
3610 Again, for details see @ref{m4_warn}.
3615 @node Autoheader Macros
3616 @subsection Autoheader Macros
3617 @cindex Autoheader macros
3619 @command{autoheader} scans @file{configure.ac} and figures out which C
3620 preprocessor symbols it might define. It knows how to generate
3621 templates for symbols defined by @code{AC_CHECK_HEADERS},
3622 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3623 symbol, you must define a template for it. If there are missing
3624 templates, @command{autoheader} fails with an error message.
3626 The template for a @var{symbol} is created
3627 by @command{autoheader} from
3628 the @var{description} argument to an @code{AC_DEFINE};
3629 see @ref{Defining Symbols}.
3631 For special needs, you can use the following macros.
3634 @defmac AH_TEMPLATE (@var{key}, @var{description})
3636 Tell @command{autoheader} to generate a template for @var{key}. This macro
3637 generates standard templates just like @code{AC_DEFINE} when a
3638 @var{description} is given.
3643 AH_TEMPLATE([NULL_DEVICE],
3644 [Name of the file to open to get
3645 a null file, or a data sink.])
3649 generates the following template, with the description properly
3653 /* Name of the file to open to get a null file, or a data sink. */
3659 @defmac AH_VERBATIM (@var{key}, @var{template})
3661 Tell @command{autoheader} to include the @var{template} as-is in the header
3662 template file. This @var{template} is associated with the @var{key},
3663 which is used to sort all the different templates and guarantee their
3664 uniqueness. It should be a symbol that can be defined via @code{AC_DEFINE}.
3668 @defmac AH_TOP (@var{text})
3670 Include @var{text} at the top of the header template file.
3674 @defmac AH_BOTTOM (@var{text})
3676 Include @var{text} at the bottom of the header template file.
3680 Please note that @var{text} gets included ``verbatim'' to the template file,
3681 not to the resulting config header, so it can easily get mangled when the
3682 template is processed. There is rarely a need for something other than
3685 AH_BOTTOM([#include <custom.h>])
3690 @node Configuration Commands
3691 @section Running Arbitrary Configuration Commands
3692 @cindex Configuration commands
3693 @cindex Commands for configuration
3695 You can execute arbitrary commands before, during, and after
3696 @file{config.status} is run. The three following macros accumulate the
3697 commands to run when they are called multiple times.
3698 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3699 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3701 @anchor{AC_CONFIG_COMMANDS}
3702 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3703 @acindex{CONFIG_COMMANDS}
3704 Specify additional shell commands to run at the end of
3705 @file{config.status}, and shell commands to initialize any variables
3706 from @command{configure}. Associate the commands with @var{tag}.
3707 Since typically the @var{cmds} create a file, @var{tag} should
3708 naturally be the name of that file. If needed, the directory hosting
3709 @var{tag} is created. The @var{tag} should not contain shell
3710 metacharacters. @xref{Special Chars in Variables}.
3711 This macro is one of the instantiating macros;
3712 see @ref{Configuration Actions}.
3714 Here is an unrealistic example:
3717 AC_CONFIG_COMMANDS([fubar],
3718 [AS_ECHO(["this is extra $fubar, and so on."])],
3722 Here is a better one:
3724 AC_CONFIG_COMMANDS([timestamp], [echo >timestamp])
3728 The following two macros look similar, but in fact they are not of the same
3729 breed: they are executed directly by @file{configure}, so you cannot use
3730 @file{config.status} to rerun them.
3732 @c Yet it is good to leave them here. The user sees them together and
3733 @c decides which best fits their needs.
3735 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3736 @acindex{CONFIG_COMMANDS_PRE}
3737 Execute the @var{cmds} right before creating @file{config.status}.
3739 This macro presents the last opportunity to call @code{AC_SUBST},
3740 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3743 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3744 @acindex{CONFIG_COMMANDS_POST}
3745 Execute the @var{cmds} right after creating @file{config.status}.
3751 @node Configuration Links
3752 @section Creating Configuration Links
3753 @cindex Configuration links
3754 @cindex Links for configuration
3756 You may find it convenient to create links whose destinations depend upon
3757 results of tests. One can use @code{AC_CONFIG_COMMANDS} but the
3758 creation of relative symbolic links can be delicate when the package is
3759 built in a directory different from the source directory.
3761 @anchor{AC_CONFIG_LINKS}
3762 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3764 @acindex{CONFIG_LINKS}
3766 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3767 the corresponding link name @var{dest}. Makes a symbolic link if
3768 possible, otherwise a hard link if possible, otherwise a copy. The
3769 @var{dest} and @var{source} names should be relative to the top level
3770 source or build directory, and should not contain shell metacharacters.
3771 @xref{Special Chars in Variables}.
3773 This macro is one of the instantiating
3774 macros; see @ref{Configuration Actions}.
3776 For example, this call:
3779 AC_CONFIG_LINKS([host.h:config/$machine.h
3780 object.h:config/$obj_format.h])
3784 creates in the current directory @file{host.h} as a link to
3785 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3786 link to @file{@var{srcdir}/config/$obj_format.h}.
3788 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3789 impossible for @samp{config.status} to guess the links to establish.
3793 ./config.status host.h object.h
3796 to create the links.
3801 @node Subdirectories
3802 @section Configuring Other Packages in Subdirectories
3803 @cindex Configure subdirectories
3804 @cindex Subdirectory configure
3806 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3807 makefiles in subdirectories. However, @command{configure} scripts
3808 that control more than one independent package can use
3809 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3810 packages in subdirectories.
3812 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3813 @acindex{CONFIG_SUBDIRS}
3815 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3816 @var{dir} in the given blank-or-newline-separated list. Each @var{dir} should
3817 be a literal, i.e., please do not use:
3820 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3821 if test "x$package_foo_enabled" = xyes; then
3822 my_subdirs="$my_subdirs foo"
3824 AC_CONFIG_SUBDIRS([$my_subdirs])
3828 because this prevents @samp{./configure --help=recursive} from
3829 displaying the options of the package @code{foo}. Instead, you should
3833 AS_IF([test "x$package_foo_enabled" = xyes],
3834 [AC_CONFIG_SUBDIRS([foo])])
3837 If a given @var{dir} is not found at @command{configure} run time, a
3838 warning is reported; if the subdirectory is optional, write:
3841 AS_IF([test -d "$srcdir/foo"],
3842 [AC_CONFIG_SUBDIRS([foo])])
3845 These examples use @code{AS_IF} instead of ordinary shell @code{if} to
3846 avoid problems that Autoconf has with macro calls in shell conditionals
3847 outside macro definitions. @xref{Common Shell Constructs}.
3849 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3850 of @command{configure}. This is for packages that might use a
3851 non-Autoconf script @command{Configure}, which can't be called through a
3852 wrapper @command{configure} since it would be the same file on
3853 case-insensitive file systems.
3855 The subdirectory @command{configure} scripts are given the same command
3856 line options that were given to this @command{configure} script, with minor
3857 changes if needed, which include:
3861 adjusting a relative name for the cache file;
3864 adjusting a relative name for the source directory;
3867 propagating the current value of @code{$prefix}, including if it was
3868 defaulted, and if the default values of the top level and of the subdirectory
3869 @file{configure} differ.
3872 This macro also sets the output variable @code{subdirs} to the list of
3873 directories @samp{@var{dir} @dots{}}. Make rules can use
3874 this variable to determine which subdirectories to recurse into.
3876 This macro may be called multiple times.
3879 @node Default Prefix
3880 @section Default Prefix
3881 @cindex Install prefix
3882 @cindex Prefix for install
3884 By default, @command{configure} sets the prefix for files it installs to
3885 @file{/usr/local}. The user of @command{configure} can select a different
3886 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3887 There are two ways to change the default: when creating
3888 @command{configure}, and when running it.
3890 Some software packages might want to install in a directory other than
3891 @file{/usr/local} by default. To accomplish that, use the
3892 @code{AC_PREFIX_DEFAULT} macro.
3894 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3895 @acindex{PREFIX_DEFAULT}
3896 Set the default installation prefix to @var{prefix} instead of
3900 It may be convenient for users to have @command{configure} guess the
3901 installation prefix from the location of a related program that they
3902 have already installed. If you wish to do that, you can call
3903 @code{AC_PREFIX_PROGRAM}.
3905 @anchor{AC_PREFIX_PROGRAM}
3906 @defmac AC_PREFIX_PROGRAM (@var{program})
3907 @acindex{PREFIX_PROGRAM}
3908 If the user did not specify an installation prefix (using the
3909 @option{--prefix} option), guess a value for it by looking for
3910 @var{program} in @env{PATH}, the way the shell does. If @var{program}
3911 is found, set the prefix to the parent of the directory containing
3912 @var{program}, else default the prefix as described above
3913 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}). For example, if
3914 @var{program} is @code{gcc} and the @env{PATH} contains
3915 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3920 @c ======================================================== Existing tests
3922 @node Existing Tests
3923 @chapter Existing Tests
3925 These macros test for particular system features that packages might
3926 need or want to use. If you need to test for a kind of feature that
3927 none of these macros check for, you can probably do it by calling
3928 primitive test macros with appropriate arguments (@pxref{Writing
3931 These tests print messages telling the user which feature they're
3932 checking for, and what they find. They cache their results for future
3933 @command{configure} runs (@pxref{Caching Results}).
3935 Some of these macros set output variables. @xref{Makefile
3936 Substitutions}, for how to get their values. The phrase ``define
3937 @var{name}'' is used below as a shorthand to mean ``define the C
3938 preprocessor symbol @var{name} to the value 1''. @xref{Defining
3939 Symbols}, for how to get those symbol definitions into your program.
3942 * Common Behavior:: Macros' standard schemes
3943 * Alternative Programs:: Selecting between alternative programs
3944 * Files:: Checking for the existence of files
3945 * Libraries:: Library archives that might be missing
3946 * Library Functions:: C library functions that might be missing
3947 * Header Files:: Header files that might be missing
3948 * Declarations:: Declarations that may be missing
3949 * Structures:: Structures or members that might be missing
3950 * Types:: Types that might be missing
3951 * Compilers and Preprocessors:: Checking for compiling programs
3952 * System Services:: Operating system services
3953 * C and POSIX Variants:: Kludges for C and POSIX variants
3954 * Erlang Libraries:: Checking for the existence of Erlang libraries
3957 @node Common Behavior
3958 @section Common Behavior
3959 @cindex Common autoconf behavior
3961 Much effort has been expended to make Autoconf easy to learn. The most
3962 obvious way to reach this goal is simply to enforce standard interfaces
3963 and behaviors, avoiding exceptions as much as possible. Because of
3964 history and inertia, unfortunately, there are still too many exceptions
3965 in Autoconf; nevertheless, this section describes some of the common
3969 * Standard Symbols:: Symbols defined by the macros
3970 * Default Includes:: Includes used by the generic macros
3973 @node Standard Symbols
3974 @subsection Standard Symbols
3975 @cindex Standard symbols
3977 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3978 their test transform their @var{argument} values to a standard alphabet.
3979 First, @var{argument} is converted to upper case and any asterisks
3980 (@samp{*}) are each converted to @samp{P}. Any remaining characters
3981 that are not alphanumeric are converted to underscores.
3986 AC_CHECK_TYPES([struct $Expensive*])
3990 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3994 @node Default Includes
3995 @subsection Default Includes
3996 @cindex Default includes
3997 @cindex Includes, default
4017 Test programs frequently need to include headers that may or may not be
4018 available on the system whose features are being tested. Each test can
4019 use all the preprocessor macros that have been @code{AC_DEFINE}d by
4020 previous tests, so for example one may write
4025 #ifdef HAVE_SYS_TIME_H
4026 # include <sys/time.h>
4032 if @file{sys/time.h} has already been tested for.
4034 All hosted environments that are still of interest for portable code
4035 provide all of the headers specified in C89 (as amended in 1995):
4036 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
4037 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
4038 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
4039 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
4040 @file{wchar.h}, and @file{wctype.h}. Most programs can safely include
4041 these headers unconditionally. A program not intended to be portable to
4042 C89 can also safely include the C99-specified header @file{stdbool.h}.
4043 Other headers, including headers from C99 and later revisions of the C
4044 standard, might need to be tested for (@pxref{Header Files}) or their
4045 bugs may need to be worked around (@pxref{Gnulib}).
4047 If your program needs to be portable to a @emph{freestanding}
4048 environment, such as an embedded OS that doesn't provide all of the
4049 facilities of the C89 standard library, you may need to test for some of
4050 the above headers as well. Note that many Autoconf macros internally
4051 assume that the complete set of C89 headers are available.
4053 Most generic macros use the following macro to provide a default set
4056 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
4057 @acindex{INCLUDES_DEFAULT}
4058 Expand to @var{include-directives} if present and nonempty, otherwise to:
4066 #ifdef HAVE_STDLIB_H
4067 # include <stdlib.h>
4069 #ifdef HAVE_STRING_H
4070 # include <string.h>
4072 #ifdef HAVE_INTTYPES_H
4073 # include <inttypes.h>
4075 #ifdef HAVE_STDINT_H
4076 # include <stdint.h>
4078 #ifdef HAVE_STRINGS_H
4079 # include <strings.h>
4081 #ifdef HAVE_SYS_TYPES_H
4082 # include <sys/types.h>
4084 #ifdef HAVE_SYS_STAT_H
4085 # include <sys/stat.h>
4087 #ifdef HAVE_UNISTD_H
4088 # include <unistd.h>
4093 Using this macro without @var{include-directives} has the side effect of
4094 checking for @file{stdio.h}, @file{stdlib.h}, @file{string.h},
4095 @file{inttypes.h}, @file{stdint.h}, @file{strings.h},
4096 @file{sys/types.h}, @file{sys/stat.h}, and @file{unistd.h}, as if by
4097 @code{AC_CHECK_HEADERS_ONCE}. For backward compatibility, the macro
4098 @code{STDC_HEADERS} will be defined when both @file{stdlib.h} and
4099 @file{string.h} are available.
4101 @strong{Portability Note:} It is safe for most programs to assume the
4102 presence of all of the headers required by the original 1990 C standard.
4103 @code{AC_INCLUDES_DEFAULT} checks for @file{stdio.h}, @file{stdlib.h},
4104 and @file{string.h}, even though they are in that list, because they
4105 might not be available when compiling for a ``freestanding environment''
4106 (in which most of the features of the C library are optional). You
4107 probably do not need to write @samp{#ifdef HAVE_STDIO_H} in your own
4110 @file{inttypes.h} and @file{stdint.h} were added to C in the 1999
4111 revision of the standard, and @file{strings.h}, @file{sys/types.h},
4112 @file{sys/stat.h}, and @file{unistd.h} are POSIX extensions. You
4113 @emph{should} guard uses of these headers with appropriate conditionals.
4116 @defmac AC_CHECK_INCLUDES_DEFAULT
4117 @acindex{CHECK_INCLUDES_DEFAULT}
4118 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
4119 for as a side-effect, if this has not already happened.
4121 This macro mainly exists so that @code{autoupdate} can replace certain
4122 obsolete constructs with it. You should not need to use it yourself; in
4123 fact, it is likely to be safe to delete it from any script in which it
4124 appears. (@code{autoupdate} does not know whether preprocessor macros
4125 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4126 would get defined as a side-effect of other checks.)
4129 @node Alternative Programs
4130 @section Alternative Programs
4131 @cindex Programs, checking
4133 These macros check for the presence or behavior of particular programs.
4134 They are used to choose between several alternative programs and to
4135 decide what to do once one has been chosen. If there is no macro
4136 specifically defined to check for a program you need, and you don't need
4137 to check for any special properties of it, then you can use one of the
4138 general program-check macros.
4141 * Particular Programs:: Special handling to find certain programs
4142 * Generic Programs:: How to find other programs
4145 @node Particular Programs
4146 @subsection Particular Program Checks
4148 These macros check for particular programs---whether they exist, and
4149 in some cases whether they support certain features.
4155 @c @caindex prog_ac_ct_AR
4156 Set output variable @code{AR} to @samp{ar} if @code{ar} is found, and
4157 otherwise to @samp{:} (do nothing).
4164 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4165 order, and set output variable @code{AWK} to the first one that is found.
4166 It tries @code{gawk} first because that is reported to be the
4167 best implementation. The result can be overridden by setting the
4168 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4170 Using this macro is sufficient to avoid the pitfalls of traditional
4171 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4174 @defmac AC_PROG_GREP
4178 Look for the best available @code{grep} or @code{ggrep} that accepts the
4179 longest input lines possible, and that supports multiple @option{-e} options.
4180 Set the output variable @code{GREP} to whatever is chosen.
4181 @xref{grep, , Limitations of Usual Tools}, for more information about
4182 portability problems with the @command{grep} command family. The result
4183 can be overridden by setting the @code{GREP} variable and is cached in the
4184 @code{ac_cv_path_GREP} variable.
4187 @defmac AC_PROG_EGREP
4188 @acindex{PROG_EGREP}
4191 Check whether @code{$GREP -E} works, or else look for the best available
4192 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4193 Set the output variable @code{EGREP} to whatever is chosen. The result
4194 can be overridden by setting the @code{EGREP} variable and is cached in the
4195 @code{ac_cv_path_EGREP} variable.
4198 @defmac AC_PROG_FGREP
4199 @acindex{PROG_FGREP}
4202 Check whether @code{$GREP -F} works, or else look for the best available
4203 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4204 Set the output variable @code{FGREP} to whatever is chosen. The result
4205 can be overridden by setting the @code{FGREP} variable and is cached in the
4206 @code{ac_cv_path_FGREP} variable.
4209 @defmac AC_PROG_INSTALL
4210 @acindex{PROG_INSTALL}
4212 @ovindex INSTALL_PROGRAM
4213 @ovindex INSTALL_DATA
4214 @ovindex INSTALL_SCRIPT
4215 @caindex path_install
4216 @prindex @command{install-sh}
4217 Set output variable @code{INSTALL} to the name of a BSD-compatible
4218 @command{install} program, if one is found in the current @env{PATH}.
4219 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4220 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4221 default directories) to determine @var{dir} (@pxref{Output}). Also set
4222 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4223 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4225 @samp{@@INSTALL@@} is special, as its value may vary for different
4226 configuration files.
4228 This macro screens out various instances of @command{install} known not to
4229 work. It prefers to find a C program rather than a shell script, for
4230 speed. Instead of @file{install-sh}, it can also use @file{install.sh},
4231 but that name is obsolete because some @command{make} programs have a rule
4232 that creates @file{install} from it if there is no makefile. Further, this
4233 macro requires @command{install} to be able to install multiple files into a
4234 target directory in a single invocation.
4236 Autoconf comes with a copy of @file{install-sh} that you can use.
4237 If you use @code{AC_PROG_INSTALL}, you must include @file{install-sh} in
4238 your distribution; otherwise @command{autoreconf} and @command{configure}
4239 will produce an error message saying they can't find it---even if the
4240 system you're on has a good @command{install} program. This check is a
4241 safety measure to prevent you from accidentally leaving that file out,
4242 which would prevent your package from installing on systems that don't
4243 have a BSD-compatible @command{install} program.
4245 If you need to use your own installation program because it has features
4246 not found in standard @command{install} programs, there is no reason to use
4247 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4248 @file{Makefile.in} files.
4250 The result of the test can be overridden by setting the variable
4251 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4254 @defmac AC_PROG_MKDIR_P
4255 @acindex{PROG_MKDIR_P}
4258 @prindex @command{install-sh}
4259 Set output variable @code{MKDIR_P} to a program that ensures that for
4260 each argument, a directory named by this argument exists, creating it
4261 and its parent directories if needed, and without race conditions when
4262 two instances of the program attempt to make the same directory at
4263 nearly the same time.
4265 This macro uses the equivalent of the @samp{mkdir -p} command. Ancient
4266 versions of @command{mkdir} are vulnerable to race conditions, so if you
4267 want to support parallel installs from different packages into the same
4268 directory you should use a non-ancient @command{mkdir}.
4270 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4271 in M4sh}), but it sets an output variable intended for use in other
4272 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4273 @command{configure}. Also, @code{AS_MKDIR_P} does not accept options,
4274 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4275 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4276 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4277 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4279 The result of the test can be overridden by setting the variable
4280 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4283 @anchor{AC_PROG_LEX}
4284 @defmac AC_PROG_LEX (@var{options})
4288 @cvindex YYTEXT_POINTER
4289 @ovindex LEX_OUTPUT_ROOT
4291 Search for a lexical analyzer generator, preferring @code{flex}
4292 to plain @code{lex}. Output variable @code{LEX} is set to whichever
4293 program is available. If neither program is available, @code{LEX}
4295 for packages that ship the generated @file{file.yy.c}
4296 alongside the source @file{file.l}, this default allows users without a
4297 lexer generator to still build the package even if the timestamp for
4298 @file{file.l} is inadvertently changed.
4300 The name of the program to use can be overridden by setting the
4301 output variable @code{LEX} or the cache variable @code{ac_cv_prog_LEX}
4302 when running @command{configure}.
4304 If a lexical analyzer generator is found, this macro performs additional
4305 checks for common portability pitfalls. If these additional checks
4306 fail, @code{LEX} is reset to @samp{:}; otherwise the following
4307 additional macros and variables are provided.
4309 Preprocessor macro @code{YYTEXT_POINTER} is defined if the lexer
4310 skeleton, by default, declares @code{yytext} as a @samp{@w{char *}}
4311 rather than a @samp{@w{char []}}.
4313 Output variable @code{LEX_OUTPUT_ROOT} is set to the base of the file
4314 name that the lexer generates; this is usually either @file{lex.yy} or
4317 If generated lexers need a library to work, output variable
4318 @code{LEXLIB} is set to a link option for that library (e.g.,
4319 @option{-ll}), otherwise it is set to empty.
4321 The @var{options} argument modifies the behavior of @code{AC_PROG_LEX}.
4322 It should be a whitespace-separated list of options. Currently there
4323 are only two options, and they are mutually exclusive:
4327 Indicate that the library in @code{LEXLIB} needs to define the function
4328 @code{yywrap}. If a library that defines this function cannot be found,
4329 @code{LEX} will be reset to @samp{:}.
4332 Indicate that the library in @code{LEXLIB} does not need to define the
4333 function @code{yywrap}. @command{configure} will not search for it at
4337 Prior to Autoconf 2.70, @code{AC_PROG_LEX} did not take any arguments,
4338 and its behavior was different from either of the above possibilities:
4339 it would search for a library that defines @code{yywrap}, and would set
4340 @code{LEXLIB} to that library if it finds one. However, if a library
4341 that defines this function could not be found, @code{LEXLIB} would be
4342 left empty and @code{LEX} would @emph{not} be reset. This behavior was
4343 due to a bug, but several packages came to depend on it, so
4344 @code{AC_PROG_LEX} still does this if neither the @code{yywrap} nor the
4345 @code{noyywrap} option is given.
4347 Usage of @code{AC_PROG_LEX} without choosing one of the @code{yywrap}
4348 or @code{noyywrap} options is deprecated. It is usually better to
4349 use @code{noyywrap} and define the @code{yywrap} function yourself,
4350 as this almost always renders the @code{LEXLIB} unnecessary.
4352 @strong{Caution:} As a side-effect of the test, this macro may delete
4353 any file in the configure script's current working directory named
4354 @file{lex.yy.c} or @file{lexyy.c}.
4356 @strong{Caution:} Packages that ship a generated @file{lex.yy.c}
4357 cannot assume that the definition of @code{YYTEXT_POINTER} matches
4358 the code in that file. They also cannot assume that @code{LEXLIB}
4359 provides the library routines required by the code in that file.
4361 If you use Flex to generate @file{lex.yy.c}, you can work around these
4362 limitations by defining @code{yywrap} and @code{main} yourself
4363 (rendering @code{-lfl} unnecessary), and by using either the
4364 @option{--array} or @option{--pointer} options to control how
4365 @code{yytext} is declared. The code generated by Flex is also more
4366 portable than the code generated by historical versions of Lex.
4368 If you have used Flex to generate @file{lex.yy.c}, and especially if
4369 your scanner depends on Flex features, we recommend you use this
4370 Autoconf snippet to prevent the scanner being regenerated with
4375 AS_IF([test "x$LEX" != xflex],
4376 [LEX="$SHELL $missing_dir/missing flex"
4377 AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4378 AC_SUBST([LEXLIB], [''])])
4381 The shell script @command{missing} can be found in the Automake
4384 Remember that the user may have supplied an alternate location in
4385 @env{LEX}, so if Flex is required, it is better to check that the user
4386 provided something sufficient by parsing the output of @samp{$LEX
4387 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4390 @anchor{AC_PROG_LN_S}
4391 @defmac AC_PROG_LN_S
4394 If @samp{ln -s} works on the current file system (the operating system
4395 and file system support symbolic links), set the output variable
4396 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4397 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4399 If you make a link in a directory other than the current directory, its
4400 meaning depends on whether @samp{ln} or @samp{ln -s} is used. To safely
4401 create links using @samp{$(LN_S)}, either find out which form is used
4402 and adjust the arguments, or always invoke @code{ln} in the directory
4403 where the link is to be created.
4405 In other words, it does not work to do:
4413 (cd /x && $(LN_S) foo bar)
4417 @defmac AC_PROG_RANLIB
4418 @acindex{PROG_RANLIB}
4420 @c @caindex prog_RANLIB
4421 @c @caindex prog_ac_ct_RANLIB
4422 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4423 is found, and otherwise to @samp{:} (do nothing).
4430 Set output variable @code{SED} to a Sed implementation that conforms to
4431 POSIX and does not have arbitrary length limits. Report an error if no
4432 acceptable Sed is found. @xref{sed, , Limitations of Usual Tools}, for more
4433 information about portability problems with Sed.
4435 The result of this test can be overridden by setting the @code{SED} variable
4436 and is cached in the @code{ac_cv_path_SED} variable.
4439 @defmac AC_PROG_YACC
4445 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4446 -y}. Otherwise, if @code{byacc} is found, set @code{YACC} to
4447 @samp{byacc}. Otherwise set @code{YACC} to @samp{yacc}.
4448 The result of this test can be influenced by setting the variable
4449 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4452 @node Generic Programs
4453 @subsection Generic Program and File Checks
4455 These macros are used to find programs not covered by the ``particular''
4456 test macros. If you need to check the behavior of a program as well as
4457 find out whether it is present, you have to write your own test for it
4458 (@pxref{Writing Tests}). By default, these macros use the environment
4459 variable @env{PATH}. If you need to check for a program that might not
4460 be in the user's @env{PATH}, you can pass a modified path to use
4464 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4465 [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4466 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4469 You are strongly encouraged to declare the @var{variable} passed to
4470 @code{AC_CHECK_PROG} etc.@: as precious. @xref{Setting Output Variables},
4471 @code{AC_ARG_VAR}, for more details.
4473 @anchor{AC_CHECK_PROG}
4474 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4475 @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4477 @acindex{CHECK_PROG}
4478 @caindex prog_@var{variable}
4479 Check whether program @var{prog-to-check-for} exists in @var{path}. If
4480 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4481 @var{value-if-not-found}, if given. Always pass over @var{reject} (an
4482 absolute file name) even if it is the first found in the search path; in
4483 that case, set @var{variable} using the absolute file name of the
4484 @var{prog-to-check-for} found that is not @var{reject}. If
4485 @var{variable} was already set, do nothing. Calls @code{AC_SUBST} for
4486 @var{variable}. The result of this test can be overridden by setting the
4487 @var{variable} variable or the cache variable
4488 @code{ac_cv_prog_@var{variable}}.
4491 @anchor{AC_CHECK_PROGS}
4492 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4493 @ovar{value-if-not-found}, @dvar{path, $PATH})
4494 @acindex{CHECK_PROGS}
4495 @caindex prog_@var{variable}
4496 Check for each program in the blank-separated list
4497 @var{progs-to-check-for} existing in the @var{path}. If one is found, set
4498 @var{variable} to the name of that program. Otherwise, continue
4499 checking the next program in the list. If none of the programs in the
4500 list are found, set @var{variable} to @var{value-if-not-found}; if
4501 @var{value-if-not-found} is not specified, the value of @var{variable}
4502 is not changed. Calls @code{AC_SUBST} for @var{variable}. The result of
4503 this test can be overridden by setting the @var{variable} variable or the
4504 cache variable @code{ac_cv_prog_@var{variable}}.
4507 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4508 @ovar{value-if-not-found}, @dvar{path, $PATH})
4509 @acindex{CHECK_TARGET_TOOL}
4510 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4511 with a prefix of the target type as determined by
4512 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4513 If the tool cannot be found with a prefix, and if the build and target
4514 types are equal, then it is also searched for without a prefix.
4516 As noted in @ref{Specifying Target Triplets}, the
4517 target is rarely specified, because most of the time it is the same
4518 as the host: it is the type of system for which any compiler tool in
4519 the package produces code. What this macro looks for is,
4520 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4521 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4522 uses to produce objects, archives or executables}.
4525 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4526 @ovar{value-if-not-found}, @dvar{path, $PATH})
4527 @acindex{CHECK_TOOL}
4528 @c @caindex prog_@var{VARIABLE}
4529 @c @caindex prog_ac_ct_@var{VARIABLE}
4530 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4531 with a prefix of the host type as specified by @option{--host}, followed by a
4532 dash. For example, if the user runs
4533 @samp{configure --build=x86_64-gnu --host=aarch64-linux-gnu}, then this call:
4535 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4538 sets @code{RANLIB} to @file{aarch64-linux-gnu-ranlib} if that program exists in
4539 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4540 @var{path}, or to @samp{:} if neither program exists.
4542 When cross-compiling, this macro will issue a warning if no program
4543 prefixed with the host type could be found.
4544 For more information, see @ref{Specifying Target Triplets}.
4547 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4548 @ovar{value-if-not-found}, @dvar{path, $PATH})
4549 @acindex{CHECK_TARGET_TOOLS}
4550 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4551 @var{progs-to-check-for} are checked with a prefix of the target type as
4552 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4553 (@pxref{Canonicalizing}). If none of the tools can be found with a
4554 prefix, and if the build and target types are equal, then the first one
4555 without a prefix is used. If a tool is found, set @var{variable} to
4556 the name of that program. If none of the tools in the list are found,
4557 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4558 is not specified, the value of @var{variable} is not changed. Calls
4559 @code{AC_SUBST} for @var{variable}.
4562 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4563 @ovar{value-if-not-found}, @dvar{path, $PATH})
4564 @acindex{CHECK_TOOLS}
4565 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4566 @var{progs-to-check-for} are checked with a prefix of the host type as
4567 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4568 (@pxref{Canonicalizing}). If none of the tools can be found with a
4569 prefix, then the first one without a prefix is used. If a tool is found,
4570 set @var{variable} to the name of that program. If none of the tools in
4571 the list are found, set @var{variable} to @var{value-if-not-found}; if
4572 @var{value-if-not-found} is not specified, the value of @var{variable}
4573 is not changed. Calls @code{AC_SUBST} for @var{variable}.
4575 When cross-compiling, this macro will issue a warning if no program
4576 prefixed with the host type could be found.
4577 For more information, see @ref{Specifying Target Triplets}.
4580 @anchor{AC_PATH_PROG}
4581 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4582 @ovar{value-if-not-found}, @dvar{path, $PATH})
4584 @caindex path_@var{variable}
4585 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4586 name of @var{prog-to-check-for} if found. The result of this test
4587 can be overridden by setting the @var{variable} variable. A positive
4588 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4592 @anchor{AC_PATH_PROGS}
4593 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4594 @ovar{value-if-not-found}, @dvar{path, $PATH})
4595 @acindex{PATH_PROGS}
4596 @caindex path_@var{variable}
4597 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4598 are found, set @var{variable} to the absolute name of the program
4599 found. The result of this test can be overridden by setting the
4600 @var{variable} variable. A positive result of this test is cached in
4601 the @code{ac_cv_path_@var{variable}} variable.
4604 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4605 @var{progs-to-check-for}, @var{feature-test}, @
4606 @ovar{action-if-not-found}, @dvar{path, $PATH})
4607 @acindex{PATH_PROGS_FEATURE_CHECK}
4608 @caindex path_@var{variable}
4609 @vrindex ac_path_@var{variable}
4610 @vrindex ac_path_@var{variable}_found
4611 This macro was introduced in Autoconf 2.62. If @var{variable} is not
4612 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4613 its value. Otherwise, check for each program in the blank-separated
4614 list @var{progs-to-check-for} existing in @var{path}. For each program
4615 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4616 set to the absolute name of the candidate program. If no invocation of
4617 @var{feature-test} sets the shell variable
4618 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4619 executed. @var{feature-test} will be run even when
4620 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4621 choose a better candidate found later in @var{path}; to accept the
4622 current setting and bypass all further checks, @var{feature-test} can
4623 execute @code{ac_path_@var{variable}_found=:}.
4625 Note that this macro has some subtle differences from
4626 @code{AC_CHECK_PROGS}. It is designed to be run inside
4627 @code{AC_CACHE_VAL}, therefore, it should have no side effects. In
4628 particular, @var{variable} is not set to the final value of
4629 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4630 run. Also, on failure, any action can be performed, whereas
4631 @code{AC_CHECK_PROGS} only performs
4632 @code{@var{variable}=@var{value-if-not-found}}.
4634 Here is an example that searches for an implementation of @command{m4} that
4635 supports the @code{indir} builtin, even if it goes by the name
4636 @command{gm4} or is not the first implementation on @env{PATH}.
4639 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4640 [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4641 [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4642 test "x$m4out" = x0 \
4643 && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4644 [AC_MSG_ERROR([could not find m4 that supports indir])])])
4645 AC_SUBST([M4], [$ac_cv_path_M4])
4649 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4650 @ovar{value-if-not-found}, @dvar{path, $PATH})
4651 @acindex{PATH_TARGET_TOOL}
4652 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4653 name of the program if it is found.
4656 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4657 @ovar{value-if-not-found}, @dvar{path, $PATH})
4659 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4660 name of the program if it is found.
4662 When cross-compiling, this macro will issue a warning if no program
4663 prefixed with the host type could be found.
4664 For more information, see @ref{Specifying Target Triplets}.
4670 @cindex File, checking
4672 You might also need to check for the existence of files. Before using
4673 these macros, ask yourself whether a runtime test might not be a better
4674 solution. Be aware that, like most Autoconf macros, they test a feature
4675 of the host machine, and therefore, they die when cross-compiling.
4677 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4678 @ovar{action-if-not-found})
4679 @acindex{CHECK_FILE}
4680 @caindex file_@var{file}
4681 Check whether file @var{file} exists on the native system. If it is
4682 found, execute @var{action-if-found}, otherwise do
4683 @var{action-if-not-found}, if given. Cache the result of this test
4684 in the @code{ac_cv_file_@var{file}} variable, with characters not
4685 suitable for a variable name mapped to underscores.
4688 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4689 @ovar{action-if-not-found})
4690 @acindex{CHECK_FILES}
4691 @caindex file_@var{file}
4692 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4693 and perform either @var{action-if-found} or @var{action-if-not-found}.
4694 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4695 (@pxref{Standard Symbols}) for each file found and caches the results of
4696 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4697 not suitable for a variable name mapped to underscores.
4702 @section Library Files
4703 @cindex Library, checking
4705 The following macros check for the presence of certain C, C++, Fortran,
4706 or Go library archive files.
4708 @anchor{AC_CHECK_LIB}
4709 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4710 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4712 @caindex lib_@var{library}_@var{function}
4713 Test whether the library @var{library} is available by trying to link
4714 a test program that calls function @var{function} with the library.
4715 @var{function} should be a function provided by the library.
4717 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4718 the @var{library} argument.
4720 @var{action-if-found} is a list of shell commands to run if the link
4721 with the library succeeds; @var{action-if-not-found} is a list of shell
4722 commands to run if the link fails. If @var{action-if-found} is not
4723 specified, the default action prepends @option{-l@var{library}} to
4724 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4725 capitals). This macro is intended to support building @code{LIBS} in
4726 a right-to-left (least-dependent to most-dependent) fashion such that
4727 library dependencies are satisfied as a natural side effect of
4728 consecutive tests. Linkers are sensitive to library ordering
4729 so the order in which @code{LIBS} is generated is important to reliable
4730 detection of libraries.
4732 If linking with @var{library} results in unresolved symbols that would
4733 be resolved by linking with additional libraries, give those libraries
4734 as the @var{other-libraries} argument, separated by spaces:
4735 e.g., @option{-lXt -lX11}. Otherwise, this macro may fail to detect
4736 that @var{library} is present, because linking the test program can
4737 fail with unresolved symbols. The @var{other-libraries} argument
4738 should be limited to cases where it is desirable to test for one library
4739 in the presence of another that is not already in @code{LIBS}.
4741 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4742 in some common cases. Many standard functions like @code{gethostbyname}
4743 appear in the standard C library on some hosts, and in special libraries
4744 like @code{nsl} on other hosts. On some hosts the special libraries
4745 contain variant implementations that you may not want to use. These
4746 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4747 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4749 The result of this test is cached in the
4750 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4753 @anchor{AC_SEARCH_LIBS}
4754 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4755 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4756 @acindex{SEARCH_LIBS}
4757 @caindex search_@var{function}
4758 Search for a library defining @var{function} if it's not already
4759 available. This equates to calling
4760 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4761 no libraries, then for each library listed in @var{search-libs}.
4763 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4764 to contain @var{function}, and run @var{action-if-found}. If the
4765 function is not found, run @var{action-if-not-found}.
4767 If linking with @var{library} results in unresolved symbols that would
4768 be resolved by linking with additional libraries, give those libraries
4769 as the @var{other-libraries} argument, separated by spaces:
4770 e.g., @option{-lXt -lX11}. Otherwise, this macro fails to detect
4771 that @var{function} is present, because linking the test program
4772 always fails with unresolved symbols.
4774 The result of this test is cached in the
4775 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4776 @var{function} is already available, as @samp{no} if no library
4777 containing @var{function} was found, otherwise as the
4778 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4783 @node Library Functions
4784 @section Library Functions
4786 The following macros check for particular C library functions.
4787 If there is no macro specifically defined to check for a function you need,
4788 and you don't need to check for any special properties of
4789 it, then you can use one of the general function-check macros.
4792 * Function Portability:: Pitfalls with usual functions
4793 * Particular Functions:: Special handling to find certain functions
4794 * Generic Functions:: How to find other functions
4797 @node Function Portability
4798 @subsection Portability of C Functions
4799 @cindex Portability of C functions
4800 @cindex C function portability
4802 Most usual functions can either be missing, or be buggy, or be limited
4803 on some architectures. This section tries to make an inventory of these
4804 portability issues. By definition, this list always requires
4805 additions. A much more complete list is maintained by the Gnulib
4806 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4807 Current POSIX Functions, gnulib, Gnulib}, @ref{Legacy Function
4808 Substitutes, , Legacy Functions, gnulib, Gnulib}, and @ref{Glibc
4809 Function Substitutes, , Glibc Functions, gnulib, Gnulib}. Please
4810 help us keep the Gnulib list as complete as possible.
4815 @prindex @code{exit}
4816 On ancient hosts, @code{exit} returned @code{int}.
4817 This is because @code{exit} predates @code{void}, and there was a long
4818 tradition of it returning @code{int}.
4820 On current hosts, the problem more likely is that @code{exit} is not
4821 declared, due to C++ problems of some sort or another. For this reason
4822 we suggest that test programs not invoke @code{exit}, but return from
4823 @code{main} instead.
4827 @prindex @code{malloc}
4828 The C standard says a successful call @code{malloc (0)} is implementation
4829 dependent. It can return either @code{NULL} or a new non-null pointer.
4830 The latter is more common (e.g., the GNU C Library) but is by
4831 no means universal. @code{AC_FUNC_MALLOC}
4832 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4836 @prindex @code{putenv}
4837 POSIX prefers @code{setenv} to @code{putenv}; among other things,
4838 @code{putenv} is not required of all POSIX implementations, but
4841 POSIX specifies that @code{putenv} puts the given string directly in
4842 @code{environ}, but some systems make a copy of it instead (e.g.,
4843 glibc 2.0, or BSD). And when a copy is made, @code{unsetenv} might
4844 not free it, causing a memory leak (e.g., FreeBSD 4).
4846 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4847 environment, but this is not standard usage and it dumps core
4848 on some systems (e.g., AIX).
4850 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4851 environment, rather than inserting it with an empty value.
4853 @item @code{realloc}
4855 @prindex @code{realloc}
4856 It is problematic to call @code{realloc} with a zero size.
4857 The C standard says @code{realloc (NULL, 0)} is equivalent to
4858 @code{malloc (0)}, which means one cannot portably tell whether the call
4859 has succeeded if it returns a null pointer. If @code{ptr} is non-null,
4860 the C standard says @code{realloc (ptr, 0)} has undefined behavior.
4862 The @code{AC_FUNC_REALLOC} macro avoids some of these portability issues.
4863 @xref{Particular Functions}.
4865 @item @code{signal} handler
4867 @prindex @code{signal}
4868 @prindex @code{sigaction}
4869 In most cases, it is more robust to use @code{sigaction} when it is
4870 available, rather than @code{signal}.
4872 @item @code{snprintf}
4873 @c @fuindex snprintf
4874 @prindex @code{snprintf}
4875 @c @fuindex vsnprintf
4876 @prindex @code{vsnprintf}
4877 In C99 and later, if the output array isn't big enough
4878 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4879 truncate the output and return the number of bytes that ought to have
4880 been produced. Some older systems, notably Microsoft Windows before
4881 Visual Studio 2015 and Windows 10, do not null-terminate the output
4882 and return @minus{}1 instead.
4884 Portable code can check the return value of @code{snprintf (buf, sizeof
4885 buf, ...)}: if the value is negative or is not less than @code{sizeof
4886 buf}, an error occurred and the contents of @code{buf} can be ignored.
4887 Alternatively, one of the Gnulib modules related to @code{snprintf} can
4888 be used. @xref{Gnulib}.
4890 @item @code{strerror_r}
4891 @c @fuindex strerror_r
4892 @prindex @code{strerror_r}
4893 POSIX specifies that @code{strerror_r} returns an @code{int}, but many
4894 systems (e.g., GNU C Library version 2.36) provide a
4895 different version returning a @code{char *}. @code{AC_FUNC_STRERROR_R}
4896 can detect which is in use (@pxref{Particular Functions}).
4898 @item @code{strnlen}
4900 @prindex @code{strnlen}
4901 Android 5.0's strnlen was broken, because it assumed the addressed array
4902 always had at least the specified number of bytes. For example,
4903 @code{strnlen ("", SIZE_MAX)} should return 0 but on Android 5.0 it
4906 AIX 4.3 provided a broken version which produces the
4910 strnlen ("foobar", 0) = 0
4911 strnlen ("foobar", 1) = 3
4912 strnlen ("foobar", 2) = 2
4913 strnlen ("foobar", 3) = 1
4914 strnlen ("foobar", 4) = 0
4915 strnlen ("foobar", 5) = 6
4916 strnlen ("foobar", 6) = 6
4917 strnlen ("foobar", 7) = 6
4918 strnlen ("foobar", 8) = 6
4919 strnlen ("foobar", 9) = 6
4922 @item @code{sysconf}
4924 @prindex @code{sysconf}
4925 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4926 9) have @code{_SC_PAGE_SIZE} instead. This can be tested with
4931 @prindex @code{unlink}
4932 The POSIX spec says that @code{unlink} causes the given file to be
4933 removed only after there are no more open file handles for it. Some
4934 non-POSIX hosts have trouble with this requirement, though,
4935 and some DOS variants even corrupt the file system.
4937 @item @code{unsetenv}
4938 @c @fuindex unsetenv
4939 @prindex @code{unsetenv}
4940 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4941 can be removed with a call @code{putenv ("FOO=")}, as described under
4942 @code{putenv} above.
4944 @item @code{va_copy}
4946 @prindex @code{va_copy}
4947 C99 and later provide @code{va_copy} for copying
4948 @code{va_list} variables. It may be available in older environments
4949 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4950 pre-C99 mode). These can be tested with @code{#ifdef}. A fallback to
4951 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4954 @item @code{va_list}
4956 @prindex @code{va_list}
4957 @code{va_list} is not necessarily just a pointer. It can be a
4958 @code{struct}, which means @code{NULL} is not portable.
4959 Or it can be an array, which means as a function parameter it can be
4960 effectively call-by-reference and library routines might modify the
4961 value back in the caller.
4963 @item Signed @code{>>}
4964 Normally the C @code{>>} right shift of a signed type replicates the
4965 high bit, giving a so-called ``arithmetic'' shift. But care should be
4966 taken since Standard C doesn't require that behavior. On a few platforms
4967 (e.g., Cray C by default) zero bits are shifted in, the same as a shift of an
4970 @item Integer @code{/}
4971 C divides signed integers by truncating their quotient toward zero,
4972 yielding the same result as Fortran. However, before C99 the standard
4973 allowed C implementations to take the floor or ceiling of the quotient
4974 in some cases. Hardly any implementations took advantage of this
4975 freedom, though, and it's probably not worth worrying about this issue
4980 @node Particular Functions
4981 @subsection Particular Function Checks
4982 @cindex Function, checking
4984 These macros check for particular C functions---whether they exist, and
4985 in some cases how they respond when given certain arguments.
4987 @anchor{AC_FUNC_ALLOCA}
4988 @defmac AC_FUNC_ALLOCA
4989 @acindex{FUNC_ALLOCA}
4991 @cvindex HAVE_ALLOCA_H
4994 @prindex @code{alloca}
4996 @c @caindex working_alloca_h
4997 Check for the @code{alloca} function. Define @code{HAVE_ALLOCA_H} if
4998 @file{alloca.h} defines a working @code{alloca}. If not, look for a
4999 builtin alternative. If either method succeeds, define
5000 @code{HAVE_ALLOCA}. Otherwise, set the output variable @code{ALLOCA} to
5001 @samp{$@{LIBOBJDIR@}alloca.o} and define
5002 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
5003 garbage collect). This variable is separate from @code{LIBOBJS} so
5004 multiple programs can share the value of @code{ALLOCA} without needing
5005 to create an actual library, in case only some of them use the code in
5006 @code{LIBOBJS}. The @samp{$@{LIBOBJDIR@}} prefix serves the same
5007 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
5009 Source files that use @code{alloca} should start with a piece of code
5010 like the following, to declare it properly.
5016 #ifdef HAVE_ALLOCA_H
5017 # include <alloca.h>
5018 #elif !defined alloca
5020 # define alloca __builtin_alloca
5021 # elif defined _MSC_VER
5022 # include <malloc.h>
5023 # define alloca _alloca
5024 # elif !defined HAVE_ALLOCA
5028 void *alloca (size_t);
5034 If you don't want to maintain this piece of code in your package manually,
5035 you can instead use the Gnulib module @code{alloca-opt} or @code{alloca}.
5039 @defmac AC_FUNC_CHOWN
5040 @acindex{FUNC_CHOWN}
5043 @prindex @code{chown}
5044 @caindex func_chown_works
5045 If the @code{chown} function is available and works (in particular, it
5046 should accept @option{-1} for @code{uid} and @code{gid}), define
5047 @code{HAVE_CHOWN}. The result of this macro is cached in the
5048 @code{ac_cv_func_chown_works} variable.
5050 If you want a workaround, that is, a @code{chown} function that is
5051 available and works, you can use the Gnulib module @code{chown}.
5055 @anchor{AC_FUNC_CLOSEDIR_VOID}
5056 @defmac AC_FUNC_CLOSEDIR_VOID
5057 @acindex{FUNC_CLOSEDIR_VOID}
5058 @cvindex CLOSEDIR_VOID
5059 @c @fuindex closedir
5060 @prindex @code{closedir}
5061 @caindex func_closedir_void
5062 If the @code{closedir} function does not return a meaningful value,
5063 define @code{CLOSEDIR_VOID}. Otherwise, callers ought to check its
5064 return value for an error indicator.
5066 Currently this test is implemented by running a test program. When
5067 cross compiling the pessimistic assumption that @code{closedir} does not
5068 return a meaningful value is made.
5070 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
5073 This macro is obsolescent, as @code{closedir} returns a meaningful value
5074 on current systems. New programs need not use this macro.
5077 @defmac AC_FUNC_ERROR_AT_LINE
5078 @acindex{FUNC_ERROR_AT_LINE}
5079 @c @fuindex error_at_line
5080 @prindex @code{error_at_line}
5081 @caindex lib_error_at_line
5082 If the @code{error_at_line} function is not found, require an
5083 @code{AC_LIBOBJ} replacement of @samp{error}.
5085 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
5088 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent. New programs
5089 should use Gnulib's @code{error} module. @xref{Gnulib}.
5092 @defmac AC_FUNC_FNMATCH
5093 @acindex{FUNC_FNMATCH}
5095 @prindex @code{fnmatch}
5096 @caindex func_fnmatch_works
5097 If the @code{fnmatch} function conforms to POSIX, define
5098 @code{HAVE_FNMATCH}.
5100 Unlike the other specific
5101 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5102 broken/missing @code{fnmatch}. This is for historical reasons.
5103 See @code{AC_REPLACE_FNMATCH} below.
5105 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5108 This macro is obsolescent. New programs should use Gnulib's
5109 @code{fnmatch-posix} module. @xref{Gnulib}.
5112 @defmac AC_FUNC_FNMATCH_GNU
5113 @acindex{FUNC_FNMATCH_GNU}
5115 @prindex @code{fnmatch}
5116 @caindex func_fnmatch_gnu
5117 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5118 whether @code{fnmatch} supports GNU extensions. Detect common
5119 implementation bugs, for example, the bugs in the GNU C
5122 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5125 This macro is obsolescent. New programs should use Gnulib's
5126 @code{fnmatch-gnu} module. @xref{Gnulib}.
5129 @anchor{AC_FUNC_FORK}
5130 @defmac AC_FUNC_FORK
5132 @cvindex HAVE_VFORK_H
5133 @cvindex HAVE_WORKING_FORK
5134 @cvindex HAVE_WORKING_VFORK
5137 @prindex @code{fork}
5139 @prindex @code{vfork}
5141 @c @caindex func_fork
5142 @c @caindex func_fork_works
5143 This macro checks for the @code{fork} and @code{vfork} functions. If a
5144 working @code{fork} is found, define @code{HAVE_WORKING_FORK}. This macro
5145 checks whether @code{fork} is just a stub by trying to run it.
5147 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}. If a working
5148 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}. Otherwise,
5149 define @code{vfork} to be @code{fork} for backward compatibility with
5150 previous versions of @command{autoconf}. This macro checks for several known
5151 errors in implementations of @code{vfork} and considers the system to not
5152 have a working @code{vfork} if it detects any of them.
5154 Since this macro defines @code{vfork} only for backward compatibility with
5155 previous versions of @command{autoconf} you're encouraged to define it
5156 yourself in new code:
5159 #ifndef HAVE_WORKING_VFORK
5165 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5166 and @code{ac_cv_func_vfork_works} variables. In order to override the
5167 test, you also need to set the @code{ac_cv_func_fork} and
5168 @code{ac_cv_func_vfork} variables.
5171 @anchor{AC_FUNC_FSEEKO}
5172 @defmac AC_FUNC_FSEEKO
5173 @acindex{FUNC_FSEEKO}
5174 @cvindex _LARGEFILE_SOURCE
5175 @cvindex HAVE_FSEEKO
5177 @prindex @code{fseeko}
5179 @prindex @code{ftello}
5180 @c @caindex sys_largefile_source
5181 If the @code{fseeko} and @code{ftello} functions are available, define
5182 @code{HAVE_FSEEKO}. Define @code{_LARGEFILE_SOURCE} if necessary to
5183 make the prototype visible.
5185 Configure scripts that use @code{AC_FUNC_FSEEKO} should normally also
5186 use @code{AC_SYS_LARGEFILE} to ensure that @code{off_t} can represent
5187 all supported file sizes. @xref{AC_SYS_LARGEFILE}.
5189 The Gnulib module @code{fseeko} invokes @code{AC_FUNC_FSEEKO}
5190 and also contains workarounds for other portability problems of
5191 @code{fseeko}. @xref{Gnulib}.
5194 @defmac AC_FUNC_GETGROUPS
5195 @acindex{FUNC_GETGROUPS}
5196 @cvindex HAVE_GETGROUPS
5197 @ovindex GETGROUPS_LIB
5198 @c @fuindex getgroups
5199 @prindex @code{getgroups}
5200 @caindex func_getgroups_works
5201 Perform all the checks performed by @code{AC_TYPE_GETGROUPS}
5202 (@pxref{AC_TYPE_GETGROUPS}).
5203 Then, if the @code{getgroups} function is available
5204 and known to work correctly, define @code{HAVE_GETGROUPS}.
5205 Set the output variable @code{GETGROUPS_LIB} to any libraries
5206 needed to get that function.
5208 This macro relies on a list of systems with known, serious bugs in
5209 @code{getgroups}. If this list mis-identifies your system's
5210 @code{getgroups} as buggy, or as not buggy, you can override it by
5211 setting the cache variable @code{ac_cv_func_getgroups_works} in a
5212 @file{config.site} file (@pxref{Site Defaults}). Please also report the
5213 error to @email{bug-autoconf@@gnu.org, the Autoconf Bugs mailing list}.
5215 The Gnulib module @code{getgroups} provides workarounds for additional,
5216 less severe portability problems with this function.
5219 @anchor{AC_FUNC_GETLOADAVG}
5220 @defmac AC_FUNC_GETLOADAVG
5221 @acindex{FUNC_GETLOADAVG}
5226 @cvindex HAVE_NLIST_H
5227 @cvindex NLIST_NAME_UNION
5228 @cvindex GETLOADAVG_PRIVILEGED
5229 @cvindex NEED_SETGID
5230 @cvindex C_GETLOADAVG
5232 @ovindex NEED_SETGID
5234 @ovindex GETLOADAVG_LIBS
5235 @c @fuindex getloadavg
5236 @prindex @code{getloadavg}
5237 Check how to get the system load averages. To perform its tests
5238 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5239 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5240 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5242 If the system has the @code{getloadavg} function, define
5243 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5244 necessary to get that function. Also add @code{GETLOADAVG_LIBS} to
5245 @code{LIBS}. Otherwise, require an @code{AC_LIBOBJ} replacement for
5246 @samp{getloadavg} and possibly define several other C preprocessor
5247 macros and output variables:
5251 Define @code{C_GETLOADAVG}.
5254 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5259 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5262 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5263 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}. The obsolete symbol
5264 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5267 Programs may need to be installed set-group-ID (or set-user-ID) for
5268 @code{getloadavg} to work. In this case, define
5269 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5270 to @samp{true} (and otherwise to @samp{false}), and set
5271 @code{KMEM_GROUP} to the name of the group that should own the installed
5275 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent. New programs should
5276 use Gnulib's @code{getloadavg} module. @xref{Gnulib}.
5279 @anchor{AC_FUNC_GETMNTENT}
5280 @defmac AC_FUNC_GETMNTENT
5281 @acindex{FUNC_GETMNTENT}
5282 @cvindex HAVE_GETMNTENT
5283 @c @fuindex getmntent
5284 @prindex @code{getmntent}
5285 @caindex search_getmntent
5286 Check for @code{getmntent} in the standard C library, and then in the
5287 @file{sun}, @file{seq}, and @file{gen} libraries. Then, if
5288 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5289 @code{ac_cv_func_getmntent} to @code{yes}. Otherwise set
5290 @code{ac_cv_func_getmntent} to @code{no}.
5292 The result of this macro can be overridden by setting the cache variable
5293 @code{ac_cv_search_getmntent}.
5295 The @code{AC_FUNC_GETMNTENT} macro is obsolescent. New programs should
5296 use Gnulib's @code{mountlist} module. @xref{Gnulib}.
5299 @defmac AC_FUNC_GETPGRP
5300 @acindex{FUNC_GETPGRP}
5301 @cvindex GETPGRP_VOID
5304 @prindex @code{getpgid}
5305 @prindex @code{getpgrp}
5306 @caindex func_getpgrp_void
5307 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5308 @code{getpgrp}; this is the POSIX behavior. On older BSD
5309 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5310 behaves like POSIX's @code{getpgid}.
5320 This macro does not check whether
5321 @code{getpgrp} exists at all; if you need to work in that situation,
5322 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5324 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5327 This macro is obsolescent, as current systems have a @code{getpgrp}
5328 whose signature conforms to POSIX. New programs need not use this macro.
5331 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5332 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5333 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5335 @prindex @code{lstat}
5336 @caindex func_lstat_dereferences_slashed_symlink
5337 If @file{link} is a symbolic link, then @code{lstat} should treat
5338 @file{link/} the same as @file{link/.}. However, many older
5339 @code{lstat} implementations incorrectly ignore trailing slashes.
5341 It is safe to assume that if @code{lstat} incorrectly ignores
5342 trailing slashes, then other symbolic-link-aware functions like
5343 @code{unlink} also incorrectly ignore trailing slashes.
5345 If @code{lstat} behaves properly, define
5346 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5347 @code{AC_LIBOBJ} replacement of @code{lstat}.
5349 The result of this macro is cached in the
5350 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5352 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5353 New programs should use Gnulib's @code{lstat} module. @xref{Gnulib}.
5356 @defmac AC_FUNC_MALLOC
5357 @acindex{FUNC_MALLOC}
5358 @cvindex HAVE_MALLOC
5361 @prindex @code{malloc}
5362 @caindex func_malloc_0_nonnull
5363 If the @code{malloc} function is compatible with the GNU C
5364 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5365 pointer), define @code{HAVE_MALLOC} to 1. Otherwise define
5366 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5367 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5368 native @code{malloc} is not used in the main project.
5370 Typically, the replacement file @file{malloc.c} should look like (note
5371 the @samp{#undef malloc}):
5379 /* Allocate an N-byte block of memory from the heap.
5380 If N is zero, allocate a 1-byte block. */
5383 rpl_malloc (size_t n)
5391 The result of this macro is cached in the
5392 @code{ac_cv_func_malloc_0_nonnull} variable.
5393 The result might contain spaces, e.g., @code{guessing yes}.
5395 If you don't want to maintain a @code{malloc.c} file in your package
5396 manually, you can instead use the Gnulib module @code{malloc-gnu}.
5399 @defmac AC_FUNC_MBRTOWC
5400 @acindex{FUNC_MBRTOWC}
5401 @cvindex HAVE_MBRTOWC
5403 @prindex @code{mbrtowc}
5404 @caindex func_mbrtowc
5405 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5406 type @code{mbstate_t} are properly declared.
5408 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5411 The Gnulib module @code{mbrtowc} not only ensures that the
5412 function is declared, but also works around other portability
5413 problems of this function.
5416 @defmac AC_FUNC_MEMCMP
5417 @acindex{FUNC_MEMCMP}
5420 @prindex @code{memcmp}
5421 @caindex func_memcmp_working
5422 If the @code{memcmp} function is not available or does not work, require an
5423 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5425 The result of this macro is cached in the
5426 @code{ac_cv_func_memcmp_working} variable.
5428 This macro is obsolescent, as current systems have a working
5429 @code{memcmp}. New programs need not use this macro.
5432 @defmac AC_FUNC_MKTIME
5433 @acindex{FUNC_MKTIME}
5436 @prindex @code{mktime}
5437 @caindex func_working_mktime
5438 If the @code{mktime} function is not available, or does not work
5439 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5440 For the purposes of this test, @code{mktime} should conform to the
5441 POSIX standard and should be the inverse of
5444 The result of this macro is cached in the
5445 @code{ac_cv_func_working_mktime} variable.
5447 The @code{AC_FUNC_MKTIME} macro is obsolescent. New programs should
5448 use Gnulib's @code{mktime} module. @xref{Gnulib}.
5451 @anchor{AC_FUNC_MMAP}
5452 @defmac AC_FUNC_MMAP
5456 @prindex @code{mmap}
5457 @caindex func_mmap_fixed_mapped
5458 If the @code{mmap} function exists and works correctly, define
5459 @code{HAVE_MMAP}. This checks only private fixed mapping of already-mapped
5462 The result of this macro is cached in the
5463 @code{ac_cv_func_mmap_fixed_mapped} variable.
5465 Note: This macro asks for more than what an average program needs from
5466 @code{mmap}. In particular, the use of @code{MAP_FIXED} fails on
5467 HP-UX 11, whereas @code{mmap} otherwise works fine on this platform.
5470 @defmac AC_FUNC_OBSTACK
5471 @acindex{FUNC_OBSTACK}
5472 @cvindex HAVE_OBSTACK
5474 @caindex func_obstack
5475 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5476 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5478 The result of this macro is cached in the @code{ac_cv_func_obstack}
5481 The @code{AC_FUNC_OBSTACK} macro is obsolescent. New programs should use
5482 Gnulib's @code{obstack} module. @xref{Gnulib}.
5485 @defmac AC_FUNC_REALLOC
5486 @acindex{FUNC_REALLOC}
5487 @cvindex HAVE_REALLOC
5490 @prindex @code{realloc}
5491 @caindex func_realloc_0_nonnull
5492 If a successful call to @samp{realloc (NULL, 0)} returns a
5493 non-null pointer, define @code{HAVE_REALLOC} to 1. Otherwise define
5494 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5495 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5496 the native @code{realloc} is not used in the main project. See
5497 @code{AC_FUNC_MALLOC} for details.
5499 The result of this macro is cached in the
5500 @code{ac_cv_func_realloc_0_nonnull} variable.
5501 The result might contain spaces, e.g., @code{guessing yes}.
5503 This macro does not check compatibility with glibc @code{realloc (@var{p}, 0)}
5504 when @var{p} is non-null, as glibc 1--2.1 behaves differently from glibc
5505 2.1.1--2.40 (at least), and the C standard says behavior is undefined.
5508 @defmac AC_FUNC_SELECT_ARGTYPES
5509 @acindex{FUNC_SELECT_ARGTYPES}
5510 @cvindex SELECT_TYPE_ARG1
5511 @cvindex SELECT_TYPE_ARG234
5512 @cvindex SELECT_TYPE_ARG5
5514 @prindex @code{select}
5515 @c @caindex func_select_args
5516 Determines the correct type to be passed for each of the
5517 @code{select} function's arguments, and defines those types
5518 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5519 @code{SELECT_TYPE_ARG5} respectively. @code{SELECT_TYPE_ARG1} defaults
5520 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5521 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5523 This macro is obsolescent, as current systems have a @code{select} whose
5524 signature conforms to POSIX. New programs need not use this macro.
5527 @defmac AC_FUNC_SETPGRP
5528 @acindex{FUNC_SETPGRP}
5529 @cvindex SETPGRP_VOID
5531 @prindex @code{setpgrp}
5532 @caindex func_setpgrp_void
5533 If @code{setpgrp} takes no argument (the POSIX version), define
5534 @code{SETPGRP_VOID}. Otherwise, it is the BSD version, which takes
5535 two process IDs as arguments. This macro does not check whether
5536 @code{setpgrp} exists at all; if you need to work in that situation,
5537 first call @code{AC_CHECK_FUNC} for @code{setpgrp}. This macro also
5538 does not check for the Solaris variant of @code{setpgrp}, which returns
5539 a @code{pid_t} instead of an @code{int}; portable code should only use
5540 the return value by comparing it against @code{-1} to check for errors.
5542 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5545 This macro is obsolescent, as all forms of @code{setpgrp} are also
5546 obsolescent. New programs should use the POSIX function @code{setpgid},
5547 which takes two process IDs as arguments (like the BSD @code{setpgrp}).
5550 @defmac AC_FUNC_STAT
5551 @defmacx AC_FUNC_LSTAT
5553 @acindex{FUNC_LSTAT}
5554 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5555 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5557 @prindex @code{stat}
5559 @prindex @code{lstat}
5560 @caindex func_stat_empty_string_bug
5561 @caindex func_lstat_empty_string_bug
5562 Determine whether @code{stat} or @code{lstat} have the bug that it
5563 succeeds when given the zero-length file name as argument.
5565 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5566 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5569 The results of these macros are cached in the
5570 @code{ac_cv_func_stat_empty_string_bug} and the
5571 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5573 These macros are obsolescent, as no current systems have the bug.
5574 New programs need not use these macros.
5577 @anchor{AC_FUNC_STRCOLL}
5578 @defmac AC_FUNC_STRCOLL
5579 @acindex{FUNC_STRCOLL}
5580 @cvindex HAVE_STRCOLL
5582 @prindex @code{strcoll}
5583 @caindex func_strcoll_works
5584 If the @code{strcoll} function exists and works correctly, define
5585 @code{HAVE_STRCOLL}. This does a bit more than
5586 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5587 definitions of @code{strcoll} that should not be used. But it does
5588 not check against a known bug of this function on Solaris 10.
5590 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5594 @defmac AC_FUNC_STRERROR_R
5595 @acindex{FUNC_STRERROR_R}
5596 @cvindex HAVE_STRERROR_R
5597 @cvindex HAVE_DECL_STRERROR_R
5598 @cvindex STRERROR_R_CHAR_P
5599 @c @fuindex strerror_r
5600 @caindex func_strerror_r_char_p
5601 @prindex @code{strerror_r}
5602 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5603 it is declared, define @code{HAVE_DECL_STRERROR_R}. If it returns a
5604 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5605 returns an @code{int} error number. The Thread-Safe Functions option of
5606 POSIX requires @code{strerror_r} to return @code{int}, but
5607 many systems (including, for example, version 2.2.4 of the GNU C
5608 Library) return a @code{char *} value that is not necessarily equal to
5609 the buffer argument.
5611 The result of this macro is cached in the
5612 @code{ac_cv_func_strerror_r_char_p} variable.
5614 The Gnulib module @code{strerror_r} not only ensures that the function
5615 has the return type specified by POSIX, but also works around other
5616 portability problems of this function.
5619 @anchor{AC_FUNC_STRFTIME}
5620 @defmac AC_FUNC_STRFTIME
5621 @acindex{FUNC_STRFTIME}
5622 @cvindex HAVE_STRFTIME
5623 @c @fuindex strftime
5624 @prindex @code{strftime}
5625 Check for @code{strftime} in the @file{intl} library.
5626 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5628 This macro is obsolescent, as no current systems require the @file{intl}
5629 library for @code{strftime}. New programs need not use this macro.
5632 @defmac AC_FUNC_STRTOD
5633 @acindex{FUNC_STRTOD}
5636 @prindex @code{strtod}
5637 @caindex func_strtod
5639 If the @code{strtod} function does not exist or doesn't work correctly,
5640 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}. In this case,
5641 because @file{strtod.c} is likely to need @samp{pow}, set the output
5642 variable @code{POW_LIB} to the extra library needed.
5644 This macro caches its result in the @code{ac_cv_func_strtod} variable
5645 and depends upon the result in the @code{ac_cv_func_pow} variable.
5647 The @code{AC_FUNC_STRTOD} macro is obsolescent. New programs should
5648 use Gnulib's @code{strtod} module. @xref{Gnulib}.
5651 @defmac AC_FUNC_STRTOLD
5652 @acindex{FUNC_STRTOLD}
5653 @cvindex HAVE_STRTOLD
5654 @prindex @code{strtold}
5655 @caindex func_strtold
5656 If the @code{strtold} function exists and conforms to C99 or later, define
5657 @code{HAVE_STRTOLD}.
5659 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5661 The Gnulib module @code{strtold} not only ensures that the
5662 function exists, but also works around other portability
5663 problems of this function.
5666 @defmac AC_FUNC_STRNLEN
5667 @acindex{FUNC_STRNLEN}
5668 @cvindex HAVE_STRNLEN
5670 @prindex @code{strnlen}
5671 @caindex func_strnlen_working
5672 If the @code{strnlen} function is not available, or is buggy (like the one
5673 from Android 5.0 or AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5675 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5678 The @code{AC_FUNC_STRNLEN} macro is obsolescent. New programs should
5679 use Gnulib's @code{strnlen} module. @xref{Gnulib}.
5682 @anchor{AC_FUNC_UTIME_NULL}
5683 @defmac AC_FUNC_UTIME_NULL
5684 @acindex{FUNC_UTIME_NULL}
5685 @cvindex HAVE_UTIME_NULL
5687 @prindex @code{utime}
5688 @caindex func_utime_null
5689 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5690 the present, define @code{HAVE_UTIME_NULL}.
5692 This macro caches its result in the @code{ac_cv_func_utime_null}
5695 This macro is obsolescent, as all current systems have a @code{utime}
5696 that behaves this way. New programs need not use this macro.
5699 @anchor{AC_FUNC_VPRINTF}
5700 @defmac AC_FUNC_VPRINTF
5701 @acindex{FUNC_VPRINTF}
5702 @cvindex HAVE_VPRINTF
5703 @cvindex HAVE_DOPRNT
5705 @prindex @code{vprintf}
5706 @c @fuindex vsprintf
5707 @prindex @code{vsprintf}
5708 If @code{vprintf} is found, define @code{HAVE_VPRINTF}. Otherwise, if
5709 @code{_doprnt} is found, define @code{HAVE_DOPRNT}. (If @code{vprintf}
5710 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5711 are also available.)
5713 This macro is obsolescent, as all current systems have @code{vprintf}.
5714 New programs need not use this macro.
5717 @defmac AC_REPLACE_FNMATCH
5718 @acindex{REPLACE_FNMATCH}
5720 @prindex @code{fnmatch}
5721 @hdrindex{fnmatch.h}
5722 @caindex func_fnmatch_works
5723 If the @code{fnmatch} function does not conform to POSIX (see
5724 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5726 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5727 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5728 copy of the source code of GNU @code{fnmatch}. If necessary,
5729 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5730 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5731 included in place of the system @code{<fnmatch.h>}.
5733 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5736 This macro is obsolescent, as it assumes the use of particular source
5737 files. New programs should use Gnulib's @code{fnmatch-posix} module,
5738 which provides this macro along with the source files. @xref{Gnulib}.
5743 @node Generic Functions
5744 @subsection Generic Function Checks
5746 These macros are used to find functions not covered by the ``particular''
5747 test macros. If the functions might be in libraries other than the
5748 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5749 If you need to check the behavior of a function as well as find out
5750 whether it is present, you have to write your own test for
5751 it (@pxref{Writing Tests}).
5753 @anchor{AC_CHECK_FUNC}
5754 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5755 @ovar{action-if-not-found})
5756 @acindex{CHECK_FUNC}
5757 @caindex func_@var{function}
5758 If C function @var{function} is available, run shell commands
5759 @var{action-if-found}, otherwise @var{action-if-not-found}. If you just
5760 want to define a symbol if the function is available, consider using
5761 @code{AC_CHECK_FUNCS} instead. This macro checks for functions with C
5762 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5763 standardized than C++. (@pxref{Language Choice}, for more information
5764 about selecting the language for checks.)
5766 This macro caches its result in the @code{ac_cv_func_@var{function}}
5770 @anchor{AC_CHECK_FUNCS}
5771 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5772 @ovar{action-if-not-found})
5773 @acindex{CHECK_FUNCS}
5774 @cvindex HAVE_@var{function}
5775 For each @var{function} enumerated in the blank-or-newline-separated argument
5776 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5777 If @var{action-if-found} is given, it is additional shell code to
5778 execute when one of the functions is found. You can give it a value of
5779 @samp{break} to break out of the loop on the first match. If
5780 @var{action-if-not-found} is given, it is executed when one of the
5781 functions is not found.
5783 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5786 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5787 @acindex{CHECK_FUNCS_ONCE}
5788 @cvindex HAVE_@var{function}
5789 For each @var{function} enumerated in the blank-or-newline-separated argument
5790 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5791 This is a once-only variant of @code{AC_CHECK_FUNCS}. It generates the
5792 checking code at most once, so that @command{configure} is smaller and
5793 faster; but the checks cannot be conditionalized and are always done once,
5794 early during the @command{configure} run.
5799 Autoconf follows a philosophy that was formed over the years by those
5800 who have struggled for portability: isolate the portability issues in
5801 specific files, and then program as if you were in a POSIX
5802 environment. Some functions may be missing or unfixable, and your
5803 package must be ready to replace them.
5805 Suitable replacements for many such problem functions are available from
5806 Gnulib (@pxref{Gnulib}).
5808 @defmac AC_LIBOBJ (@var{function})
5811 Specify that @samp{@var{function}.c} must be included in the executables
5812 to replace a missing or broken implementation of @var{function}.
5815 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5816 variable @code{LIBOBJS} if it is not already in, and calls
5817 @code{AC_LIBSOURCE} for @samp{@var{function}.c}. You should not
5818 directly change @code{LIBOBJS}, since this is not traceable.
5821 @defmac AC_LIBSOURCE (@var{file})
5823 Specify that @var{file} might be needed to compile the project. If you
5824 need to know what files might be needed by a @file{configure.ac}, you
5825 should trace @code{AC_LIBSOURCE}. @var{file} must be a literal.
5827 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5828 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}. In
5829 that case, since shell variables cannot be traced statically, you must
5830 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5831 might cause @code{AC_LIBOBJ} to need. For example, if you want to pass
5832 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5833 @code{"foo"} or @code{"bar"}, you should do:
5836 AC_LIBSOURCE([foo.c])
5837 AC_LIBSOURCE([bar.c])
5838 AC_LIBOBJ([$foo_or_bar])
5842 There is usually a way to avoid this, however, and you are encouraged to
5843 simply call @code{AC_LIBOBJ} with literal arguments.
5845 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5846 slightly different semantics: the old macro took the function name,
5847 e.g., @code{foo}, as its argument rather than the file name.
5850 @defmac AC_LIBSOURCES (@var{files})
5851 @acindex{LIBSOURCES}
5852 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5853 comma-separated M4 list. Thus, the above example might be rewritten:
5856 AC_LIBSOURCES([foo.c, bar.c])
5857 AC_LIBOBJ([$foo_or_bar])
5861 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5862 @acindex{CONFIG_LIBOBJ_DIR}
5863 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5864 @var{directory}, a name relative to the top level of the
5865 source tree. The replacement directory defaults to @file{.}, the top
5866 level directory, and the most typical value is @file{lib}, corresponding
5867 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5869 @command{configure} might need to know the replacement directory for the
5870 following reasons: (i) some checks use the replacement files, (ii) some
5871 macros bypass broken system headers by installing links to the
5872 replacement headers (iii) when used in conjunction with Automake,
5873 within each makefile, @var{directory} is used as a relative path
5874 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5875 @code{LTLIBOBJS}, etc.
5880 It is common to merely check for the existence of a function, and ask
5881 for its @code{AC_LIBOBJ} replacement if missing. The following macro is
5882 a convenient shorthand.
5884 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5885 @acindex{REPLACE_FUNCS}
5886 @cvindex HAVE_@var{function}
5888 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5889 @var{action-if-not-found}. You can declare your replacement function by
5890 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}. If the
5891 system has the function, it probably declares it in a header file you
5892 should be including, so you shouldn't redeclare it lest your declaration
5897 @section Header Files
5898 @cindex Header, checking
5900 The following macros check for the presence of certain C header files.
5901 If there is no macro specifically defined to check for a header file you need,
5902 and you don't need to check for any special properties of
5903 it, then you can use one of the general header-file check macros.
5906 * Header Portability:: Collected knowledge on common headers
5907 * Particular Headers:: Special handling to find certain headers
5908 * Generic Headers:: How to find other headers
5911 @node Header Portability
5912 @subsection Portability of Headers
5913 @cindex Portability of headers
5914 @cindex Header portability
5916 This section documents some collected knowledge about common headers,
5917 and the problems they cause. By definition, this list always requires
5918 additions. A much more complete list is maintained by the Gnulib
5919 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5920 POSIX Headers, gnulib, Gnulib} and @ref{Glibc Header File
5921 Substitutes, , Glibc Headers, gnulib, Gnulib}. Please help us keep
5922 the Gnulib list as complete as possible.
5924 When we say that a header ``may require'' some set of other headers, we
5925 mean that it may be necessary for you to manually include those other
5926 headers first, or the contents of the header under test will fail to
5927 compile. When checking for these headers, you must provide the
5928 potentially-required headers in the @var{includes} argument to
5929 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5930 fail spuriously. @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5931 arranges to include a number of common requirements and should normally
5932 come first in your @var{includes}. For example, @file{net/if.h} may
5933 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5934 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5935 @file{sys/socket.h}, so you should check for it like this:
5938 AC_CHECK_HEADERS([sys/socket.h])
5939 AC_CHECK_HEADERS([net/if.h], [], [],
5940 [AC_INCLUDES_DEFAULT[
5941 #ifdef HAVE_SYS_SOCKET_H
5942 # include <sys/socket.h>
5947 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5948 so that it gets expanded) and double quoting (to ensure that each
5949 preprocessor @code{#} gets treated as a literal string rather than a
5954 @item @file{limits.h}
5955 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5956 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5957 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5960 @item @file{memory.h}
5962 This header file is obsolete; use @file{string.h} instead.
5964 @item @file{strings.h}
5965 @hdrindex{strings.h}
5966 On some systems, this is the only header that declares
5967 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5969 This header may or may not include @file{string.h} for you. However, on
5970 all recent systems it is safe to include both @file{string.h} and
5971 @file{strings.h}, in either order, in the same source file.
5973 @item @file{inttypes.h} vs.@: @file{stdint.h}
5974 @hdrindex{inttypes.h}
5976 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5977 no need to include @file{stdint.h} separately in a standard environment.
5978 However, some implementations have @file{stdint.h} but not @file{inttypes.h}
5979 (e.g. MSVC 2012). Therefore, it is necessary to check for each and include
5980 each only if available.
5982 @item @file{linux/irda.h}
5983 @hdrindex{linux/irda.h}
5984 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5986 @item @file{linux/random.h}
5987 @hdrindex{linux/random.h}
5988 This header may require @file{linux/types.h}.
5990 @item @file{net/if.h}
5992 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5994 @item @file{netinet/if_ether.h}
5995 @hdrindex{netinet/if_ether.h}
5996 This header may require some combination of @file{sys/types.h},
5997 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5999 @item @file{sys/mount.h}
6000 @hdrindex{sys/mount.h}
6001 This header may require @file{sys/params.h}.
6003 @item @file{sys/ptem.h}
6004 @hdrindex{sys/ptem.h}
6005 This header may require @file{sys/stream.h}.
6007 @item @file{sys/socket.h}
6008 @hdrindex{sys/socket.h}
6009 This header may require @file{sys/types.h}.
6011 @item @file{sys/ucred.h}
6012 @hdrindex{sys/ucred.h}
6013 This header may require @file{sys/types.h}.
6015 @item @file{X11/extensions/scrnsaver.h}
6016 @hdrindex{X11/extensions/scrnsaver.h}
6017 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
6018 so required that you might not even consider looking for it.
6023 @node Particular Headers
6024 @subsection Particular Header Checks
6026 These macros check for particular system header files---whether they
6027 exist, and in some cases whether they declare certain symbols.
6029 @defmac AC_CHECK_HEADER_STDBOOL
6030 @acindex{CHECK_HEADER_STDBOOL}
6032 @hdrindex{stdbool.h}
6033 @caindex header_stdbool_h
6034 Check whether @file{stdbool.h} exists and conforms to C99 or later,
6035 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
6036 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
6038 This macro is obsolescent, as all current C compilers have @file{stdbool.h},
6039 a header that is itself obsolescent as of C23.
6041 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
6042 packages that supply a substitute @file{stdbool.h} on platforms lacking
6043 a conforming one. The @code{AC_HEADER_STDBOOL} macro is better for code
6044 that explicitly checks for @file{stdbool.h}.
6047 @defmac AC_HEADER_ASSERT
6048 @acindex{HEADER_ASSERT}
6051 Check whether to enable assertions in the style of @file{assert.h}.
6052 Assertions are enabled by default, but the user can override this by
6053 invoking @command{configure} with the @option{--disable-assert} option.
6056 @anchor{AC_HEADER_DIRENT}
6057 @defmac AC_HEADER_DIRENT
6058 @acindex{HEADER_DIRENT}
6059 @cvindex HAVE_DIRENT_H
6060 @cvindex HAVE_NDIR_H
6061 @cvindex HAVE_SYS_DIR_H
6062 @cvindex HAVE_SYS_NDIR_H
6064 @hdrindex{sys/ndir.h}
6065 @hdrindex{sys/dir.h}
6067 Check for the following header files. For the first one that is
6068 found and defines @samp{DIR}, define the listed C preprocessor macro:
6070 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
6071 @item @file{dirent.h} @tab @code{HAVE_DIRENT_H}
6072 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
6073 @item @file{sys/dir.h} @tab @code{HAVE_SYS_DIR_H}
6074 @item @file{ndir.h} @tab @code{HAVE_NDIR_H}
6077 The directory-library declarations in your source code should look
6078 something like the following:
6082 #include <sys/types.h>
6083 #ifdef HAVE_DIRENT_H
6084 # include <dirent.h>
6085 # define NAMLEN(dirent) strlen ((dirent)->d_name)
6087 # define dirent direct
6088 # define NAMLEN(dirent) ((dirent)->d_namlen)
6089 # ifdef HAVE_SYS_NDIR_H
6090 # include <sys/ndir.h>
6092 # ifdef HAVE_SYS_DIR_H
6093 # include <sys/dir.h>
6102 Using the above declarations, the program would declare variables to be
6103 of type @code{struct dirent}, not @code{struct direct}, and would access
6104 the length of a directory entry name by passing a pointer to a
6105 @code{struct dirent} to the @code{NAMLEN} macro.
6107 This macro also checks for the obsolete @file{dir} and @file{x} libraries.
6109 This macro is obsolescent, as all current systems with directory
6110 libraries have @code{<dirent.h>}. New programs need not use this macro.
6112 Also see @code{AC_STRUCT_DIRENT_D_INO} and
6113 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
6116 @anchor{AC_HEADER_MAJOR}
6117 @defmac AC_HEADER_MAJOR
6118 @acindex{HEADER_MAJOR}
6119 @cvindex MAJOR_IN_MKDEV
6120 @cvindex MAJOR_IN_SYSMACROS
6121 @hdrindex{sys/mkdev.h}
6122 @hdrindex{sys/sysmacros.h}
6123 Detect the headers required to use @code{makedev}, @code{major}, and
6124 @code{minor}. These functions may be defined by @file{sys/mkdev.h},
6125 @code{sys/sysmacros.h}, or @file{sys/types.h}.
6127 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
6128 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6129 @file{sys/sysmacros.h}. If neither macro is defined, they are either in
6130 @file{sys/types.h} or unavailable.
6132 To properly use these functions, your code should contain something
6136 #include <sys/types.h>
6137 #ifdef MAJOR_IN_MKDEV
6138 # include <sys/mkdev.h>
6139 #elif defined MAJOR_IN_SYSMACROS
6140 # include <sys/sysmacros.h>
6144 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6145 detect a problem if @file{sys/types.h} contains definitions of
6146 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6147 warnings upon use. This is known to occur with GNU libc 2.25, where
6148 those definitions are being deprecated to reduce namespace pollution.
6149 If it is not practical to use Autoconf 2.70 to regenerate the configure
6150 script of affected software, you can work around the problem by setting
6151 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6152 @command{configure} or as part of a @file{config.site} site default file
6153 (@pxref{Site Defaults}).
6156 @defmac AC_HEADER_RESOLV
6157 @acindex{HEADER_RESOLV}
6158 @cvindex HAVE_RESOLV_H
6160 Checks for header @file{resolv.h}, checking for prerequisites first.
6161 To properly use @file{resolv.h}, your code should contain something like
6165 #ifdef HAVE_SYS_TYPES_H
6166 # include <sys/types.h>
6168 #ifdef HAVE_NETINET_IN_H
6169 # include <netinet/in.h> /* inet_ functions / structs */
6171 #ifdef HAVE_ARPA_NAMESER_H
6172 # include <arpa/nameser.h> /* DNS HEADER struct */
6181 @anchor{AC_HEADER_STAT}
6182 @defmac AC_HEADER_STAT
6183 @acindex{HEADER_STAT}
6184 @cvindex STAT_MACROS_BROKEN
6185 @hdrindex{sys/stat.h}
6186 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6187 @file{sys/stat.h} do not work properly (returning false positives),
6188 define @code{STAT_MACROS_BROKEN}. This is the case on Tektronix UTekV,
6189 Amdahl UTS and Motorola System V/88.
6191 This macro is obsolescent, as no current systems have the bug.
6192 New programs need not use this macro.
6195 @defmac AC_HEADER_STDBOOL
6196 @acindex{HEADER_STDBOOL}
6197 @cvindex HAVE_STDBOOL_H
6199 @hdrindex{stdbool.h}
6200 @caindex header_stdbool_h
6201 If @file{stdbool.h} exists and conforms to C99 or later, define
6202 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6203 @code{HAVE__BOOL} to 1.
6205 This macro is obsolescent, as all current C compilers have
6206 @file{stdbool.h}, a header that is itself obsolescent as of C23.
6207 Nowadays programs that need @code{bool}, @code{true} and @code{false}
6208 can include @file{stdbool.h} unconditionally, without using
6209 @code{AC_HEADER_STDBOOL}, and if such a program needs to be portable
6210 only to C23 or later it need not even include @file{stdbool.h}.
6212 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6215 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6216 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6220 @anchor{AC_HEADER_STDC}
6221 @defmac AC_HEADER_STDC
6222 @acindex{HEADER_STDC}
6223 @cvindex STDC_HEADERS
6224 @caindex header_stdc
6226 This macro is obsolescent. Its sole effect is to make sure that all the
6227 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6228 Includes}), but not part of C89, have been checked for.
6230 All hosted environments that are still of interest for portable code
6231 provide all of the headers specified in C89 (as amended in 1995).
6234 @defmac AC_HEADER_SYS_WAIT
6235 @acindex{HEADER_SYS_WAIT}
6236 @cvindex HAVE_SYS_WAIT_H
6237 @hdrindex{sys/wait.h}
6238 @caindex header_sys_wait_h
6239 If @file{sys/wait.h} exists and is compatible with POSIX, define
6240 @code{HAVE_SYS_WAIT_H}. Incompatibility can occur if @file{sys/wait.h}
6241 does not exist, or if it uses the old BSD @code{union wait} instead
6242 of @code{int} to store a status value. If @file{sys/wait.h} is not
6243 POSIX compatible, then instead of including it, define the
6244 POSIX macros with their usual interpretations. Here is an
6249 #include <sys/types.h>
6250 #ifdef HAVE_SYS_WAIT_H
6251 # include <sys/wait.h>
6254 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6257 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6263 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6266 This macro is obsolescent, as current systems are compatible with POSIX.
6267 New programs need not use this macro.
6270 @cvindex _POSIX_VERSION
6272 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6273 POSIX systems. If there is no @file{unistd.h}, it is definitely
6274 not a POSIX system. However, some non-POSIX systems do
6275 have @file{unistd.h}.
6277 The way to check whether the system supports POSIX is:
6281 #ifdef HAVE_UNISTD_H
6282 # include <sys/types.h>
6283 # include <unistd.h>
6286 #ifdef _POSIX_VERSION
6287 /* Code for POSIX systems. */
6292 @defmac AC_HEADER_TIOCGWINSZ
6293 @acindex{HEADER_TIOCGWINSZ}
6294 @cvindex GWINSZ_IN_SYS_IOCTL
6295 @hdrindex{sys/ioctl.h}
6296 @hdrindex{termios.h}
6297 @c FIXME: I need clarifications from Jim.
6298 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6299 define @code{GWINSZ_IN_SYS_IOCTL}. Otherwise @code{TIOCGWINSZ} can be
6300 found in @file{<termios.h>}.
6306 #ifdef HAVE_TERMIOS_H
6307 # include <termios.h>
6310 #ifdef GWINSZ_IN_SYS_IOCTL
6311 # include <sys/ioctl.h>
6317 @node Generic Headers
6318 @subsection Generic Header Checks
6320 These macros are used to find system header files not covered by the
6321 ``particular'' test macros. If you need to check the contents of a header
6322 as well as find out whether it is present, you have to write your own
6323 test for it (@pxref{Writing Tests}).
6325 @anchor{AC_CHECK_HEADER}
6326 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6327 @ovar{action-if-not-found}, @ovar{includes})
6328 @acindex{CHECK_HEADER}
6329 @caindex header_@var{header-file}
6330 If the system header file @var{header-file} is compilable, execute shell
6331 commands @var{action-if-found}, otherwise execute
6332 @var{action-if-not-found}. If you just want to define a symbol if the
6333 header file is available, consider using @code{AC_CHECK_HEADERS}
6336 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6337 whatever might be required to appear above
6338 @samp{#include <@var{header-file}>} for it to compile without error.
6339 This can be anything, but will normally be additional @samp{#include}
6340 directives. If @var{includes} is omitted or empty, @file{configure} will
6341 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6342 @xref{Default Includes}.
6344 This macro used to check only for the @emph{presence} of a header, not
6345 whether its contents were acceptable to the compiler. Some older
6346 @command{configure} scripts rely on this behavior, so it is still
6347 available by specifying @samp{-} as @var{includes}. This mechanism is
6348 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6349 check is required should use @code{AC_PREPROC_IFELSE}.
6350 @xref{Running the Preprocessor}.
6352 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6353 variable, with characters not suitable for a variable name mapped to
6357 @anchor{AC_CHECK_HEADERS}
6358 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6359 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6361 @acindex{CHECK_HEADERS}
6362 @cvindex HAVE_@var{header}
6363 @caindex header_@var{header-file}
6364 For each given system header file @var{header-file} in the
6365 blank-separated argument list that exists, define
6366 @code{HAVE_@var{header-file}} (in all capitals). If @var{action-if-found}
6367 is given, it is additional shell code to execute when one of the header
6368 files is found. You can give it a value of @samp{break} to break out of
6369 the loop on the first match. If @var{action-if-not-found} is given, it
6370 is executed when one of the header files is not found.
6372 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6373 choose the set of preprocessor directives supplied before the header
6376 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6377 variable, with characters not suitable for a variable name mapped to
6381 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6382 @acindex{CHECK_HEADERS_ONCE}
6383 @cvindex HAVE_@var{header}
6384 For each given system header file @var{header-file} in the
6385 blank-separated argument list that exists, define
6386 @code{HAVE_@var{header-file}} (in all capitals).
6388 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6389 variant generates smaller, faster @command{configure} files. All
6390 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6391 pass, early during the @command{configure} run. The checks cannot be
6392 conditionalized, you cannot specify an @var{action-if-found} or
6393 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6394 for the prerequisites.
6397 In previous versions of Autoconf, these macros merely checked whether
6398 the header was accepted by the preprocessor. This was changed because
6399 the old test was inappropriate for typical uses. Headers are typically
6400 used to compile, not merely to preprocess, and the old behavior
6401 sometimes accepted headers that clashed at compile-time
6402 (@pxref{Present But Cannot Be Compiled}). If for some reason it is
6403 inappropriate to check whether a header is compilable, you should use
6404 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6407 Requiring each header to compile improves the robustness of the test,
6408 but it also requires you to make sure that the @var{includes} are
6409 correct. Most system headers nowadays make sure to @code{#include}
6410 whatever they require, or else have their dependencies satisfied by
6411 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6412 @pxref{Header Portability}, for known exceptions. In general, if you
6413 are looking for @file{bar.h}, which requires that @file{foo.h} be
6414 included first if it exists, you should do something like this:
6417 AC_CHECK_HEADERS([foo.h])
6418 AC_CHECK_HEADERS([bar.h], [], [],
6426 @section Declarations
6427 @cindex Declaration, checking
6429 The following macros check for the declaration of variables and
6430 functions. If there is no macro specifically defined to check for a
6431 symbol you need, then you can use the general macros (@pxref{Generic
6432 Declarations}) or, for more complex tests, you may use
6433 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6436 * Particular Declarations:: Macros to check for certain declarations
6437 * Generic Declarations:: How to find other declarations
6440 @node Particular Declarations
6441 @subsection Particular Declaration Checks
6443 There are no specific macros for declarations.
6445 @node Generic Declarations
6446 @subsection Generic Declaration Checks
6448 These macros are used to find declarations not covered by the ``particular''
6451 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6452 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6453 @acindex{CHECK_DECL}
6454 @caindex have_decl_@var{symbol}
6455 If @var{symbol} (a function, variable, or constant) is not declared in
6456 @var{includes} and a declaration is needed, run the shell commands
6457 @var{action-if-not-found}, otherwise @var{action-if-found}.
6458 @var{includes} is a series of include directives, defaulting to
6459 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6460 prior to the declaration under test.
6462 This macro actually tests whether @var{symbol} is defined as a macro or
6463 can be used as an r-value, not whether it is really declared, because it
6464 is much safer to avoid introducing extra declarations when they are not
6465 needed. In order to facilitate use of C++ and overloaded function
6466 declarations, it is possible to specify function argument types in
6467 parentheses for types which can be zero-initialized:
6470 AC_CHECK_DECL([basename(char *)])
6473 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6474 variable, with characters not suitable for a variable name mapped to
6478 @anchor{AC_CHECK_DECLS}
6479 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6480 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6481 @acindex{CHECK_DECLS}
6482 @cvindex HAVE_DECL_@var{symbol}
6483 @caindex have_decl_@var{symbol}
6484 For each of the @var{symbols} (@emph{comma}-separated list with optional
6485 function argument types for C++ overloads), define
6486 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6487 @var{symbol} is declared, otherwise to @samp{0}. If
6488 @var{action-if-not-found} is given, it is additional shell code to
6489 execute when one of the function declarations is needed, otherwise
6490 @var{action-if-found} is executed.
6492 @var{includes} is a series of include directives, defaulting to
6493 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6494 prior to the declarations under test.
6496 This macro uses an M4 list as first argument:
6498 AC_CHECK_DECLS([strdup])
6499 AC_CHECK_DECLS([strlen])
6500 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6501 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6502 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6505 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6506 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6507 of leaving @code{HAVE_DECL_@var{symbol}} undeclared. When you are
6508 @emph{sure} that the check was performed, use
6509 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6512 #if !HAVE_DECL_SYMBOL
6513 extern char *symbol;
6518 If the test may have not been performed, however, because it is safer
6519 @emph{not} to declare a symbol than to use a declaration that conflicts
6520 with the system's one, you should use:
6523 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6524 void *malloc (size_t *s);
6529 You fall into the second category only in extreme situations: either
6530 your files may be used without being configured, or they are used during
6531 the configuration. In most cases the traditional approach is enough.
6533 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6534 variables, with characters not suitable for a variable name mapped to
6538 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6539 @acindex{CHECK_DECLS_ONCE}
6540 @cvindex HAVE_DECL_@var{symbol}
6541 For each of the @var{symbols} (@emph{comma}-separated list), define
6542 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6543 @var{symbol} is declared in the default include files, otherwise to
6544 @samp{0}. This is a once-only variant of @code{AC_CHECK_DECLS}. It
6545 generates the checking code at most once, so that @command{configure} is
6546 smaller and faster; but the checks cannot be conditionalized and are
6547 always done once, early during the @command{configure} run.
6553 @cindex Structure, checking
6555 The following macros check for the presence of certain members in C
6556 structures. If there is no macro specifically defined to check for a
6557 member you need, then you can use the general structure-member macros
6558 (@pxref{Generic Structures}) or, for more complex tests, you may use
6559 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6562 * Particular Structures:: Macros to check for certain structure members
6563 * Generic Structures:: How to find other structure members
6566 @node Particular Structures
6567 @subsection Particular Structure Checks
6569 The following macros check for certain structures or structure members.
6571 @defmac AC_STRUCT_DIRENT_D_INO
6572 @acindex{STRUCT_DIRENT_D_INO}
6573 @cvindex HAVE_STRUCT_DIRENT_D_INO
6574 @c @caindex header_dirent_dirent_h
6575 @c @caindex member_struct_dirent_d_ino
6576 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6577 Headers}). Then, if @code{struct dirent} contains a @code{d_ino}
6578 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6580 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6581 @code{d_ino}, not whether its contents are always reliable.
6582 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6583 though current systems hide this detail from the user and never return
6584 zero @code{d_ino} values.
6585 Many current systems report an incorrect @code{d_ino} for a directory
6586 entry that is a mount point.
6589 @defmac AC_STRUCT_DIRENT_D_TYPE
6590 @acindex{STRUCT_DIRENT_D_TYPE}
6591 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6592 @c @caindex header_dirent_dirent_h
6593 @c @caindex member_struct_dirent_d_type
6594 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6595 Headers}). Then, if @code{struct dirent} contains a @code{d_type}
6596 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6599 @anchor{AC_STRUCT_ST_BLOCKS}
6600 @defmac AC_STRUCT_ST_BLOCKS
6601 @acindex{STRUCT_ST_BLOCKS}
6602 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6603 @cvindex HAVE_ST_BLOCKS
6605 @caindex member_struct_stat_st_blocks
6606 If @code{struct stat} contains an @code{st_blocks} member, define
6607 @code{HAVE_STRUCT_STAT_ST_BLOCKS}. Otherwise, require an
6608 @code{AC_LIBOBJ} replacement of @samp{fileblocks}. The former name,
6609 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6612 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6616 @defmac AC_STRUCT_TM
6618 @cvindex TM_IN_SYS_TIME
6620 @hdrindex{sys/time.h}
6621 If @file{time.h} does not define @code{struct tm}, define
6622 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6623 had better define @code{struct tm}.
6625 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6626 current systems. New programs need not use this macro.
6629 @anchor{AC_STRUCT_TIMEZONE}
6630 @defmac AC_STRUCT_TIMEZONE
6631 @acindex{STRUCT_TIMEZONE}
6632 @cvindex HAVE_DECL_TZNAME
6633 @cvindex HAVE_STRUCT_TM_TM_ZONE
6634 @cvindex HAVE_TM_ZONE
6635 @cvindex HAVE_TZNAME
6636 @c @caindex member_struct_tm_tm_zone
6637 @c @caindex struct_tm
6638 Figure out how to get the current timezone. If @code{struct tm} has a
6639 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6640 obsoleted @code{HAVE_TM_ZONE}). Otherwise, if the external array
6641 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6642 define @code{HAVE_DECL_TZNAME}.
6645 @node Generic Structures
6646 @subsection Generic Structure Checks
6648 These macros are used to find structure members not covered by the
6649 ``particular'' test macros.
6651 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6652 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6653 @dvar{includes, AC_INCLUDES_DEFAULT})
6654 @acindex{CHECK_MEMBER}
6655 @caindex member_@var{aggregate}_@var{member}
6656 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6657 If no @var{includes} are specified, the default includes are used
6658 (@pxref{Default Includes}).
6661 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6662 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6663 [[#include <pwd.h>]])
6666 You can use this macro for submembers:
6669 AC_CHECK_MEMBER(struct top.middle.bot)
6672 This macro caches its result in the
6673 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6674 characters not suitable for a variable name mapped to underscores.
6677 @anchor{AC_CHECK_MEMBERS}
6678 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6679 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6680 @acindex{CHECK_MEMBERS}
6681 @cvindex HAVE_@var{aggregate}_@var{member}
6682 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6683 @var{members} using the previous macro. When @var{member} belongs to
6684 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6685 capitals, with spaces and dots replaced by underscores). If
6686 @var{action-if-found} is given, it is executed for each of the found
6687 members. If @var{action-if-not-found} is given, it is executed for each
6688 of the members that could not be found.
6690 @var{includes} is a series of include directives, defaulting to
6691 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6692 prior to the members under test.
6694 This macro uses M4 lists:
6696 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6706 The following macros check for C types, either builtin or typedefs. If
6707 there is no macro specifically defined to check for a type you need, and
6708 you don't need to check for any special properties of it, then you can
6709 use a general type-check macro.
6712 * Particular Types:: Special handling to find certain types
6713 * Generic Types:: How to find other types
6716 @node Particular Types
6717 @subsection Particular Type Checks
6719 @hdrindex{sys/types.h}
6722 @hdrindex{inttypes.h}
6723 These macros check for particular C types in @file{sys/types.h},
6724 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6727 The Gnulib @code{stdint} module is an alternate way to define many of
6728 these symbols; it is useful if you prefer your code to assume a
6729 C99-or-better environment. @xref{Gnulib}.
6731 @anchor{AC_TYPE_GETGROUPS}
6732 @defmac AC_TYPE_GETGROUPS
6733 @acindex{TYPE_GETGROUPS}
6734 @cvindex GETGROUPS_T
6735 @caindex type_getgroups
6736 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6737 is the base type of the array argument to @code{getgroups}.
6739 This macro caches the base type in the @code{ac_cv_type_getgroups}
6743 @defmac AC_TYPE_INT8_T
6744 @acindex{TYPE_INT8_T}
6745 @cvindex HAVE_INT8_T
6748 If @file{stdint.h} or @file{inttypes.h} does not define the type
6749 @code{int8_t}, define @code{int8_t} to a signed
6750 integer type that is exactly 8 bits wide and that uses two's complement
6751 representation, if such a type exists.
6752 If you are worried about porting to hosts that lack such a type, you can
6753 use the results of this macro as follows:
6757 # include <stdint.h>
6759 #if defined INT8_MAX || defined int8_t
6760 @emph{code using int8_t}
6762 @emph{complicated alternative using >8-bit 'signed char'}
6766 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6769 @defmac AC_TYPE_INT16_T
6770 @acindex{TYPE_INT16_T}
6771 @cvindex HAVE_INT16_T
6774 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6777 @defmac AC_TYPE_INT32_T
6778 @acindex{TYPE_INT32_T}
6779 @cvindex HAVE_INT32_T
6782 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6785 @defmac AC_TYPE_INT64_T
6786 @acindex{TYPE_INT64_T}
6787 @cvindex HAVE_INT64_T
6790 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6793 @defmac AC_TYPE_INTMAX_T
6794 @acindex{TYPE_INTMAX_T}
6795 @cvindex HAVE_INTMAX_T
6797 @c @caindex type_intmax_t
6798 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6799 define @code{HAVE_INTMAX_T}. Otherwise, define @code{intmax_t} to the
6800 widest signed integer type.
6803 @defmac AC_TYPE_INTPTR_T
6804 @acindex{TYPE_INTPTR_T}
6805 @cvindex HAVE_INTPTR_T
6807 @c @caindex type_intptr_t
6808 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6809 define @code{HAVE_INTPTR_T}. Otherwise, define @code{intptr_t} to a
6810 signed integer type wide enough to hold a pointer, if such a type
6814 @defmac AC_TYPE_LONG_DOUBLE
6815 @acindex{TYPE_LONG_DOUBLE}
6816 @cvindex HAVE_LONG_DOUBLE
6817 @caindex type_long_double
6818 If the C compiler supports a working @code{long double} type, define
6819 @code{HAVE_LONG_DOUBLE}. The @code{long double} type might have the
6820 same range and precision as @code{double}.
6822 This macro caches its result in the @code{ac_cv_type_long_double}
6825 This macro is obsolescent, as current C compilers support @code{long
6826 double}. New programs need not use this macro.
6829 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6830 @acindex{TYPE_LONG_DOUBLE_WIDER}
6831 @cvindex HAVE_LONG_DOUBLE_WIDER
6832 @caindex type_long_double_wider
6833 If the C compiler supports a working @code{long double} type with more
6834 range or precision than the @code{double} type, define
6835 @code{HAVE_LONG_DOUBLE_WIDER}.
6837 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6841 @defmac AC_TYPE_LONG_LONG_INT
6842 @acindex{TYPE_LONG_LONG_INT}
6843 @cvindex HAVE_LONG_LONG_INT
6844 @caindex type_long_long_int
6845 If the C compiler supports a working @code{long long int} type, define
6846 @code{HAVE_LONG_LONG_INT}. However, this test does not test
6847 @code{long long int} values in preprocessor @code{#if} expressions,
6848 because too many compilers mishandle such expressions.
6849 @xref{Preprocessor Arithmetic}.
6851 This macro caches its result in the @code{ac_cv_type_long_long_int}
6855 @defmac AC_TYPE_MBSTATE_T
6856 @acindex{TYPE_MBSTATE_T}
6859 @caindex type_mbstate_t
6860 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6861 @code{mbstate_t} type. Also, define @code{mbstate_t} to be a type if
6862 @code{<wchar.h>} does not declare it.
6864 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6868 @anchor{AC_TYPE_MODE_T}
6869 @defmac AC_TYPE_MODE_T
6870 @acindex{TYPE_MODE_T}
6872 @caindex type_mode_t
6873 Define @code{mode_t} to a suitable type, if standard headers do not
6876 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6879 @anchor{AC_TYPE_OFF_T}
6880 @defmac AC_TYPE_OFF_T
6881 @acindex{TYPE_OFF_T}
6884 Define @code{off_t} to a suitable type, if standard headers do not
6887 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6890 @anchor{AC_TYPE_PID_T}
6891 @defmac AC_TYPE_PID_T
6892 @acindex{TYPE_PID_T}
6895 Define @code{pid_t} to a suitable type, if standard headers do not
6898 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6901 @anchor{AC_TYPE_SIZE_T}
6902 @defmac AC_TYPE_SIZE_T
6903 @acindex{TYPE_SIZE_T}
6905 @caindex type_size_t
6906 Define @code{size_t} to a suitable type, if standard headers do not
6909 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6912 @defmac AC_TYPE_SSIZE_T
6913 @acindex{TYPE_SSIZE_T}
6915 @caindex type_ssize_t
6916 Define @code{ssize_t} to a suitable type, if standard headers do not
6919 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6922 @anchor{AC_TYPE_UID_T}
6923 @defmac AC_TYPE_UID_T
6924 @acindex{TYPE_UID_T}
6928 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6929 headers do not define them.
6931 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6934 @defmac AC_TYPE_UINT8_T
6935 @acindex{TYPE_UINT8_T}
6936 @cvindex HAVE_UINT8_T
6939 If @file{stdint.h} or @file{inttypes.h} does not define the type
6940 @code{uint8_t}, define @code{uint8_t} to an
6941 unsigned integer type that is exactly 8 bits wide, if such a type
6943 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6946 @defmac AC_TYPE_UINT16_T
6947 @acindex{TYPE_UINT16_T}
6948 @cvindex HAVE_UINT16_T
6951 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6954 @defmac AC_TYPE_UINT32_T
6955 @acindex{TYPE_UINT32_T}
6956 @cvindex HAVE_UINT32_T
6959 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6962 @defmac AC_TYPE_UINT64_T
6963 @acindex{TYPE_UINT64_T}
6964 @cvindex HAVE_UINT64_T
6967 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6970 @defmac AC_TYPE_UINTMAX_T
6971 @acindex{TYPE_UINTMAX_T}
6972 @cvindex HAVE_UINTMAX_T
6974 @c @caindex type_uintmax_t
6975 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6976 define @code{HAVE_UINTMAX_T}. Otherwise, define @code{uintmax_t} to the
6977 widest unsigned integer type.
6980 @defmac AC_TYPE_UINTPTR_T
6981 @acindex{TYPE_UINTPTR_T}
6982 @cvindex HAVE_UINTPTR_T
6984 @c @caindex type_uintptr_t
6985 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6986 define @code{HAVE_UINTPTR_T}. Otherwise, define @code{uintptr_t} to an
6987 unsigned integer type wide enough to hold a pointer, if such a type
6991 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6992 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6993 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6994 @caindex type_unsigned_long_long_int
6995 If the C compiler supports a working @code{unsigned long long int} type,
6996 define @code{HAVE_UNSIGNED_LONG_LONG_INT}. However, this test does not test
6997 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6998 because too many compilers mishandle such expressions.
6999 @xref{Preprocessor Arithmetic}.
7001 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
7006 @subsection Generic Type Checks
7008 These macros are used to check for types not covered by the ``particular''
7011 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
7012 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7013 @acindex{CHECK_TYPE}
7014 @caindex type_@var{type}
7015 Check whether @var{type} is defined. It may be a compiler builtin type
7016 or defined by the @var{includes}. @var{includes} is a series of include
7017 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
7018 Includes}), which are used prior to the type under test.
7020 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
7021 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not). The
7022 same test is applied when compiling for C++, which means that in C++
7023 @var{type} should be a type-id and should not be an anonymous
7024 @samp{struct} or @samp{union}.
7026 This macro caches its result in the @code{ac_cv_type_@var{type}}
7027 variable, with @samp{*} mapped to @samp{p} and other characters not
7028 suitable for a variable name mapped to underscores.
7032 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
7033 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7034 @acindex{CHECK_TYPES}
7035 @cvindex HAVE_@var{type}
7036 For each @var{type} of the @var{types} that is defined, define
7037 @code{HAVE_@var{type}} (in all capitals). Each @var{type} must follow
7038 the rules of @code{AC_CHECK_TYPE}. If no @var{includes} are
7039 specified, the default includes are used (@pxref{Default Includes}). If
7040 @var{action-if-found} is given, it is additional shell code to execute
7041 when one of the types is found. If @var{action-if-not-found} is given,
7042 it is executed when one of the types is not found.
7044 This macro uses M4 lists:
7046 AC_CHECK_TYPES([ptrdiff_t])
7047 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
7048 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
7053 Autoconf, up to 2.13, used to provide to another version of
7054 @code{AC_CHECK_TYPE}, broken by design. In order to keep backward
7055 compatibility, a simple heuristic, quite safe but not totally, is
7056 implemented. In case of doubt, read the documentation of the former
7057 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
7060 @node Compilers and Preprocessors
7061 @section Compilers and Preprocessors
7063 @cindex Preprocessors
7066 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
7067 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
7068 the output of the compiler, typically to the empty string if
7069 POSIX and @samp{.exe} if a DOS variant.
7072 They also define the output variable @code{OBJEXT} based on the
7073 output of the compiler, after @file{.c} files have been excluded, typically
7074 to @samp{o} if POSIX, @samp{obj} if a DOS variant.
7076 If the compiler being used does not produce executables, the tests fail. If
7077 the executables can't be run, and cross-compilation is not enabled, they
7078 fail too. @xref{Manual Configuration}, for more on support for cross
7082 * Specific Compiler Characteristics:: Some portability issues
7083 * Generic Compiler Characteristics:: Language independent tests and features
7084 * C Compiler:: Checking its characteristics
7085 * C++ Compiler:: Likewise
7086 * Objective C Compiler:: Likewise
7087 * Objective C++ Compiler:: Likewise
7088 * Erlang Compiler and Interpreter:: Likewise
7089 * Fortran Compiler:: Likewise
7090 * Go Compiler:: Likewise
7093 @node Specific Compiler Characteristics
7094 @subsection Specific Compiler Characteristics
7096 Some compilers exhibit different behaviors.
7099 @item Static/Dynamic Expressions
7100 Autoconf relies on a trick to extract one bit of information from the C
7101 compiler: using negative array sizes. For instance the following
7102 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7106 static int test_array[sizeof (int) == 4 ? 1 : -1];
7110 To our knowledge, there is a single compiler that does not support this
7111 trick: the HP C compilers (the real ones, not only the
7112 ``bundled'') on HP-UX 11.00.
7113 They incorrectly reject the above program with the diagnostic
7114 ``Variable-length arrays cannot have static storage.''
7115 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7116 not from the @code{? 1 : -1}, and
7117 Autoconf works around this problem by casting @code{sizeof (int)} to
7118 @code{long int} before comparing it.
7121 @node Generic Compiler Characteristics
7122 @subsection Generic Compiler Characteristics
7124 @anchor{AC_CHECK_SIZEOF}
7125 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7126 @dvar{includes, AC_INCLUDES_DEFAULT})
7127 @acindex{CHECK_SIZEOF}
7128 @cvindex SIZEOF_@var{type-or-expr}
7129 @caindex sizeof_@var{type-or-expr}
7130 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7131 the size in bytes of @var{type-or-expr}, which may be either a type or
7132 an expression returning a value that has a size. If the expression
7133 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7134 @var{includes} is a series of include directives, defaulting to
7135 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7136 prior to the expression under test.
7138 This macro now works even when cross-compiling. The @var{unused}
7139 argument was used when cross-compiling.
7141 For example, the call
7144 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7145 AC_CHECK_SIZEOF([int *])
7149 defines @code{SIZEOF_INT_P} to be 8 on x86-64 systems.
7151 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7152 variable, with @samp{*} mapped to @samp{p} and other characters not
7153 suitable for a variable name mapped to underscores.
7156 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7157 @acindex{CHECK_ALIGNOF}
7158 @cvindex ALIGNOF_@var{type}
7159 @caindex alignof_@var{type-or-expr}
7160 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7161 alignment in bytes of @var{type}. @samp{@var{type} y;} must be valid as
7162 a structure member declaration. If @samp{type} is unknown, the result
7163 is 0. If no @var{includes} are specified, the default includes are used
7164 (@pxref{Default Includes}).
7166 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7167 variable, with @samp{*} mapped to @samp{p} and other characters not
7168 suitable for a variable name mapped to underscores.
7171 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7172 @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7173 @acindex{COMPUTE_INT}
7174 Store into the shell variable @var{var} the value of the integer
7175 @var{expression}. The
7176 value should fit in an initializer in a C variable of type @code{signed
7177 long}. To support cross compilation, it should be possible to evaluate
7178 the expression at compile-time. If no @var{includes} are specified, the
7179 default includes are used (@pxref{Default Includes}).
7181 Execute @var{action-if-fails} if the value cannot be determined correctly.
7184 @defmac AC_LANG_WERROR
7185 @acindex{LANG_WERROR}
7186 Normally Autoconf ignores warnings generated by the compiler, linker, and
7187 preprocessor. If this macro is used, warnings count as fatal
7188 errors for the current language. This macro is useful when the
7189 results of configuration are used where warnings are unacceptable; for
7190 instance, if parts of a program are built with the GCC
7192 option. If the whole program is built using @option{-Werror} it is
7193 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7200 @ovindex OPENMP_CFLAGS
7201 @ovindex OPENMP_CXXFLAGS
7202 @ovindex OPENMP_FFLAGS
7203 @ovindex OPENMP_FCFLAGS
7204 @caindex prog_c_openmp
7205 @caindex prog_cxx_openmp
7206 @caindex prog_f77_openmp
7207 @caindex prog_fc_openmp
7208 @uref{https://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7209 and Fortran that simplify optimization of shared memory parallelism,
7210 which is a common problem on multi-core CPUs.
7212 If the current language is C, the macro @code{AC_OPENMP} sets the
7213 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7214 supporting OpenMP@. @code{OPENMP_CFLAGS} is set to empty if the
7215 compiler already supports OpenMP, if it has no way to activate OpenMP
7216 support, or if the user rejects OpenMP support by invoking
7217 @samp{configure} with the @samp{--disable-openmp} option.
7219 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7220 preprocessing program source, and when linking programs. Therefore you
7221 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7222 that use OpenMP@. If you preprocess OpenMP-specific C code, you also
7223 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}. The presence of
7224 OpenMP support is revealed at compile time by the preprocessor macro
7227 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7228 shared library to the program's dependencies, so its use is recommended
7229 only on programs that actually require OpenMP.
7231 If the current language is C++, @code{AC_OPENMP} sets the variable
7232 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler. The same remarks
7235 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7236 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7237 respectively. Similar remarks as for C hold, except that
7238 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7239 signals OpenMP support.
7241 For portability, it is best to avoid spaces between @samp{#} and
7242 @samp{pragma omp}. That is, write @samp{#pragma omp}, not
7243 @samp{# pragma omp}. The Sun WorkShop 6.2 C compiler chokes on the
7246 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7247 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7248 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7250 @strong{Caution:} Some of the compiler options that @code{AC_OPENMP}
7251 tests, mean ``enable OpenMP'' to one compiler, but ``write output to a
7252 file named @file{mp} or @file{penmp}'' to other compilers. We cannot
7253 guarantee that the implementation of @code{AC_OPENMP} will not overwrite
7254 an existing file with either of these names.
7256 Therefore, as a defensive measure, a @command{configure} script that
7257 uses @code{AC_OPENMP} will issue an error and stop (before doing any of
7258 the operations that might overwrite these files) upon encountering
7259 either of these files in its working directory.
7260 @command{autoconf} will also issue an error if it finds either of
7261 these files in the same directory as a @file{configure.ac} that
7262 uses @code{AC_OPENMP}.
7264 If you have files with either of these names at the top level of your
7265 source tree, and you need to use @code{AC_OPENMP}, we recommend you
7266 either change their names or move them into a subdirectory.
7270 @subsection C Compiler Characteristics
7272 The following macros provide ways to find and exercise a C Compiler.
7273 There are a few constructs that ought to be avoided, but do not deserve
7274 being checked for, since they can easily be worked around.
7277 @item Don't use lines containing solitary backslashes
7278 They tickle a bug in the HP-UX C compiler (checked on
7280 11.00, and 11i). When given the following source:
7285 * A comment with backslash-newlines in it. %@{ %@} *\
7289 " A string with backslash-newlines in it %@{ %@} \\
7291 char apostrophe = '\\
7299 the compiler incorrectly fails with the diagnostics ``Non-terminating
7300 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7301 Removing the lines with solitary backslashes solves the problem.
7303 @item Don't compile several files at once if output matters to you
7304 Some compilers, such as HP's, report names of files being
7305 compiled when given more than one file operand. For instance:
7314 This can cause problems if you observe the output of the compiler to
7315 detect failures. Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7316 b.o} solves the issue.
7318 @item Don't rely on correct @code{#line} support
7319 On Solaris, @command{c89} (at least through Oracle Developer Studio 12.6)
7320 diagnoses @code{#line} directives whose line
7321 numbers are greater than 32767. Nothing in POSIX
7322 makes this invalid. That is why Autoconf stopped issuing
7323 @code{#line} directives.
7327 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7333 Determine a C compiler to use.
7335 If the environment variable @code{CC} is set, its value will be taken as
7336 the name of the C compiler to use. Otherwise, search for a C compiler
7337 under a series of likely names, trying @code{gcc} and @code{cc} first.
7338 Regardless, the output variable @code{CC} is set to the chosen compiler.
7340 If the optional first argument to the macro is used, it must be a
7341 whitespace-separated list of potential names for a C compiler,
7342 which overrides the built-in list.
7344 If no C compiler can be found, @command{configure} will error out.
7346 If the selected C compiler is found to be GNU C (regardless of
7347 its name), the shell variable @code{GCC} will be set to @samp{yes}.
7348 If the shell variable @code{CFLAGS} was not already set, it is set
7349 to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7350 where GCC does not accept @option{-g}), or @option{-g} for other
7351 compilers. @code{CFLAGS} is then made an output variable.
7352 You can override the default for @code{CFLAGS} by inserting a shell
7353 default assignment between @code{AC_INIT} and @code{AC_PROG_CC}:
7356 : $@{CFLAGS="@var{options}"@}
7359 where @var{options} are the appropriate set of options to use by
7360 default. (It is important to use this construct rather than a normal
7361 assignment, so that @code{CFLAGS} can still be overridden by the
7362 person building the package. @xref{Preset Output Variables}.)
7364 If necessary, options are added to @code{CC} to enable support for
7365 ISO Standard C features with extensions, preferring the newest edition
7366 of the C standard for which detection is supported. Currently the
7367 newest edition Autoconf knows how to detect support for is C23. After calling
7368 this macro you can check whether the C compiler has been set to accept
7369 standard C by inspecting the shell variable @code{ac_prog_cc_stdc}.
7370 Its value is @samp{c23}, @samp{c11}, @samp{c99}, or @samp{c89}, respectively,
7371 if the C compiler has been set to use the 2023, 2011, 1999, or 1990 edition of
7372 the C standard, and @samp{no} if the compiler does not support compiling
7374 (There is no special value for the 2017 edition of the C standard,
7375 as it is a minor revision that does not introduce new language features.)
7377 The tests for standard conformance are not comprehensive. They test the
7378 value of @code{__STDC_VERSION__}, and a
7379 representative sample of the language features added in each version of
7380 the C standard. They do not examine @code{__STDC__}
7381 because some compilers by default leave it undefined.
7382 They do not test for variable-length arrays,
7383 a C99 feature that was made optional in C11;
7384 if you need to use this feature when available, use @code{AC_C_VARARRAYS}.
7385 They do not test the C standard library, because the C
7386 compiler might be generating code for a ``freestanding environment''
7387 (in which most of the standard library is optional). If you need to know
7388 whether a particular C standard header exists, use @code{AC_CHECK_HEADER}.
7390 None of the options that may be added to @code{CC} by this macro
7391 enable @emph{strict} conformance to the C standard. In particular,
7392 system-specific extensions are not disabled. (For example, for GNU C,
7393 the @option{-std=gnu@var{nn}} options may be used, but not the
7394 @option{-std=c@var{nn}} options.)
7396 Many Autoconf macros use a compiler, and thus call
7397 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7398 determined before the body of the outermost @code{AC_DEFUN} macro.
7399 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7400 performs certain checks (such as the proper value of @env{EXEEXT}) only
7401 on the first invocation. Therefore, care must be used when invoking
7402 this macro from within another macro rather than at the top level
7403 (@pxref{Expanded Before Required}).
7406 @anchor{AC_PROG_CC_C_O}
7407 @defmac AC_PROG_CC_C_O
7408 @acindex{PROG_CC_C_O}
7409 @cvindex NO_MINUS_C_MINUS_O
7410 @caindex prog_cc_@var{compiler}_c_o
7411 If the C compiler does not accept the @option{-c} and @option{-o} options
7412 simultaneously, define @code{NO_MINUS_C_MINUS_O}. This macro actually
7413 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7414 the first @code{cc} in the path. The test fails if one fails. This
7415 macro was created for GNU Make to choose the default C compilation
7418 For the compiler @var{compiler}, this macro caches its result in the
7419 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7427 Set output variable @code{CPP} to a command that runs the
7428 C preprocessor. If @samp{$CC -E} doesn't work, tries @code{cpp} and
7429 @file{/lib/cpp}, in that order.
7431 It is only portable to run @code{CPP} on files with a @file{.c}
7434 Some preprocessors don't indicate missing include files by the error
7435 status. For such preprocessors an internal variable is set that causes
7436 other macros to check the standard error from the preprocessor and
7437 consider the test failed if any warnings have been reported.
7438 For most preprocessors, though, warnings do not cause include-file
7439 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7442 @defmac AC_PROG_CPP_WERROR
7443 @acindex{PROG_CPP_WERROR}
7445 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7446 preprocessor as errors even if the preprocessor exit status indicates
7447 success. This is useful for avoiding headers that generate mandatory
7448 warnings, such as deprecation notices.
7452 The following macros check for C compiler or machine architecture
7453 features. To check for characteristics not listed here, use
7454 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7455 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7457 @defmac AC_C_BACKSLASH_A
7458 @acindex{C_BACKSLASH_A}
7459 @cvindex HAVE_C_BACKSLASH_A
7460 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7463 This macro is obsolescent, as current C compilers understand @samp{\a}.
7464 New programs need not use this macro.
7467 @anchor{AC_C_BIGENDIAN}
7468 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7469 @ovar{action-if-unknown}, @ovar{action-if-universal})
7470 @acindex{C_BIGENDIAN}
7471 @cvindex WORDS_BIGENDIAN
7473 If words are stored with the most significant byte first (like Motorola
7474 and SPARC CPUs), execute @var{action-if-true}. If words are stored with
7475 the least significant byte first (like Intel and VAX CPUs), execute
7476 @var{action-if-false}.
7478 This macro runs a test-case if endianness cannot be determined from the
7479 system header files. When cross-compiling, the test-case is not run but
7480 grep'ed for some magic values. @var{action-if-unknown} is executed if
7481 the latter case fails to determine the byte sex of the host system.
7483 In some cases a single run of a compiler can generate code for multiple
7484 architectures. This can happen, for example, when generating Mac OS X
7485 universal binary files, which work on both PowerPC and Intel
7486 architectures. In this case, the different variants might be for
7487 architectures with differing endianness. If
7488 @command{configure} detects this, it executes @var{action-if-universal}
7489 instead of @var{action-if-unknown}.
7491 The default for @var{action-if-true} is to define
7492 @samp{WORDS_BIGENDIAN}. The default for @var{action-if-false} is to do
7493 nothing. The default for @var{action-if-unknown} is to
7494 abort configure and tell the installer how to bypass this test.
7495 And finally, the default for @var{action-if-universal} is to ensure that
7496 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7497 detected and the current code is big-endian; this default works only if
7498 @command{autoheader} is used (@pxref{autoheader Invocation}).
7500 If you use this macro without specifying @var{action-if-universal}, you
7501 should also use @code{AC_CONFIG_HEADERS}; otherwise
7502 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7511 If the C compiler does not fully support the @code{const} keyword,
7512 define @code{const} to be empty. Some C compilers that do
7513 not define @code{__STDC__} do support @code{const}; some compilers that
7514 define @code{__STDC__} do not completely support @code{const}. Programs
7515 can simply use @code{const} as if every C compiler supported it; for
7516 those that don't, the makefile or configuration header file
7517 defines it as empty.
7519 Occasionally installers use a C++ compiler to compile C code, typically
7520 because they lack a C compiler. This causes problems with @code{const},
7521 because C and C++ treat @code{const} differently. For example:
7528 is valid in C but not in C++. These differences unfortunately cannot be
7529 papered over by defining @code{const} to be empty.
7531 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7532 as this generally yields better results in practice. However, using a
7533 C++ compiler to compile C code is not recommended or supported, and
7534 installers who run into trouble in this area should get a C compiler
7535 like GCC to compile their C code.
7537 This macro caches its result in the @code{ac_cv_c_const} variable.
7539 This macro is obsolescent, as current C compilers support @code{const}.
7540 New programs need not use this macro.
7543 @defmac AC_C__GENERIC
7544 @acindex{C__GENERIC}
7546 If the C compiler supports C11-style generic selection using the
7547 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7550 @defmac AC_C_RESTRICT
7551 @acindex{C_RESTRICT}
7554 If the C compiler recognizes a variant spelling for the @code{restrict}
7555 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7556 then define @code{restrict} to that; this is more likely to do the right
7557 thing with compilers that support language variants where plain
7558 @code{restrict} is not a keyword. Otherwise, if the C compiler
7559 recognizes the @code{restrict} keyword, don't do anything.
7560 Otherwise, define @code{restrict} to be empty.
7561 Thus, programs may simply use @code{restrict} as if every C compiler
7562 supported it; for those that do not, the makefile
7563 or configuration header defines it away.
7565 Although support in C++ for the @code{restrict} keyword is not
7566 required, several C++ compilers do accept the keyword.
7567 This macro works for them, too.
7569 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7570 if @code{restrict} is not supported, and a supported spelling otherwise.
7573 @defmac AC_C_VOLATILE
7574 @acindex{C_VOLATILE}
7576 If the C compiler does not understand the keyword @code{volatile},
7577 define @code{volatile} to be empty. Programs can simply use
7578 @code{volatile} as if every C compiler supported it; for those that do
7579 not, the makefile or configuration header defines it as
7582 If the correctness of your program depends on the semantics of
7583 @code{volatile}, simply defining it to be empty does, in a sense, break
7584 your code. However, given that the compiler does not support
7585 @code{volatile}, you are at its mercy anyway. At least your
7586 program compiles, when it wouldn't before.
7587 @xref{Volatile Objects}, for more about @code{volatile}.
7589 This macro is obsolescent, as current C compilers support @code{volatile}.
7590 New programs need not use this macro.
7593 @anchor{AC_C_INLINE}
7597 If the C compiler supports the keyword @code{inline}, do nothing.
7598 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7599 if it accepts one of those, otherwise define @code{inline} to be empty.
7602 @anchor{AC_C_CHAR_UNSIGNED}
7603 @defmac AC_C_CHAR_UNSIGNED
7604 @acindex{C_CHAR_UNSIGNED}
7605 @cvindex __CHAR_UNSIGNED__
7606 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7607 unless the C compiler predefines it.
7609 These days, using this macro is not necessary. The same information can
7610 be determined by this portable alternative, thus avoiding the use of
7611 preprocessor macros in the namespace reserved for the implementation.
7616 # define CHAR_UNSIGNED 1
7621 @defmac AC_C_STRINGIZE
7622 @acindex{C_STRINGIZE}
7623 @cvindex HAVE_STRINGIZE
7624 If the C preprocessor supports the stringizing operator, define
7625 @code{HAVE_STRINGIZE}. The stringizing operator is @samp{#} and is
7626 found in macros such as this:
7632 This macro is obsolescent, as current C compilers support the
7633 stringizing operator. New programs need not use this macro.
7636 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7637 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7638 @cvindex FLEXIBLE_ARRAY_MEMBER
7639 If the C compiler supports flexible array members, define
7640 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7641 That way, a declaration like this:
7647 double val[FLEXIBLE_ARRAY_MEMBER];
7652 will let applications use the ``struct hack'' even with compilers that
7653 do not support flexible array members. To allocate and use such an
7654 object, you can use code like this:
7658 size_t n = compute_value_count ();
7660 malloc (offsetof (struct s, val)
7661 + n * sizeof (double));
7663 for (i = 0; i < n; i++)
7664 p->val[i] = compute_value (i);
7668 @defmac AC_C_VARARRAYS
7669 @acindex{C_VARARRAYS}
7670 @cvindex __STDC_NO_VLA__
7671 @cvindex HAVE_C_VARARRAYS
7672 If the C compiler does not support variable-length arrays, define the
7673 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined. A
7674 variable-length array is an array of automatic storage duration whose
7675 length is determined at run time, when the array is declared. For
7676 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7677 if the C compiler supports variable-length arrays, but this usage is
7678 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7683 @cvindex HAVE_TYPEOF
7685 If the C compiler supports GNU C's @code{typeof} syntax either
7687 through a different spelling of the keyword (e.g., @code{__typeof__}),
7688 define @code{HAVE_TYPEOF}. If the support is available only through a
7689 different spelling, define @code{typeof} to that spelling.
7692 @defmac AC_C_PROTOTYPES
7693 @acindex{C_PROTOTYPES}
7695 @cvindex __PROTOTYPES
7697 If function prototypes are understood by the compiler (as determined by
7698 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7699 Defining @code{__PROTOTYPES} is for the benefit of
7700 header files that cannot use macros that infringe on user name space.
7702 This macro is obsolescent, as current C compilers support prototypes.
7703 New programs need not use this macro.
7707 @subsection C++ Compiler Characteristics
7710 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7716 Determine a C++ compiler to use.
7718 If either the environment variable @code{CXX} or the environment
7719 variable @code{CCC} is set, its value will be taken as the name of a
7720 C++ compiler. If both are set, @code{CXX} is preferred. If neither
7721 are set, search for a C++ compiler under a series of likely names,
7722 trying @code{g++} and @code{c++} first. Regardless, the output
7723 variable @code{CXX} is set to the chosen compiler.
7725 If the optional first argument to the macro is used, it must be a
7726 whitespace-separated list of potential names for a C++ compiler,
7727 which overrides the built-in list.
7729 If no C++ compiler can be found, as a last resort @code{CXX} is set to
7730 @code{g++} (and subsequent tests will probably fail).
7732 If the selected C++ compiler is found to be GNU C++ (regardless of
7733 its name), the shell variable @code{GXX} will be set to @samp{yes}.
7734 If the shell variable @code{CXXFLAGS} was not already set, it is set
7735 to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on systems
7736 where G++ does not accept @option{-g}), or @option{-g} for other
7737 compilers. @code{CXXFLAGS} is then made an output variable.
7738 You can override the default for @code{CXXFLAGS} by inserting a shell
7739 default assignment between @code{AC_INIT} and @code{AC_PROG_CXX}:
7742 : $@{CXXFLAGS="@var{options}"@}
7745 where @var{options} are the appropriate set of options to use by
7746 default. (It is important to use this construct rather than a normal
7747 assignment, so that @code{CXXFLAGS} can still be overridden by the
7748 person building the package. @xref{Preset Output Variables}.)
7751 @defmac AC_PROG_CXXCPP
7752 @acindex{PROG_CXXCPP}
7755 Set output variable @code{CXXCPP} to a command that runs the C++
7756 preprocessor. If @samp{$CXX -E} doesn't work, tries @code{cpp} and
7757 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7758 may or may not set C++-specific predefined macros (such as @code{__cplusplus}).
7760 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7761 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7763 Some preprocessors don't indicate missing include files by the error
7764 status. For such preprocessors an internal variable is set that causes
7765 other macros to check the standard error from the preprocessor and
7766 consider the test failed if any warnings have been reported. However,
7767 it is not known whether such broken preprocessors exist for C++.
7770 @defmac AC_PROG_CXX_C_O
7771 @acindex{PROG_CXX_C_O}
7772 @cvindex CXX_NO_MINUS_C_MINUS_O
7773 Test whether the C++ compiler accepts the options @option{-c} and
7774 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7779 @node Objective C Compiler
7780 @subsection Objective C Compiler Characteristics
7783 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7789 Determine an Objective C compiler to use. If @code{OBJC} is not already
7790 set in the environment, check for Objective C compilers. Set output
7791 variable @code{OBJC} to the name of the compiler found.
7793 This macro may, however, be invoked with an optional first argument
7794 which, if specified, must be a blank-separated list of Objective C compilers to
7795 search for. This just gives the user an opportunity to specify an
7796 alternative search list for the Objective C compiler. For example, if you
7797 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7801 AC_PROG_OBJC([gcc objcc objc])
7804 If using a compiler that supports GNU Objective C, set shell variable
7805 @code{GOBJC} to @samp{yes}. If output variable @code{OBJCFLAGS} was not
7806 already set, set it to @option{-g -O2} for a GNU Objective C
7807 compiler (@option{-O2} on systems where the compiler does not accept
7808 @option{-g}), or @option{-g} for other compilers.
7811 @defmac AC_PROG_OBJCPP
7812 @acindex{PROG_OBJCPP}
7815 Set output variable @code{OBJCPP} to a command that runs the Objective C
7816 preprocessor. If @samp{$OBJC -E} doesn't work, tries @code{cpp} and
7817 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7818 may or may not set Objective-C-specific predefined macros (such as
7823 @node Objective C++ Compiler
7824 @subsection Objective C++ Compiler Characteristics
7827 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7828 @acindex{PROG_OBJCXX}
7830 @evindex OBJCXXFLAGS
7832 @ovindex OBJCXXFLAGS
7833 Determine an Objective C++ compiler to use. If @code{OBJCXX} is not already
7834 set in the environment, check for Objective C++ compilers. Set output
7835 variable @code{OBJCXX} to the name of the compiler found.
7837 This macro may, however, be invoked with an optional first argument
7838 which, if specified, must be a blank-separated list of Objective C++ compilers
7839 to search for. This just gives the user an opportunity to specify an
7840 alternative search list for the Objective C++ compiler. For example, if you
7841 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7845 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7848 If using a compiler that supports GNU Objective C++, set shell variable
7849 @code{GOBJCXX} to @samp{yes}. If output variable @code{OBJCXXFLAGS} was not
7850 already set, set it to @option{-g -O2} for a GNU Objective C++
7851 compiler (@option{-O2} on systems where the compiler does not accept
7852 @option{-g}), or @option{-g} for other compilers.
7855 @defmac AC_PROG_OBJCXXCPP
7856 @acindex{PROG_OBJCXXCPP}
7859 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7860 preprocessor. If @samp{$OBJCXX -E} doesn't work, tries @code{cpp} and
7861 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7862 may or may not set Objective-C++-specific predefined macros (such as
7863 @code{__cplusplus} and @code{__OBJC__}).
7867 @node Erlang Compiler and Interpreter
7868 @subsection Erlang Compiler and Interpreter Characteristics
7871 Autoconf defines the following macros for determining paths to the essential
7872 Erlang/OTP programs:
7874 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7875 @acindex{ERLANG_PATH_ERLC}
7880 Determine an Erlang compiler to use. If @code{ERLC} is not already set in the
7881 environment, check for @command{erlc}. Set output variable @code{ERLC} to the
7882 complete path of the compiler command found. In addition, if @code{ERLCFLAGS}
7883 is not set in the environment, set it to an empty value.
7885 The two optional arguments have the same meaning as the two last arguments of
7886 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program. For
7887 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7891 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7895 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7896 @acindex{ERLANG_NEED_ERLC}
7897 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7898 error message and exits the @command{configure} script if the @command{erlc}
7899 program is not found.
7902 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7903 @acindex{ERLANG_PATH_ERL}
7906 Determine an Erlang interpreter to use. If @code{ERL} is not already
7908 environment, check for @command{erl}. Set output variable @code{ERL} to the
7909 complete path of the interpreter command found.
7911 The two optional arguments have the same meaning as the two last arguments of
7912 macro @code{AC_PATH_PROG} for looking for the @command{erl} program. For
7913 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7917 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7921 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7922 @acindex{ERLANG_NEED_ERL}
7923 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7924 error message and exits the @command{configure} script if the @command{erl}
7925 program is not found.
7929 @node Fortran Compiler
7930 @subsection Fortran Compiler Characteristics
7934 The Autoconf Fortran support is divided into two categories: legacy
7935 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7936 The former are intended for traditional Fortran 77 code, and have output
7937 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}. The latter
7938 are for newer programs that can (or must) compile under the newer
7939 Fortran standards, and have output variables like @code{FC},
7940 @code{FCFLAGS}, and @code{FCLIBS}.
7942 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7943 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7944 @code{FC} and @code{F77} macros behave almost identically, and so they
7945 are documented together in this section.
7948 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7954 @caindex f77_compiler_gnu
7956 Determine a Fortran 77 compiler to use. If @code{F77} is not already
7957 set in the environment, then check for @code{g77} and @code{f77}, and
7958 then some other names. Set the output variable @code{F77} to the name
7959 of the compiler found.
7961 This macro may, however, be invoked with an optional first argument
7962 which, if specified, must be a blank-separated list of Fortran 77
7963 compilers to search for. This just gives the user an opportunity to
7964 specify an alternative search list for the Fortran 77 compiler. For
7965 example, if you didn't like the default order, then you could invoke
7966 @code{AC_PROG_F77} like this:
7969 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7972 If using a compiler that supports GNU Fortran 77,
7973 set the shell variable @code{G77} to @samp{yes}.
7974 If the output variable @code{FFLAGS} was not already set in the
7975 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
7976 where the GNU Fortran 77 compiler does not accept @option{-g}), or
7977 @option{-g} for other compilers.
7979 The result of the GNU test is cached in the
7980 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7981 @code{ac_cv_prog_f77_g} variable.
7984 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7990 @caindex fc_compiler_gnu
7992 Determine a Fortran compiler to use. If @code{FC} is not already set in
7993 the environment, then @code{dialect} is a hint to indicate what Fortran
7994 dialect to search for; the default is to search for the newest available
7995 dialect. Set the output variable @code{FC} to the name of the compiler
7998 By default, newer dialects are preferred over older dialects, but if
7999 @code{dialect} is specified then older dialects are preferred starting
8000 with the specified dialect. @code{dialect} can currently be one of
8001 Fortran 77, Fortran 90, or Fortran 95. However, this is only a hint of
8002 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
8003 and no attempt is made to guarantee that a particular language standard
8004 is actually supported. Thus, it is preferable that you avoid the
8005 @code{dialect} option, and use AC_PROG_FC only for code compatible with
8006 the latest Fortran standard.
8008 This macro may, alternatively, be invoked with an optional first argument
8009 which, if specified, must be a blank-separated list of Fortran
8010 compilers to search for, just as in @code{AC_PROG_F77}.
8012 If using a compiler that supports GNU Fortran,
8013 set the shell variable @code{GFC} to @samp{yes}.
8014 If the output variable @code{FCFLAGS} was not already set in the
8015 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
8016 @option{-O2} where the compiler does not accept @option{-g}), or
8017 @option{-g} for other compilers.
8019 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
8020 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
8024 @defmac AC_PROG_F77_C_O
8025 @defmacx AC_PROG_FC_C_O
8026 @acindex{PROG_F77_C_O}
8027 @acindex{PROG_FC_C_O}
8028 @cvindex F77_NO_MINUS_C_MINUS_O
8029 @cvindex FC_NO_MINUS_C_MINUS_O
8030 @caindex prog_f77_c_o
8031 @caindex prog_fc_c_o
8032 Test whether the Fortran compiler accepts the options @option{-c} and
8033 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
8034 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
8036 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
8037 @code{ac_cv_prog_fc_c_o} variable, respectively.
8040 The following macros check for Fortran compiler characteristics.
8041 To check for characteristics not listed here, use
8042 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
8043 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
8044 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
8045 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
8048 @defmac AC_F77_LIBRARY_LDFLAGS
8049 @defmacx AC_FC_LIBRARY_LDFLAGS
8050 @acindex{F77_LIBRARY_LDFLAGS}
8052 @acindex{FC_LIBRARY_LDFLAGS}
8058 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
8059 @dfn{Fortran intrinsic and runtime libraries} that are required to
8060 successfully link a Fortran program or shared library. The output
8061 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
8062 should be included after @code{LIBS} when linking).
8064 This macro is intended to be used in those situations when it is
8065 necessary to mix, e.g., C++ and Fortran source code in a single
8066 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
8067 automake, GNU Automake}).
8069 For example, if object files from a C++ and Fortran compiler must be
8070 linked together, then the C++ compiler/linker must be used for linking
8071 (since special C++-ish things need to happen at link time like calling
8072 global constructors, instantiating templates, enabling exception
8075 However, the Fortran intrinsic and runtime libraries must be linked in
8076 as well, but the C++ compiler/linker doesn't know by default how to add
8077 these Fortran 77 libraries. Hence, this macro was created to determine
8078 these Fortran libraries.
8080 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8081 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8082 link C/C++ with Fortran; see below. Further, it is highly recommended
8083 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8084 because the complex defines that the function wrapper macros create
8085 may not work with C/C++ compiler drivers.
8087 These macros internally compute the flag needed to verbose linking
8088 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8089 variables, respectively. The computed linker flags are cached in
8090 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8093 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8094 @dvar{action-if-not-found, AC_MSG_FAILURE})
8095 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8096 @dvar{action-if-not-found, AC_MSG_FAILURE})
8097 @acindex{F77_DUMMY_MAIN}
8098 @cvindex F77_DUMMY_MAIN
8099 @acindex{FC_DUMMY_MAIN}
8100 @cvindex FC_DUMMY_MAIN
8101 @caindex f77_dummy_main
8102 @caindex fc_dummy_main
8103 With many compilers, the Fortran libraries detected by
8104 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8105 their own @code{main} entry function that initializes things like
8106 Fortran I/O, and which then calls a user-provided entry function named
8107 (say) @code{MAIN__} to run the user's program. The
8108 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8109 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8112 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8113 one prefers to provide one's own @code{main} and skip the Fortran
8114 library initializations. In this case, however, one may still need to
8115 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8116 on some systems. @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8117 detects whether any such routine is @emph{required} for linking, and
8118 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8119 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8120 was found, and @code{none} when no such dummy main is needed.
8122 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8123 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8124 @emph{if} it is required. @var{action-if-not-found} defaults to
8125 exiting with an error.
8127 In order to link with Fortran routines, the user's C/C++ program should
8128 then include the following code to define the dummy main if it is
8132 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8133 #ifdef F77_DUMMY_MAIN
8137 int F77_DUMMY_MAIN (void) @{ return 1; @}
8141 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8143 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8144 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8145 explicitly unless one wants to change the default actions.
8147 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8148 @code{ac_cv_fc_dummy_main} variable, respectively.
8159 As discussed above, many Fortran libraries allow you to provide an entry
8160 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8161 is then called by a @code{main} function in the Fortran libraries that
8162 initializes things like Fortran I/O@. The
8163 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8164 @emph{possible} to utilize such an alternate main function, and defines
8165 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function. (If no
8166 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8167 simply defined to @code{main}.)
8169 Thus, when calling Fortran routines from C that perform things like I/O,
8170 one should use this macro and declare the "main" function like so:
8173 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8177 int F77_MAIN (int argc, char *argv[]);
8180 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8182 The result of this macro is cached in the @code{ac_cv_f77_main} or
8183 @code{ac_cv_fc_main} variable, respectively.
8186 @defmac AC_F77_WRAPPERS
8187 @defmacx AC_FC_WRAPPERS
8188 @acindex{F77_WRAPPERS}
8191 @acindex{FC_WRAPPERS}
8194 @caindex f77_mangling
8195 @caindex fc_mangling
8196 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8197 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8198 mangle the names of C/C++ identifiers, and identifiers with underscores,
8199 respectively, so that they match the name-mangling scheme used by the
8202 Fortran is case-insensitive, and in order to achieve this the Fortran
8203 compiler converts all identifiers into a canonical case and format. To
8204 call a Fortran subroutine from C or to write a C function that is
8205 callable from Fortran, the C program must explicitly use identifiers in
8206 the format expected by the Fortran compiler. In order to do this, one
8207 simply wraps all C identifiers in one of the macros provided by
8208 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}. For example, suppose
8209 you have the following Fortran 77 subroutine:
8212 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8213 subroutine foobar (x, y)
8214 double precision x, y
8220 You would then declare its prototype in C or C++ as:
8223 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8224 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8226 extern "C" /* prevent C++ name mangling */
8228 void FOOBAR_F77 (double *x, double *y);
8231 Note that we pass both the lowercase and uppercase versions of the
8232 function name to @code{F77_FUNC} so that it can select the right one.
8233 Note also that all parameters to Fortran 77 routines are passed as
8234 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8237 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8239 Although Autoconf tries to be intelligent about detecting the
8240 name-mangling scheme of the Fortran compiler, there may be Fortran
8241 compilers that it doesn't support yet. In this case, the above code
8242 generates a compile-time error, but some other behavior
8243 (e.g., disabling Fortran-related features) can be induced by checking
8244 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8246 Now, to call that routine from a C program, we would do something like:
8249 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8251 double x = 2.7183, y;
8252 FOOBAR_F77 (&x, &y);
8256 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8257 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8258 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments). This is
8259 because some Fortran compilers mangle names differently if they contain
8262 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8263 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8264 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8267 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8268 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8271 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8272 hold the mangled version @var{name} according to the rules of the
8273 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8274 @code{AC_FC_WRAPPERS}). @var{shellvar} is optional; if it is not
8275 supplied, the shell variable is simply @var{name}. The purpose of
8276 this macro is to give the caller a way to access the name-mangling
8277 information other than through the C preprocessor as above, for example,
8278 to call Fortran routines from some language other than C/C++.
8281 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8282 @dvar{action-if-failure, AC_MSG_FAILURE})
8283 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8284 @dvar{action-if-failure, AC_MSG_FAILURE})
8286 @acindex{FC_PP_SRCEXT}
8287 @caindex fc_srcext_@var{ext}
8288 @caindex fc_pp_srcext_@var{ext}
8289 By default, the @code{FC} macros perform their tests using a @file{.f}
8290 extension for source-code files. Some compilers, however, only enable
8291 newer language features for appropriately named files, e.g., Fortran 90
8292 features only for @file{.f90} files, or preprocessing only with
8293 @file{.F} files or maybe other upper-case extensions. On the other
8294 hand, some other compilers expect all source files to end in @file{.f}
8295 and require special flags to support other file name extensions. The
8296 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8299 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8300 accept files ending with the extension @file{.@var{ext}} (i.e.,
8301 @var{ext} does @emph{not} contain the dot). If any special compiler
8302 flags are needed for this, it stores them in the output variable
8303 @code{FCFLAGS_@var{ext}}. This extension and these flags are then used
8304 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8305 @code{AC_FC_PP_SRCEXT} is called another time).
8307 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8308 @file{.f90} extension in future tests, and it would set the
8309 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8310 to compile such files.
8312 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8313 compiler to preprocess and compile files with the extension
8314 @file{.@var{ext}}. When both @command{fpp} and @command{cpp} style
8315 preprocessing are provided, the former is preferred, as the latter may
8316 treat continuation lines, @code{//} tokens, and white space differently
8317 from what some Fortran dialects expect. Conversely, if you do not want
8318 files to be preprocessed, use only lower-case characters in the file
8319 name extension. Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8320 are stored in the @code{FCFLAGS_@var{ext}} variable.
8322 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8323 into @code{FCFLAGS}, for two reasons based on the limitations of some
8324 compilers. First, only one @code{FCFLAGS_@var{ext}} can be used at a
8325 time, so files with different extensions must be compiled separately.
8326 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8327 the source-code file name when compiling. So, continuing the example
8328 above, you might compile a @file{foo.f90} file in your makefile with the
8333 $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8336 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8337 files with the @var{ext} extension, it calls @var{action-if-success}
8338 (defaults to nothing). If it fails, and cannot find a way to make the
8339 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8340 (defaults to exiting with an error message).
8342 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8343 results in @code{ac_cv_fc_srcext_@var{ext}} and
8344 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8347 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8348 @dvar{action-if-failure, AC_MSG_FAILURE})
8349 @acindex{FC_PP_DEFINE}
8350 @caindex fc_pp_define
8352 Find a flag to specify defines for preprocessed Fortran. Not all
8353 Fortran compilers use @option{-D}. Substitute @code{FC_DEFINE} with
8354 the result and call @var{action-if-success} (defaults to nothing) if
8355 successful, and @var{action-if-failure} (defaults to failing with an
8356 error message) if not.
8358 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8359 preprocess a @file{conftest.F} file, but restores a previously used
8360 Fortran source file extension afterwards again.
8362 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8366 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8367 @dvar{action-if-failure, AC_MSG_FAILURE})
8368 @acindex{FC_FREEFORM}
8369 @caindex fc_freeform
8371 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8372 source code (as opposed to the older fixed-format style from Fortran
8373 77). If necessary, it may add some additional flags to @code{FCFLAGS}.
8375 This macro is most important if you are using the default @file{.f}
8376 extension, since many compilers interpret this extension as indicating
8377 fixed-format source unless an additional flag is supplied. If you
8378 specify a different extension with @code{AC_FC_SRCEXT}, such as
8379 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8380 modifying @code{FCFLAGS}. For extensions which the compiler does not
8381 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8382 the compiler assume Fortran 77 by default, however.
8384 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8385 calls @var{action-if-success} (defaults to nothing). If it fails, it
8386 calls @var{action-if-failure} (defaults to exiting with an error
8389 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8390 the @code{ac_cv_fc_freeform} variable.
8393 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8394 @dvar{action-if-failure, AC_MSG_FAILURE})
8395 @acindex{FC_FIXEDFORM}
8396 @caindex fc_fixedform
8398 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8399 fixed-format source code (as opposed to free-format style). If
8400 necessary, it may add some additional flags to @code{FCFLAGS}.
8402 This macro is needed for some compilers alias names like @command{xlf95}
8403 which assume free-form source code by default, and in case you want to
8404 use fixed-form source with an extension like @file{.f90} which many
8405 compilers interpret as free-form by default. If you specify a different
8406 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8407 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8410 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8411 calls @var{action-if-success} (defaults to nothing). If it fails, it
8412 calls @var{action-if-failure} (defaults to exiting with an error
8415 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8416 the @code{ac_cv_fc_fixedform} variable.
8419 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8420 @dvar{action-if-failure, AC_MSG_FAILURE})
8421 @acindex{FC_LINE_LENGTH}
8422 @caindex fc_line_length
8424 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8425 code lines. The @var{length} argument may be given as 80, 132, or
8426 unlimited, and defaults to 132. Note that line lengths above 250
8427 columns are not portable, and some compilers do not accept more than 132
8428 columns at least for fixed format source. If necessary, it may add some
8429 additional flags to @code{FCFLAGS}.
8431 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8432 calls @var{action-if-success} (defaults to nothing). If it fails, it
8433 calls @var{action-if-failure} (defaults to exiting with an error
8436 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8437 the @code{ac_cv_fc_line_length} variable.
8440 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8441 @dvar{action-if-failure, AC_MSG_FAILURE})
8442 @acindex{FC_CHECK_BOUNDS}
8443 @caindex fc_check_bounds
8445 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8446 in the Fortran compiler. If successful, the @var{action-if-success}
8447 is called and any needed flags are added to @code{FCFLAGS}. Otherwise,
8448 @var{action-if-failure} is called, which defaults to failing with an error
8449 message. The macro currently requires Fortran 90 or a newer dialect.
8451 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8455 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8456 @dvar{action-if-failure, AC_MSG_FAILURE})
8457 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8458 @dvar{action-if-failure, AC_MSG_FAILURE})
8459 @acindex{F77_IMPLICIT_NONE}
8460 @acindex{FC_IMPLICIT_NONE}
8461 @caindex f77_implicit_none
8462 @caindex fc_implicit_none
8464 Try to disallow implicit declarations in the Fortran compiler. If
8465 successful, @var{action-if-success} is called and any needed flags
8466 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively. Otherwise,
8467 @var{action-if-failure} is called, which defaults to failing with an error
8470 The result of these macros are cached in the
8471 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8472 variables, respectively.
8475 @defmac AC_FC_MODULE_EXTENSION
8476 @acindex{FC_MODULE_EXTENSION}
8477 @caindex fc_module_ext
8480 Find the Fortran 90 module file name extension. Most Fortran 90
8481 compilers store module information in files separate from the object
8482 files. The module files are usually named after the name of the module
8483 rather than the source file name, with characters possibly turned to
8484 upper case, plus an extension, often @file{.mod}.
8486 Not all compilers use module files at all, or by default. The Cray
8487 Fortran compiler requires @option{-e m} in order to store and search
8488 module information in @file{.mod} files rather than in object files.
8489 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8490 indicate how module information is stored.
8492 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8493 without the leading dot, and stores that in the @code{FC_MODEXT}
8494 variable. If the compiler does not produce module files, or the
8495 extension cannot be determined, @code{FC_MODEXT} is empty. Typically,
8496 the result of this macro may be used in cleanup @command{make} rules as
8501 -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8504 The extension, or @samp{unknown}, is cached in the
8505 @code{ac_cv_fc_module_ext} variable.
8508 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8509 @dvar{action-if-failure, AC_MSG_FAILURE})
8510 @acindex{FC_MODULE_FLAG}
8511 @caindex fc_module_flag
8515 Find the compiler flag to include Fortran 90 module information from
8516 another directory, and store that in the @code{FC_MODINC} variable.
8517 Call @var{action-if-success} (defaults to nothing) if successful, and
8518 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8519 to exiting with an error message) if not.
8521 Most Fortran 90 compilers provide a way to specify module directories.
8522 Some have separate flags for the directory to write module files to,
8523 and directories to search them in, whereas others only allow writing to
8524 the current directory or to the first directory specified in the include
8525 path. Further, with some compilers, the module search path and the
8526 preprocessor search path can only be modified with the same flag. Thus,
8527 for portability, write module files to the current directory only and
8528 list that as first directory in the search path.
8530 There may be no whitespace between @code{FC_MODINC} and the following
8531 directory name, but @code{FC_MODINC} may contain trailing white space.
8532 For example, if you use Automake and would like to search @file{../lib}
8533 for module files, you can use the following:
8536 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8539 Inside @command{configure} tests, you can use:
8542 if test -n "$FC_MODINC"; then
8543 FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8547 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8548 The substituted value of @code{FC_MODINC} may refer to the
8549 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8550 the significant trailing whitespace in a @file{Makefile}.
8553 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8554 @dvar{action-if-failure, AC_MSG_FAILURE})
8555 @acindex{FC_MODULE_OUTPUT_FLAG}
8556 @caindex fc_module_output_flag
8559 Find the compiler flag to write Fortran 90 module information to
8560 another directory, and store that in the @code{FC_MODOUT} variable.
8561 Call @var{action-if-success} (defaults to nothing) if successful, and
8562 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8563 to exiting with an error message) if not.
8565 Not all Fortran 90 compilers write module files, and of those that do,
8566 not all allow writing to a directory other than the current one, nor
8567 do all have separate flags for writing and reading; see the description
8568 of @code{AC_FC_MODULE_FLAG} above. If you need to be able to write to
8569 another directory, for maximum portability use @code{FC_MODOUT} before
8570 any @code{FC_MODINC} and include both the current directory and the one
8571 you write to in the search path:
8574 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8577 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8578 The substituted value of @code{FC_MODOUT} may refer to the
8579 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8580 the significant trailing whitespace in a @file{Makefile}.
8583 @defmac AC_F77_CRAY_POINTERS (@ovar{action-if-success}, @
8584 @dvar{action-if-failure, AC_MSG_FAILURE})
8585 @defmacx AC_FC_CRAY_POINTERS (@ovar{action-if-success}, @
8586 @dvar{action-if-failure, AC_MSG_FAILURE})
8587 @acindex{F77_CRAY_POINTERS}
8588 @acindex{FC_CRAY_POINTERS}
8589 @caindex fc_cray_pointer
8591 Try to ensure that the Fortran compiler (@code{$F77} or @code{$FC})
8592 accepts Cray pointers. If successful, the @var{action-if-success} is
8593 called and any needed flags are added to @code{FFLAGS} or
8594 @code{FCFLAGS}. Otherwise, @var{action-if-failure} is called, which
8595 defaults to failing with an error message.
8597 Cray pointers are a non-standard extension supported by many Fortran
8598 compilers which allow an integer to be declared as C-like pointer to
8601 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8602 the @code{ac_cv_f77_cray_ptr} or @code{ac_cv_fc_cray_ptr} variable.
8607 @subsection Go Compiler Characteristics
8610 Autoconf provides basic support for the Go programming language when
8611 using the @code{gccgo} compiler (there is currently no support for the
8612 @code{6g} and @code{8g} compilers).
8614 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8615 Find the Go compiler to use. Check whether the environment variable
8616 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8619 Otherwise, if the macro is invoked without an argument, then search for
8620 a Go compiler named @code{gccgo}. If it is not found, then as a last
8621 resort set @code{GOC} to @code{gccgo}.
8623 This macro may be invoked with an optional first argument which, if
8624 specified, must be a blank-separated list of Go compilers to search for.
8626 If output variable @code{GOFLAGS} was not already set, set it to
8627 @option{-g -O2}. If your package does not like this default,
8628 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8632 @node System Services
8633 @section System Services
8635 The following macros check for operating system services or capabilities.
8641 @cindex X Window System
8642 Try to locate the X Window System include files and libraries. If the
8643 user gave the command line options @option{--x-includes=@var{dir}} and
8644 @option{--x-libraries=@var{dir}}, use those directories.
8646 If either or both were not given, get the missing values by running
8647 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8648 environment variable) on a trivial @file{Imakefile} and examining the
8649 makefile that it produces. Setting @code{XMKMF} to @samp{false}
8650 disables this method.
8652 If this method fails to find the X Window System, @command{configure}
8653 looks for the files in several directories where they often reside.
8654 If either method is successful, set the shell variables
8655 @code{x_includes} and @code{x_libraries} to their locations, unless they
8656 are in directories the compiler searches by default.
8658 If both methods fail, or the user gave the command line option
8659 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8660 otherwise set it to the empty string.
8663 @anchor{AC_PATH_XTRA}
8664 @defmac AC_PATH_XTRA
8668 @ovindex X_EXTRA_LIBS
8670 @cvindex X_DISPLAY_MISSING
8671 An enhanced version of @code{AC_PATH_X}. It adds the C compiler flags
8672 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8673 to @code{X_LIBS}. Define @code{X_DISPLAY_MISSING} if X is not
8676 This macro also checks for special libraries that some systems need in
8677 order to compile X programs. It adds any that the system needs to
8678 output variable @code{X_EXTRA_LIBS}. And it checks for special X11R6
8679 libraries that need to be linked with before @option{-lX11}, and adds
8680 any found to the output variable @code{X_PRE_LIBS}.
8682 @c This is an incomplete kludge. Make a real way to do it.
8683 @c If you need to check for other X functions or libraries yourself, then
8684 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8685 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8688 @anchor{AC_SYS_INTERPRETER}
8689 @defmac AC_SYS_INTERPRETER
8690 @acindex{SYS_INTERPRETER}
8691 Check whether the system supports starting scripts with a line of the
8692 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8693 After running this macro, shell code in @file{configure.ac} can check
8694 the shell variable @code{interpval}; it is set to @samp{yes}
8695 if the system supports @samp{#!}, @samp{no} if not.
8698 @anchor{AC_SYS_LARGEFILE}
8699 @defmac AC_SYS_LARGEFILE
8700 @acindex{SYS_LARGEFILE}
8701 @cvindex _FILE_OFFSET_BITS
8704 @cindex Large file support
8706 If the default @code{off_t} type is a 32-bit integer,
8707 and therefore cannot be used with files 2 GiB or larger,
8708 make a wider @code{off_t} available if the system supports it.
8709 Similarly, widen other types related to sizes of files and file systems
8710 if possible. These types may include @code{blkcnt_t}, @code{dev_t},
8711 @code{ino_t}, @code{fsblkcnt_t}, @code{fsfilcnt_t}, and @code{rlim_t}.
8713 Also, arrange for a @command{configure} option @code{--enable-year2038}
8714 to request widening the type @code{time_t} as needed to represent file
8715 wand other timestamps after mid-January 2038. This widening is possible
8716 only on 32-bit GNU/Linux x86 and ARM systems with glibc 2.34 or later.
8717 If year-2038 support is requested but @command{configure} fails to find a way
8718 to widen @code{time_t} and inspection of the system suggests that
8719 this feature is available somehow, @command{configure} will error out.
8720 If you want the default to be @code{--enable-year2038}, you can use
8721 @code{AC_SYS_YEAR2038} or @code{AC_SYS_YEAR2038_RECOMMENDED}
8722 instead of @code{AC_SYS_LARGEFILE}.
8723 In other words, older packages that have long used @code{AC_SYS_LARGEFILE}
8724 can have year-2038 support on 32-bit GNU/Linux x86 and ARM systems either by
8725 regenerating @file{configure} with current Autoconf and configuring with
8726 @option{--enable-year2038}, or by using @code{AC_SYS_YEAR2038} or
8727 @code{AC_SYS_YEAR2038_RECOMMENDED} and configuring without
8728 @option{--disable-year2038}.
8729 A future version of Autoconf might change the @code{AC_SYS_LARGEFILE}
8730 default to @code{--enable-year2038}; if and when that happens,
8731 @code{AC_SYS_LARGEFILE} and @code{AC_SYS_YEAR2038} will become equivalent.
8732 @xref{AC_SYS_YEAR2038}.
8734 Set the shell variable @code{ac_have_largefile} to @samp{yes} or
8735 @code{no} depending on whether a wide @code{off_t} is available,
8736 regardless of whether arrangements were necessary.
8737 Similarly, set the shell variable @code{ac_have_year2038} to @code{yes}
8738 or @code{no} depending on whether a wide-enough @code{time_t} is available.
8740 Define preprocessor macros if necessary to make types wider;
8741 for example, on GNU/Linux systems the macros @code{_FILE_OFFSET_BITS}
8742 and @code{_TIME_BITS} can be defined. Some of these macros work only if
8743 defined before the first system header is included;
8744 therefore, when using this macro in concert with
8745 @code{AC_CONFIG_HEADERS}, make sure that @file{config.h} is included
8746 before any system headers.
8748 Large-file support can be disabled by configuring with the
8749 @option{--disable-largefile} option, and year-2038 support can
8750 be enabled and disabled via the @option{--enable-year2038} and
8751 @option{--disable-year2038} options. These options have no effect on
8752 systems where types are wide enough by default.
8753 Large-file support is required for year-2038 support: if you configure
8754 with @option{--disable-largefile} on a platform with 32-bit
8755 @code{time_t}, then year-2038 support is not available.
8757 Disabling large-file or year-2038 support can have surprising effects,
8758 such as causing functions like @code{readdir} and @code{stat} to fail
8759 even on a small file because its inode number or timestamp is out of range.
8761 Regardless of whether you use this macro, portable programs should not
8762 assume that any of the types listed above fit into a @code{long int}.
8763 For example, it is not portable to print an arbitrary @code{off_t} or
8764 @code{time_t} value @code{X} with @code{printf ("%ld", (long int) X)}.
8766 The standard C library functions @code{fseek} and @code{ftell}
8767 do not use @code{off_t}. If you need to use either of these functions,
8768 you should use @code{AC_FUNC_FSEEKO} as well as @code{AC_SYS_LARGEFILE},
8769 and then use their POSIX replacements @code{fseeko} and @code{ftello}.
8770 @xref{AC_FUNC_FSEEKO}.
8772 When using @code{AC_SYS_LARGEFILE} in different packages that are linked
8773 together and that have interfaces that depend on the width of @code{off_t},
8774 @code{time_t} or related types, the simplest thing is to configure all
8775 components the same way. For example, if an application uses
8776 @code{AC_SYS_LARGEFILE} and is configured with
8777 @option{--enable-year2038}, libraries it links to with an @code{off_t}-
8778 or @code{time_t}-dependent interface should be configured equivalently.
8779 Alternatively, you can modify libraries to support both 32- and 64-bit
8780 interfaces though this is more work and few libraries other than the C
8781 library itself are modified in this way.
8783 Applications and libraries should be configured compatibly.
8784 If @code{off_t}, @code{time_t} or related types appear in a library's
8785 public interface, enabling or disabling the library's large-file or
8786 year-2038 support may break binary compatibility with applications or
8787 with other libraries. Similarly, if an application links to a such a
8788 library, enabling or disabling the application's large-file support may
8789 break binary compatibility with that library.
8792 @anchor{AC_SYS_LONG_FILE_NAMES}
8793 @defmac AC_SYS_LONG_FILE_NAMES
8794 @acindex{SYS_LONG_FILE_NAMES}
8795 @cvindex HAVE_LONG_FILE_NAMES
8796 If the system supports file names longer than 14 characters, define
8797 @code{HAVE_LONG_FILE_NAMES}.
8800 @defmac AC_SYS_POSIX_TERMIOS
8801 @acindex{SYS_POSIX_TERMIOS}
8802 @cindex POSIX termios headers
8803 @cindex termios POSIX headers
8804 @caindex sys_posix_termios
8805 Check to see if the POSIX termios headers and functions are available on the
8806 system. If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8807 @samp{yes}. If not, set the variable to @samp{no}.
8810 @anchor{AC_SYS_YEAR2038}
8811 @defmac AC_SYS_YEAR2038
8812 @acindex{SYS_YEAR2038}
8814 This is like @code{AC_SYS_LARGEFILE} except it defaults to enabling
8815 instead of disabling year-2038 support. Year-2038 support for
8816 applications and libraries should be configured compatibly.
8817 @xref{AC_SYS_LARGEFILE}.
8820 @defmac AC_SYS_YEAR2038_RECOMMENDED
8821 @acindex{SYS_YEAR2038_RECOMMENDED}
8822 This macro has the same effect as @code{AC_SYS_YEAR2038},
8823 but also declares that the program being configured
8824 should support timestamps after mid-January 2038.
8825 If a large @code{time_t} is unavailable, @command{configure} will error
8826 out unless the @option{--disable-year2038} option is specified.
8828 Year-2038 support for applications and libraries should be configured
8829 compatibly. @xref{AC_SYS_YEAR2038}.
8832 @node C and POSIX Variants
8833 @section C and POSIX Variants
8835 The following macro makes it possible to use C language and library
8836 extensions defined by the C standards committee, features of POSIX that
8837 are extensions to C, and platform extensions not defined by POSIX.
8839 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8840 @defmac AC_USE_SYSTEM_EXTENSIONS
8841 @acindex{USE_SYSTEM_EXTENSIONS}
8842 If possible, enable extensions to C or POSIX on hosts that normally
8843 disable the extensions, typically due to standards-conformance namespace
8844 issues. This should be called before any macros that run the C
8845 compiler. Also, when using this macro in concert with
8846 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8847 before any system header.
8849 Define the following preprocessor macros unconditionally:
8853 @cvindex _ALL_SOURCE
8854 Enable extensions on AIX and z/OS.
8855 @item _DARWIN_C_SOURCE
8856 @cvindex _DARWIN_C_SOURCE
8857 Enable extensions on macOS.
8859 @cvindex _GNU_SOURCE
8860 Enable extensions on GNU systems.
8861 @item _NETBSD_SOURCE
8862 @cvindex _NETBSD_SOURCE
8863 Enable general extensions on NetBSD.
8864 Enable NetBSD compatibility extensions on Minix.
8865 @item _OPENBSD_SOURCE
8866 @cvindex _OPENBSD_SOURCE
8867 Enable OpenBSD compatibility extensions on NetBSD.
8868 Oddly enough, this does nothing on OpenBSD.
8869 @item _POSIX_PTHREAD_SEMANTICS
8870 @cvindex _POSIX_PTHREAD_SEMANTICS
8871 Enable POSIX-compatible threading on Solaris.
8872 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8873 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8874 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8875 @item __STDC_WANT_IEC_60559_BFP_EXT__
8876 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8877 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8878 @item __STDC_WANT_IEC_60559_DFP_EXT__
8879 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8880 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8881 @item __STDC_WANT_IEC_60559_EXT__
8882 @cvindex __STDC_WANT_IEC_60559_EXT__
8883 Enable extensions specified by C23 Annex F.
8884 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8885 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8886 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8887 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8888 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8889 Enable extensions specified by C23 Annex H and by ISO/IEC TS 18661-3:2015.
8890 @item __STDC_WANT_LIB_EXT2__
8891 @cvindex __STDC_WANT_LIB_EXT2__
8892 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8893 @item __STDC_WANT_MATH_SPEC_FUNCS__
8894 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8895 Enable extensions specified by ISO/IEC 24747:2009.
8896 @item _TANDEM_SOURCE
8897 @cvindex _TANDEM_SOURCE
8898 Enable extensions on HP NonStop systems.
8901 The following preprocessor macros are defined only when necessary;
8902 they enable access to extensions on some operating systems but
8903 @emph{disable} extensions on other operating systems.
8906 @item __EXTENSIONS__
8907 @cvindex __EXTENSIONS__
8908 Enable general extensions on Solaris. This macro is defined only if
8909 the headers included by @code{AC_INCLUDES_DEFAULT}
8910 (@pxref{Default Includes}) work correctly with it defined.
8913 @itemx _POSIX_SOURCE
8914 @itemx _POSIX_1_SOURCE
8916 @cvindex _POSIX_SOURCE
8917 @cvindex _POSIX_1_SOURCE
8918 Defined only on MINIX. @code{_POSIX_SOURCE} and @code{_POSIX_1_SOURCE}
8919 are needed to enable a number of POSIX features on this OS.
8920 @code{_MINIX} does not affect the system headers' behavior;
8921 future versions of Autoconf may stop defining it.
8922 Programs that need to recognize Minix should use @code{AC_CANONICAL_HOST}.
8925 @cvindex _XOPEN_SOURCE
8926 Defined (with value 500) only if needed to make @file{wchar.h} declare
8927 @code{mbstate_t}. This is known to be necessary on some versions of HP-UX.
8930 @cvindex __STDC_WANT_DEC_FP__
8931 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
8932 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
8934 @cvindex __STDC_WANT_LIB_EXT1__
8935 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
8936 as the C standard's Annex K is problematic. See: O'Donell C, Sebor M.
8937 @uref{https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8938 Experience With Annex K---Bounds Checking Interfaces}.
8940 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
8945 @node Erlang Libraries
8946 @section Erlang Libraries
8947 @cindex Erlang, Library, checking
8949 The following macros check for an installation of Erlang/OTP, and for the
8950 presence of certain Erlang libraries. All those macros require the
8951 configuration of an Erlang interpreter and an Erlang compiler
8952 (@pxref{Erlang Compiler and Interpreter}).
8954 @defmac AC_ERLANG_SUBST_ERTS_VER
8955 @acindex{ERLANG_SUBST_ERTS_VER}
8956 @ovindex ERLANG_ERTS_VER
8957 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8958 Erlang runtime system (as returned by Erlang's
8959 @code{erlang:system_info(version)} function). The result of this test
8960 is cached if caching is enabled when running @command{configure}. The
8961 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8962 for features of specific ERTS versions, but to be used for substituting
8963 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8964 files), as shown below.
8967 @defmac AC_ERLANG_SUBST_ROOT_DIR
8968 @acindex{ERLANG_SUBST_ROOT_DIR}
8969 @ovindex ERLANG_ROOT_DIR
8970 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8971 directory in which Erlang/OTP is installed (as returned by Erlang's
8972 @code{code:root_dir/0} function). The result of this test is cached if
8973 caching is enabled when running @command{configure}.
8976 @defmac AC_ERLANG_SUBST_LIB_DIR
8977 @acindex{ERLANG_SUBST_LIB_DIR}
8978 @ovindex ERLANG_LIB_DIR
8979 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8980 directory of Erlang/OTP (as returned by Erlang's
8981 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8982 Erlang/OTP library. The result of this test is cached if caching is enabled
8983 when running @command{configure}.
8986 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8987 @ovar{action-if-not-found})
8988 @acindex{ERLANG_CHECK_LIB}
8989 @ovindex ERLANG_LIB_DIR_@var{library}
8990 @ovindex ERLANG_LIB_VER_@var{library}
8991 Test whether the Erlang/OTP library @var{library} is installed by
8992 calling Erlang's @code{code:lib_dir/1} function. The result of this
8993 test is cached if caching is enabled when running @command{configure}.
8994 @var{action-if-found} is a list of shell commands to run if the library
8995 is installed; @var{action-if-not-found} is a list of shell commands to
8996 run if it is not. Additionally, if the library is installed, the output
8997 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8998 library installation directory, and the output variable
8999 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
9000 part of the subdirectory name, if it is in the standard form
9001 (@code{@var{library}-@var{version}}). If the directory name does not
9002 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
9003 empty string. If the library is not installed,
9004 @samp{ERLANG_LIB_DIR_@var{library}} and
9005 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}. For
9006 example, to check if library @code{stdlib} is installed:
9009 AC_ERLANG_CHECK_LIB([stdlib],
9010 [AS_ECHO(["stdlib version \"$ERLANG_LIB_VER_stdlib\""])
9011 AS_ECHO(["is installed in \"$ERLANG_LIB_DIR_stdlib\""])],
9012 [AC_MSG_ERROR([stdlib was not found!])])
9015 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
9016 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
9017 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
9018 testing for features of specific versions of libraries or of the Erlang
9019 runtime system. Those variables are intended to be substituted in
9020 Erlang release resource files (@code{.rel} files). For instance, to
9021 generate a @file{example.rel} file for an application depending on the
9022 @code{stdlib} library, @file{configure.ac} could contain:
9025 AC_ERLANG_SUBST_ERTS_VER
9026 AC_ERLANG_CHECK_LIB([stdlib],
9028 [AC_MSG_ERROR([stdlib was not found!])])
9029 AC_CONFIG_FILES([example.rel])
9033 The @file{example.rel.in} file used to generate @file{example.rel}
9038 @{"@@PACKAGE@@", "@@VERSION@@"@},
9039 @{erts, "@@ERLANG_ERTS_VER@@"@},
9040 [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
9041 @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
9045 In addition to the above macros, which test installed Erlang libraries, the
9046 following macros determine the paths to the directories into which newly built
9047 Erlang libraries are to be installed:
9049 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
9050 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
9051 @ovindex ERLANG_INSTALL_LIB_DIR
9053 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
9054 which every built Erlang library should be installed in a separate
9056 If this variable is not set in the environment when @command{configure} runs,
9057 its default value is @code{$@{libdir@}/erlang/lib}.
9060 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
9061 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
9062 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
9064 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
9065 directory into which the built Erlang library @var{library} version
9066 @var{version} should be installed. If this variable is not set in the
9067 environment when @command{configure} runs, its default value is
9068 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
9069 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
9070 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
9077 @c ========================================================= Writing Tests
9080 @chapter Writing Tests
9082 If the existing feature tests don't do something you need, you have to
9083 write new ones. These macros are the building blocks. They provide
9084 ways for other macros to check whether various kinds of features are
9085 available and report the results.
9087 This chapter contains some suggestions and some of the reasons why the
9088 existing tests are written the way they are. You can also learn a lot
9089 about how to write Autoconf tests by looking at the existing ones. If
9090 something goes wrong in one or more of the Autoconf tests, this
9091 information can help you understand the assumptions behind them, which
9092 might help you figure out how to best solve the problem.
9094 These macros check the output of the compiler system of the current
9095 language (@pxref{Language Choice}). They do not cache the results of
9096 their tests for future use (@pxref{Caching Results}), because they don't
9097 know enough about the information they are checking for to generate a
9098 cache variable name. They also do not print any messages, for the same
9099 reason. The checks for particular kinds of features call these macros
9100 and do cache their results and print messages about what they're
9103 When you write a feature test that could be applicable to more than one
9104 software package, the best thing to do is encapsulate it in a new macro.
9105 @xref{Writing Autoconf Macros}, for how to do that.
9108 * Language Choice:: Selecting which language to use for testing
9109 * Writing Test Programs:: Forging source files for compilers
9110 * Running the Preprocessor:: Detecting preprocessor symbols
9111 * Running the Compiler:: Detecting language or header features
9112 * Running the Linker:: Detecting library features
9113 * Runtime:: Testing for runtime features
9114 * Multiple Cases:: Tests for several possible values
9117 @node Language Choice
9118 @section Language Choice
9121 Autoconf-generated @command{configure} scripts check for the C compiler and
9122 its features by default. Packages that use other programming languages
9123 (maybe more than one, e.g., C and C++) need to test features of the
9124 compilers for the respective languages. The following macros determine
9125 which programming language is used in the subsequent tests in
9126 @file{configure.ac}.
9129 @defmac AC_LANG (@var{language})
9131 Do compilation tests using the compiler, preprocessor, and file
9132 extensions for the specified @var{language}.
9134 Supported languages are:
9138 Do compilation tests using @code{CC} and @code{CPP} and use extension
9139 @file{.c} for test programs. Use compilation flags: @code{CPPFLAGS} with
9140 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
9143 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
9144 extension @file{.C} for test programs. Use compilation flags:
9145 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
9146 @code{CXXFLAGS} with @code{CXX}.
9149 Do compilation tests using @code{F77} and use extension @file{.f} for
9150 test programs. Use compilation flags: @code{FFLAGS}.
9153 Do compilation tests using @code{FC} and use extension @file{.f} (or
9154 whatever has been set by @code{AC_FC_SRCEXT}) for test programs. Use
9155 compilation flags: @code{FCFLAGS}.
9161 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
9162 @file{.erl} for test Erlang modules. Use compilation flags: @code{ERLCFLAGS}.
9165 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
9166 extension @file{.m} for test programs. Use compilation flags:
9167 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
9168 @code{OBJCFLAGS} with @code{OBJC}.
9171 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
9172 extension @file{.mm} for test programs. Use compilation flags:
9173 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
9174 @code{OBJCXXFLAGS} with @code{OBJCXX}.
9177 Do compilation tests using @code{GOC} and use extension @file{.go} for
9178 test programs. Use compilation flags @code{GOFLAGS}.
9182 @anchor{AC_LANG_PUSH}
9183 @defmac AC_LANG_PUSH (@var{language})
9185 Remember the current language (as set by @code{AC_LANG}) on a stack, and
9186 then select the @var{language}. Use this macro and @code{AC_LANG_POP}
9187 in macros that need to temporarily switch to a particular language.
9190 @defmac AC_LANG_POP (@ovar{language})
9192 Select the language that is saved on the top of the stack, as set by
9193 @code{AC_LANG_PUSH}, and remove it from the stack.
9195 If given, @var{language} specifies the language we just @emph{quit}. It
9196 is a good idea to specify it when it's known (which should be the
9197 case@dots{}), since Autoconf detects inconsistencies.
9200 AC_LANG_PUSH([Fortran 77])
9201 # Perform some tests on Fortran 77.
9203 AC_LANG_POP([Fortran 77])
9207 @defmac AC_LANG_ASSERT (@var{language})
9208 @acindex{LANG_ASSERT}
9209 Check statically that the current language is @var{language}.
9210 You should use this in your language specific macros
9211 to avoid that they be called with an inappropriate language.
9213 This macro runs only at @command{autoconf} time, and incurs no cost at
9214 @command{configure} time. Sadly enough and because Autoconf is a two
9215 layer language @footnote{Because M4 is not aware of Sh code,
9216 especially conditionals, some optimizations that look nice statically
9217 may produce incorrect results at runtime.}, the macros
9218 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
9219 therefore as much as possible you ought to avoid using them to wrap
9220 your code, rather, require from the user to run the macro with a
9221 correct current language, and check it with @code{AC_LANG_ASSERT}.
9222 And anyway, that may help the user understand she is running a Fortran
9223 macro while expecting a result about her Fortran 77 compiler@enddots{}
9227 @defmac AC_REQUIRE_CPP
9228 @acindex{REQUIRE_CPP}
9229 Ensure that whichever preprocessor would currently be used for tests has
9230 been found. Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9231 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9232 depending on which language is current.
9236 @node Writing Test Programs
9237 @section Writing Test Programs
9239 Autoconf tests follow a common scheme: feed some program with some
9240 input, and most of the time, feed a compiler with some source file.
9241 This section is dedicated to these source samples.
9244 * Guidelines:: General rules for writing test programs
9245 * Test Functions:: Avoiding pitfalls in test programs
9246 * Generating Sources:: Source program boilerplate
9250 @subsection Guidelines for Test Programs
9252 The most important rule to follow when writing testing samples is:
9254 @center @emph{Look for realism.}
9256 This motto means that testing samples must be written with the same
9257 strictness as real programs are written. In particular, you should
9258 avoid ``shortcuts'' and simplifications.
9260 Don't just play with the preprocessor if you want to prepare a
9261 compilation. For instance, using @command{cpp} to check whether a header is
9262 functional might let your @command{configure} accept a header which
9263 causes some @emph{compiler} error. Do not hesitate to check a header with
9264 other headers included before, especially required headers.
9266 Make sure the symbols you use are properly defined, i.e., refrain from
9267 simply declaring a function yourself instead of including the proper
9270 Test programs should not write to standard output. They
9271 should exit with status 0 if the test succeeds, and with status 1
9272 otherwise, so that success
9273 can be distinguished easily from a core dump or other failure;
9274 segmentation violations and other failures produce a nonzero exit
9275 status. Unless you arrange for @code{exit} to be declared, test
9276 programs should @code{return}, not @code{exit}, from @code{main},
9277 because on many systems @code{exit} is not declared by default.
9279 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9280 preprocessor macros defined by tests that have already run. For
9281 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9282 @file{configure.ac} you can have a test program that includes
9283 @file{stdbool.h} conditionally:
9287 #ifdef HAVE_STDBOOL_H
9288 # include <stdbool.h>
9293 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9294 work with any standard C compiler. Some developers prefer @code{#if}
9295 because it is easier to read, while others prefer @code{#ifdef} because
9296 it avoids diagnostics with picky compilers like GCC with the
9297 @option{-Wundef} option.
9299 If a test program needs to use or create a data file, give it a name
9300 that starts with @file{conftest}, such as @file{conftest.data}. The
9301 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9302 after running test programs and if the script is interrupted.
9304 @node Test Functions
9305 @subsection Test Functions
9307 Functions in test code should use function prototypes, introduced in C89
9308 and required in C23.
9310 Functions that test programs declare should also be conditionalized for
9311 C++, which requires @samp{extern "C"} prototypes. Make sure to not
9312 include any header files containing clashing prototypes.
9318 void *valloc (size_t);
9321 If a test program calls a function with invalid parameters (just to see
9322 whether it exists), organize the program to ensure that it never invokes
9323 that function. You can do this by calling it in another function that is
9324 never invoked. You can't do it by putting it after a call to
9325 @code{exit}, because GCC version 2 knows that @code{exit}
9327 and optimizes out any code that follows it in the same block.
9329 If you include any header files, be sure to call the functions
9330 relevant to them with the correct number of arguments, even if they are
9331 just 0, to avoid compilation errors due to prototypes. GCC
9333 has internal prototypes for several functions that it automatically
9334 inlines; for example, @code{memcpy}. To avoid errors when checking for
9335 them, either pass them the correct number of arguments or redeclare them
9336 with a different return type (such as @code{char}).
9339 @node Generating Sources
9340 @subsection Generating Sources
9342 Autoconf provides a set of macros that can be used to generate test
9343 source files. They are written to be language generic, i.e., they
9344 actually depend on the current language (@pxref{Language Choice}) to
9345 ``format'' the output properly.
9348 @defmac AC_LANG_CONFTEST (@var{source})
9349 @acindex{LANG_CONFTEST}
9350 Save the @var{source} text in the current test source file:
9351 @file{conftest.@var{extension}} where the @var{extension} depends on the
9352 current language. As of Autoconf 2.63b, the source file also contains
9353 the results of all of the @code{AC_DEFINE} performed so far.
9355 Note that the @var{source} is evaluated exactly once, like regular
9356 Autoconf macro arguments, and therefore (i) you may pass a macro
9357 invocation, (ii) if not, be sure to double quote if needed.
9359 The @var{source} text is expanded as an unquoted here-document, so
9360 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9361 @xref{Here-Documents}.
9363 This macro issues a warning during @command{autoconf} processing if
9364 @var{source} does not include an expansion of the macro
9365 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9366 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9368 This macro is seldom called directly, but is used under the hood by more
9369 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9372 @defmac AC_LANG_DEFINES_PROVIDED
9373 @acindex{LANG_DEFINES_PROVIDED}
9374 This macro is called as a witness that the file
9375 @file{conftest.@var{extension}} appropriate for the current language is
9376 complete, including all previously determined results from
9377 @code{AC_DEFINE}. This macro is seldom called directly, but exists if
9378 you have a compelling reason to write a conftest file without using
9379 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9380 @code{AC_LANG_CONFTEST}.
9383 @defmac AC_LANG_SOURCE (@var{source})
9384 @acindex{LANG_SOURCE}
9385 Expands into the @var{source}, with the definition of
9386 all the @code{AC_DEFINE} performed so far. This macro includes an
9387 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9389 In many cases, you may find it more convenient to use the wrapper
9390 @code{AC_LANG_PROGRAM}.
9393 For instance, executing (observe the double quotation!):
9396 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9397 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9398 [https://www.example.org/])
9399 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9400 [Greetings string.])
9403 [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9404 gcc -E -dD conftest.c
9408 on a system with @command{gcc} installed, results in:
9411 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9413 @asis{#} 1 "conftest.c"
9415 #define PACKAGE_NAME "Hello"
9416 #define PACKAGE_TARNAME "hello"
9417 #define PACKAGE_VERSION "1.0"
9418 #define PACKAGE_STRING "Hello 1.0"
9419 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9420 #define PACKAGE_URL "https://www.example.org/"
9421 #define HELLO_WORLD "Hello, World\n"
9423 const char hw[] = "Hello, World\n";
9426 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9427 definitions are not automatically translated into constants in the
9428 source code by this macro.
9430 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9431 @acindex{LANG_PROGRAM}
9432 Expands into a source file which consists of the @var{prologue}, and
9433 then @var{body} as body of the main function (e.g., @code{main} in
9434 C). Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9441 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9442 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9443 [https://www.example.org/])
9444 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9445 [Greetings string.])
9447 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9448 [[fputs (hw, stdout);]])])
9449 gcc -E -dD conftest.c
9453 on a system with @command{gcc} installed, results in:
9456 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9458 @asis{#} 1 "conftest.c"
9460 #define PACKAGE_NAME "Hello"
9461 #define PACKAGE_TARNAME "hello"
9462 #define PACKAGE_VERSION "1.0"
9463 #define PACKAGE_STRING "Hello 1.0"
9464 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9465 #define PACKAGE_URL "https://www.example.org/"
9466 #define HELLO_WORLD "Hello, World\n"
9468 const char hw[] = "Hello, World\n";
9478 In Erlang tests, the created source file is that of an Erlang module called
9479 @code{conftest} (@file{conftest.erl}). This module defines and exports
9481 one @code{start/0} function, which is called to perform the test. The
9482 @var{prologue} is optional code that is inserted between the module header and
9483 the @code{start/0} function definition. @var{body} is the body of the
9484 @code{start/0} function without the final period (@pxref{Runtime}, about
9485 constraints on this function's behavior).
9490 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9493 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9494 [[io:format("~s~n", [?HELLO_WORLD])]])])
9504 -define(HELLO_WORLD, "Hello, world!").
9506 io:format("~s~n", [?HELLO_WORLD])
9510 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9512 Expands into a source file which consists of the @var{prologue}, and
9513 then a call to the @var{function} as body of the main function (e.g.,
9514 @code{main} in C). Since it uses @code{AC_LANG_PROGRAM}, the feature
9515 of the latter are available.
9517 This function will probably be replaced in the future by a version
9518 which would enable specifying the arguments. The use of this macro is
9519 not encouraged, as it violates strongly the typing system.
9521 This macro cannot be used for Erlang tests.
9524 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9525 @acindex{LANG_FUNC_LINK_TRY}
9526 Expands into a source file which uses the @var{function} in the body of
9527 the main function (e.g., @code{main} in C). Since it uses
9528 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9530 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9531 It is considered to be severely broken, and in the future will be
9532 removed in favor of actual function calls (with properly typed
9535 This macro cannot be used for Erlang tests.
9538 @node Running the Preprocessor
9539 @section Running the Preprocessor
9541 Sometimes one might need to run the preprocessor on some source file.
9542 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9543 your project, not merely run the preprocessor on it; therefore you
9544 certainly want to run the compiler, not the preprocessor. Resist the
9545 temptation of following the easiest path.
9547 Nevertheless, if you need to run the preprocessor, then use
9548 @code{AC_PREPROC_IFELSE}.
9550 The macros described in this section cannot be used for tests in Erlang,
9551 Fortran, or Go, since those languages require no preprocessor.
9553 @anchor{AC_PREPROC_IFELSE}
9554 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9555 @ovar{action-if-false})
9556 @acindex{PREPROC_IFELSE}
9557 Run the preprocessor of the current language (@pxref{Language Choice})
9558 on the @var{input}, run the shell commands @var{action-if-true} on
9559 success, @var{action-if-false} otherwise.
9561 If @var{input} is nonempty use the equivalent of
9562 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9563 file; otherwise reuse the already-existing test source file.
9564 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9565 The @var{input} text is expanded as an unquoted here-document, so
9566 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9567 @xref{Here-Documents}.
9569 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9570 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9573 It is customary to report unexpected failures with
9574 @code{AC_MSG_FAILURE}. If needed, @var{action-if-true} can further access
9575 the preprocessed output in the file @file{conftest.i}.
9581 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9582 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9583 [Greetings string.])
9585 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9586 [[fputs (hw, stdout);]])],
9587 [AC_MSG_RESULT([OK])],
9588 [AC_MSG_FAILURE([unexpected preprocessor failure])])
9595 checking for gcc... gcc
9596 checking whether the C compiler works... yes
9597 checking for C compiler default output file name... a.out
9598 checking for suffix of executables...
9599 checking whether we are cross compiling... no
9600 checking for suffix of object files... o
9601 checking whether the compiler supports GNU C... yes
9602 checking whether gcc accepts -g... yes
9603 checking for gcc option to enable C23 features... -std=gnu23
9604 checking how to run the C preprocessor... gcc -std=gnu23 -E
9610 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9611 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9612 it impossible to use it to elaborate sources. You are encouraged to
9613 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9614 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9615 to run the @emph{preprocessor} and not the compiler?
9617 @anchor{AC_EGREP_HEADER}
9618 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9619 @var{action-if-found}, @ovar{action-if-not-found})
9620 @acindex{EGREP_HEADER}
9621 @var{pattern}, after being expanded as if in a double-quoted shell string,
9622 is an extended regular expression.
9623 If the output of running the preprocessor on the system header file
9624 @var{header-file} contains a line matching
9625 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9626 execute @var{action-if-not-found}.
9628 See below for some problems involving this macro.
9631 @anchor{AC_EGREP_CPP}
9632 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9633 @ovar{action-if-found}, @ovar{action-if-not-found})
9635 @var{pattern}, after being expanded as if in a double-quoted shell string,
9636 is an extended regular expression.
9637 @var{program} is the text of a C or C++ program, which is expanded as an
9638 unquoted here-document (@pxref{Here-Documents}). If the
9639 output of running the preprocessor on @var{program} contains a line
9640 matching @var{pattern}, execute shell commands
9641 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9643 See below for some problems involving this macro.
9646 @code{AC_EGREP_CPP} and @code{AC_EGREP_HEADER} should be used with care,
9647 as preprocessors can insert line breaks between output tokens. For
9648 example, the preprocessor might transform this:
9653 Version MAJOR . MINOR
9667 Because preprocessors are allowed to insert white space, change escapes
9668 in string constants, insert backlash-newline pairs, or do any of a number
9669 of things that do not change the meaning of the preprocessed program, it
9670 is better to rely on @code{AC_PREPROC_IFELSE} than to resort to
9671 @code{AC_EGREP_CPP} or @code{AC_EGREP_HEADER}.
9673 For more information about what can appear in portable extended regular
9674 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
9676 @node Running the Compiler
9677 @section Running the Compiler
9679 To check for a syntax feature of the current language's (@pxref{Language
9680 Choice}) compiler, such as whether it recognizes a certain keyword, or
9681 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9682 to compile a small program that uses that feature.
9684 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9685 @ovar{action-if-false})
9686 @acindex{COMPILE_IFELSE}
9687 Run the compiler and compilation flags of the current language
9688 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9689 @var{action-if-true} on success, @var{action-if-false} otherwise.
9691 If @var{input} is nonempty use the equivalent of
9692 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9693 file; otherwise reuse the already-existing test source file.
9694 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9695 The @var{input} text is expanded as an unquoted here-document, so
9696 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9697 @xref{Here-Documents}.
9699 It is customary to report unexpected failures with
9700 @code{AC_MSG_FAILURE}. This macro does not try to link; use
9701 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9702 Linker}). If needed, @var{action-if-true} can further access the
9703 just-compiled object file @file{conftest.$OBJEXT}.
9705 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9706 current language, which means that if the compiler has not yet been
9707 determined, the compiler determination will be made prior to the body of
9708 the outermost @code{AC_DEFUN} macro that triggered this macro to
9709 expand (@pxref{Expanded Before Required}).
9713 For tests in Erlang, the @var{input} must be the source code of a module named
9714 @code{conftest}. @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9715 file that can be interpreted by the Erlang virtual machine (@code{ERL}). It is
9716 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9717 to ensure that the Erlang module has the right name.
9719 @node Running the Linker
9720 @section Running the Linker
9722 To check for a library, a function, or a global variable, Autoconf
9723 @command{configure} scripts try to compile and link a small program that
9724 uses it. This is unlike Metaconfig, which by default uses @code{nm} or
9725 @code{ar} on the C library to try to figure out which functions are
9726 available. Trying to link with the function is usually a more reliable
9727 approach because it avoids dealing with the variations in the options
9728 and output formats of @code{nm} and @code{ar} and in the location of the
9729 standard libraries. It also allows configuring for cross-compilation or
9730 checking a function's runtime behavior if needed. On the other hand,
9731 it can be slower than scanning the libraries once, but accuracy is more
9732 important than speed.
9734 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9735 functions and global variables. It is also used by @code{AC_CHECK_LIB}
9736 to check for libraries (@pxref{Libraries}), by adding the library being
9737 checked for to @code{LIBS} temporarily and trying to link a small
9740 @anchor{AC_LINK_IFELSE}
9741 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9742 @ovar{action-if-false})
9743 @acindex{LINK_IFELSE}
9744 Run the compiler (and compilation flags) and the linker of the current
9745 language (@pxref{Language Choice}) on the @var{input}, run the shell
9746 commands @var{action-if-true} on success, @var{action-if-false}
9747 otherwise. If needed, @var{action-if-true} can further access the
9748 just-linked program file @file{conftest$EXEEXT}.
9750 If @var{input} is nonempty use the equivalent of
9751 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9752 file; otherwise reuse the already-existing test source file.
9753 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9754 The @var{input} text is expanded as an unquoted here-document, so
9755 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9756 @xref{Here-Documents}.
9758 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9759 current compilation flags.
9761 It is customary to report unexpected failures with
9762 @code{AC_MSG_FAILURE}. This macro does not try to execute the program;
9763 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9766 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9767 programs are interpreted and do not require linking.
9772 @section Checking Runtime Behavior
9774 Sometimes you need to find out how a system performs at runtime, such
9775 as whether a given function has a certain capability or bug. If you
9776 can, make such checks when your program runs instead of when it is
9777 configured. You can check for things like the machine's endianness when
9778 your program initializes itself.
9780 If you really need to test for a runtime behavior while configuring,
9781 you can write a test program to determine the result, and compile and
9782 run it using @code{AC_RUN_IFELSE}. Avoid running test programs if
9783 possible, because this prevents people from configuring your package for
9786 @anchor{AC_RUN_IFELSE}
9787 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9788 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9789 @acindex{RUN_IFELSE}
9790 Run the compiler (and compilation flags) and the linker of the current
9791 language (@pxref{Language Choice}) on the @var{input}, then execute the
9792 resulting program. If the program returns an exit
9793 status of 0 when executed, run shell commands @var{action-if-true}.
9794 Otherwise, run shell commands @var{action-if-false}.
9796 If @var{input} is nonempty use the equivalent of
9797 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9798 file; otherwise reuse the already-existing test source file.
9799 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9800 The @var{input} text is expanded as an unquoted here-document, so
9801 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9802 @xref{Here-Documents}.
9804 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9805 compilation flags of the current language (@pxref{Language Choice}).
9806 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9807 for further testing.
9809 In the @var{action-if-false} section, the failing exit status is
9810 available in the shell variable @samp{$?}. This exit status might be
9811 that of a failed compilation, or it might be that of a failed program
9814 If cross-compilation mode is enabled (this is the case if either the
9815 compiler being used does not produce executables that run on the system
9816 where @command{configure} is being run, or if the options @code{--build}
9817 and @code{--host} were both specified and their values are different),
9818 then the test program is
9819 not run. If the optional shell commands @var{action-if-cross-compiling}
9820 are given, those commands are run instead; typically these commands
9821 provide pessimistic defaults that allow cross-compilation to work even
9822 if the guess was wrong. If the fourth argument is empty or omitted, but
9823 cross-compilation is detected, then @command{configure} prints an error
9824 message and exits. If you want your package to be useful in a
9825 cross-compilation scenario, you @emph{should} provide a non-empty
9826 @var{action-if-cross-compiling} clause, as well as wrap the
9827 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9828 (@pxref{Caching Results}) which allows the user to override the
9829 pessimistic default if needed.
9831 It is customary to report unexpected failures with
9832 @code{AC_MSG_FAILURE}.
9835 @command{autoconf} prints a warning message when creating
9836 @command{configure} each time it encounters a call to
9837 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9838 given. If you are not concerned about users configuring your package
9839 for cross-compilation, you may ignore the warning. A few of the macros
9840 distributed with Autoconf produce this warning message; but if this is a
9841 problem for you, please report it as a bug, along with an appropriate
9842 pessimistic guess to use instead.
9844 To configure for cross-compiling you can also choose a value for those
9845 parameters based on the canonical system name (@pxref{Manual
9846 Configuration}). Alternatively, set up a test results cache file with
9847 the correct values for the host system (@pxref{Caching Results}).
9849 @ovindex cross_compiling
9850 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9851 in other macros, including a few of the ones that come with Autoconf,
9852 you can test whether the shell variable @code{cross_compiling} is set to
9853 @samp{yes}, and then use an alternate method to get the results instead
9854 of calling the macros.
9856 It is also permissible to temporarily assign to @code{cross_compiling}
9857 in order to force tests to behave as though they are in a
9858 cross-compilation environment, particularly since this provides a way to
9859 test your @var{action-if-cross-compiling} even when you are not using a
9863 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9864 # to use the slow link-only method
9865 save_cross_compiling=$cross_compiling
9867 AC_COMPUTE_INT([@dots{}])
9868 cross_compiling=$save_cross_compiling
9871 A C or C++ runtime test should be portable.
9872 @xref{Portable C and C++}.
9874 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9875 function: the given status code is used to determine the success of the test
9876 (status is @code{0}) or its failure (status is different than @code{0}), as
9877 explained above. It must be noted that data output through the standard output
9878 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9879 Therefore, if a test must output configuration information, it is recommended
9880 to create and to output data into the temporary file named @file{conftest.out},
9881 using the functions of module @code{file}. The @code{conftest.out} file is
9882 automatically deleted by the @code{AC_RUN_IFELSE} macro. For instance, a
9883 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9887 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9891 [AC_LANG_PROGRAM([], [dnl
9892 file:write_file("conftest.out", code:lib_dir()),
9894 [AS_ECHO(["code:lib_dir() returned: `cat conftest.out`"])],
9895 [AC_MSG_FAILURE([test Erlang program execution failed])])
9899 @node Multiple Cases
9900 @section Multiple Cases
9902 Some operations are accomplished in several possible ways, depending on
9903 the OS variant. Checking for them essentially requires a ``case
9904 statement''. Autoconf does not directly provide one; however, it is
9905 easy to simulate by using a shell variable to keep track of whether a
9906 way to perform the operation has been found yet.
9908 Here is an example that uses the shell variable @code{fstype} to keep
9909 track of whether the remaining cases need to be checked. Note that
9910 since the value of @code{fstype} is under our control, we don't have to
9911 use the longer @samp{test "x$fstype" = xno}.
9915 AC_MSG_CHECKING([how to get file system type])
9917 # The order of these tests is important.
9918 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9919 #include <sys/fstyp.h>
9921 [AC_DEFINE([FSTYPE_STATVFS], [1],
9922 [Define if statvfs exists.])
9924 AS_IF([test $fstype = no],
9925 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9926 #include <sys/fstyp.h>
9928 [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9929 [Define if USG statfs.])
9931 AS_IF([test $fstype = no],
9932 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9933 #include <sys/vmount.h>
9935 [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9936 [Define if AIX statfs.])
9938 # (more cases omitted here)
9939 AC_MSG_RESULT([$fstype])
9943 @c ====================================================== Results of Tests.
9946 @chapter Results of Tests
9948 Once @command{configure} has determined whether a feature exists, what can
9949 it do to record that information? There are four sorts of things it can
9950 do: define a C preprocessor symbol, set a variable in the output files,
9951 save the result in a cache file for future @command{configure} runs, and
9952 print a message letting the user know the result of the test.
9955 * Defining Symbols:: Defining C preprocessor symbols
9956 * Setting Output Variables:: Replacing variables in output files
9957 * Special Chars in Variables:: Characters to beware of in variables
9958 * Caching Results:: Speeding up subsequent @command{configure} runs
9959 * Printing Messages:: Notifying @command{configure} users
9962 @node Defining Symbols
9963 @section Defining C Preprocessor Symbols
9965 A common action to take in response to a feature test is to define a C
9966 preprocessor symbol indicating the results of the test. That is done by
9967 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9969 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9970 into the output variable @code{DEFS}, which contains an option
9971 @option{-D@var{symbol}=@var{value}} for each symbol defined. Unlike in
9972 Autoconf version 1, there is no variable @code{DEFS} defined while
9973 @command{configure} is running. To check whether Autoconf macros have
9974 already defined a certain C preprocessor symbol, test the value of the
9975 appropriate cache variable, as in this example:
9978 AC_CHECK_FUNC([vprintf],
9979 [AC_DEFINE([HAVE_VPRINTF], [1],
9980 [Define if vprintf exists.])])
9981 AS_IF([test "x$ac_cv_func_vprintf" != xyes],
9982 [AC_CHECK_FUNC([_doprnt],
9983 [AC_DEFINE([HAVE_DOPRNT], [1],
9984 [Define if _doprnt exists.])])])
9987 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9988 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9989 correct values into @code{#define} statements in a template file.
9990 @xref{Configuration Headers}, for more information about this kind of
9993 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9994 @defmacx AC_DEFINE (@var{variable})
9995 @cvindex @var{variable}
9997 Define @var{variable} to @var{value} (verbatim), by defining a C
9998 preprocessor macro for @var{variable}. @var{variable} should be a C
9999 identifier, optionally suffixed by a parenthesized argument list to
10000 define a C preprocessor macro with arguments. The macro argument list,
10001 if present, should be a comma-separated list of C identifiers, possibly
10002 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
10003 @var{variable} should not contain comments, white space, trigraphs,
10004 backslash-newlines, universal character names, or non-ASCII
10007 @var{value} may contain backslash-escaped newlines, which will be
10008 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
10009 via @code{@@DEFS@@} (with no effect on the compilation, since the
10010 preprocessor sees only one line in the first place). @var{value} should
10011 not contain raw newlines. If you are not using
10012 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
10013 characters, as @command{make} tends to eat them. To use a shell
10014 variable, use @code{AC_DEFINE_UNQUOTED} instead.
10016 @var{description} is only useful if you are using
10017 @code{AC_CONFIG_HEADERS}. In this case, @var{description} is put into
10018 the generated @file{config.h.in} as the comment before the macro define.
10019 The following example defines the C preprocessor variable
10020 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
10023 AC_DEFINE([EQUATION], ["$a > $b"],
10024 [Equation string.])
10027 If neither @var{value} nor @var{description} are given, then
10028 @var{value} defaults to 1 instead of to the empty string. This is for
10029 backwards compatibility with older versions of Autoconf, but this usage
10030 is obsolescent and may be withdrawn in future versions of Autoconf.
10032 If the @var{variable} is a literal string, it is passed to
10033 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
10035 If multiple @code{AC_DEFINE} statements are executed for the same
10036 @var{variable} name (not counting any parenthesized argument list),
10040 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
10041 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
10042 @acindex{DEFINE_UNQUOTED}
10043 @cvindex @var{variable}
10044 Like @code{AC_DEFINE}, but three shell expansions are
10045 performed---once---on @var{variable} and @var{value}: variable expansion
10046 (@samp{$}), command substitution (@samp{`}), and backslash escaping
10047 (@samp{\}), as if in an unquoted here-document. Single and double quote
10048 characters in the value have no
10049 special meaning. Use this macro instead of @code{AC_DEFINE} when
10050 @var{variable} or @var{value} is a shell variable. Examples:
10053 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
10054 [Configuration machine file.])
10055 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
10056 [getgroups return type.])
10057 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
10058 [Translated header name.])
10062 Due to a syntactical oddity of the Bourne shell, do not use
10063 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
10064 calls from other macro calls or shell code; that can cause syntax errors
10065 in the resulting @command{configure} script. Use either blanks or
10066 newlines. That is, do this:
10069 AC_CHECK_HEADER([elf.h],
10070 [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
10077 AC_CHECK_HEADER([elf.h],
10078 [AC_DEFINE([SVR4], [1], [System V Release 4])
10079 LIBS="-lelf $LIBS"])
10086 AC_CHECK_HEADER([elf.h],
10087 [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
10090 @node Setting Output Variables
10091 @section Setting Output Variables
10092 @cindex Output variables
10094 Another way to record the results of tests is to set @dfn{output
10095 variables}, which are shell variables whose values are substituted into
10096 files that @command{configure} outputs. The two macros below create new
10097 output variables. @xref{Preset Output Variables}, for a list of output
10098 variables that are always available.
10100 @defmac AC_SUBST (@var{variable}, @ovar{value})
10102 Create an output variable from a shell variable. Make @code{AC_OUTPUT}
10103 substitute the variable @var{variable} into output files (typically one
10104 or more makefiles). This means that @code{AC_OUTPUT}
10105 replaces instances of @samp{@@@var{variable}@@} in input files with the
10106 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
10107 is called. The value can contain any non-@code{NUL} character, including
10108 newline. If you are using Automake 1.11 or newer, for newlines in values
10109 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
10110 @command{automake} from adding a line @code{@var{variable} =
10111 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
10112 Automake, automake, Other things Automake recognizes}).
10114 Variable occurrences should not overlap: e.g., an input file should
10115 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
10116 are variable names.
10117 The substituted value is not rescanned for more output variables;
10118 occurrences of @samp{@@@var{variable}@@} in the value are inserted
10119 literally into the output file. (The algorithm uses the special marker
10120 @code{|#_!!_#|} internally, so neither the substituted value nor the
10121 output file may contain @code{|#_!!_#|}.)
10123 If @var{value} is given, in addition assign it to @var{variable}.
10125 The string @var{variable} is passed to @code{m4_pattern_allow}
10126 (@pxref{Forbidden Patterns}). @var{variable} is not further expanded,
10127 even if there is another macro by the same name.
10130 @defmac AC_SUBST_FILE (@var{variable})
10131 @acindex{SUBST_FILE}
10132 Another way to create an output variable from a shell variable. Make
10133 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
10134 named by shell variable @var{variable} into output files. This means
10135 that @code{AC_OUTPUT} replaces instances of
10136 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
10137 with the contents of the file that the shell variable @var{variable}
10138 names when @code{AC_OUTPUT} is called. Set the variable to
10139 @file{/dev/null} for cases that do not have a file to insert.
10140 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
10141 line by itself, optionally surrounded by spaces and tabs. The
10142 substitution replaces the whole line, including the spaces, tabs, and
10143 the terminating newline.
10145 This macro is useful for inserting makefile fragments containing
10146 special dependencies or other @command{make} directives for particular host
10147 or target types into makefiles. For example, @file{configure.ac}
10151 AC_SUBST_FILE([host_frag])
10152 host_frag=$srcdir/conf/sun4.mh
10156 and then a @file{Makefile.in} could contain:
10162 The string @var{variable} is passed to @code{m4_pattern_allow}
10163 (@pxref{Forbidden Patterns}).
10166 @cindex Precious Variable
10167 @cindex Variable, Precious
10168 Running @command{configure} in varying environments can be extremely
10169 dangerous. If for instance the user runs @samp{CC=bizarre-cc
10170 ./configure}, then the cache, @file{config.h}, and many other output
10171 files depend upon @command{bizarre-cc} being the C compiler. If
10172 for some reason the user runs @command{./configure} again, or if it is
10173 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
10174 and @pxref{config.status Invocation}), then the configuration can be
10175 inconsistent, composed of results depending upon two different
10178 Environment variables that affect this situation, such as @samp{CC}
10179 above, are called @dfn{precious variables}, and can be declared as such
10180 by @code{AC_ARG_VAR}.
10182 @defmac AC_ARG_VAR (@var{variable}, @var{description})
10184 Declare @var{variable} is a precious variable, and include its
10185 @var{description} in the variable section of @samp{./configure --help}.
10187 Being precious means that
10190 @var{variable} is substituted via @code{AC_SUBST}.
10193 The value of @var{variable} when @command{configure} was launched is
10194 saved in the cache, including if it was not specified on the command
10195 line but via the environment. Indeed, while @command{configure} can
10196 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
10197 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
10198 which, unfortunately, is what most users do.
10200 We emphasize that it is the @emph{initial} value of @var{variable} which
10201 is saved, not that found during the execution of @command{configure}.
10202 Indeed, specifying @samp{./configure FOO=foo} and letting
10203 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
10207 @var{variable} is checked for consistency between two
10208 @command{configure} runs. For instance:
10211 $ @kbd{./configure --silent --config-cache}
10212 $ @kbd{CC=cc ./configure --silent --config-cache}
10213 configure: error: 'CC' was not set in the previous run
10214 configure: error: changes in the environment can compromise \
10216 configure: error: run 'make distclean' and/or \
10217 'rm config.cache' and start over
10221 and similarly if the variable is unset, or if its content is changed.
10222 If the content has white space changes only, then the error is degraded
10223 to a warning only, but the old value is reused.
10226 @var{variable} is kept during automatic reconfiguration
10227 (@pxref{config.status Invocation}) as if it had been passed as a command
10228 line argument, including when no cache is used:
10231 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10232 $ @kbd{./config.status --recheck}
10233 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10234 CC=/usr/bin/cc --no-create --no-recursion
10239 @node Special Chars in Variables
10240 @section Special Characters in Output Variables
10241 @cindex Output variables, special characters in
10243 Many output variables are intended to be evaluated both by
10244 @command{make} and by the shell. Some characters are expanded
10245 differently in these two contexts, so to avoid confusion these
10246 variables' values should not contain any of the following characters:
10249 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10252 Also, these variables' values should neither contain newlines, nor start
10253 with @samp{~}, nor contain white space or @samp{:} immediately followed
10254 by @samp{~}. The values can contain nonempty sequences of white space
10255 characters like tabs and spaces, but each such sequence might
10256 arbitrarily be replaced by a single space during substitution.
10258 These restrictions apply both to the values that @command{configure}
10259 computes, and to the values set directly by the user. For example, the
10260 following invocations of @command{configure} are problematic, since they
10261 attempt to use special characters within @code{CPPFLAGS} and white space
10262 within @code{$(srcdir)}:
10265 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10267 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10270 @node Caching Results
10271 @section Caching Results
10274 To avoid checking for the same features repeatedly in various
10275 @command{configure} scripts (or in repeated runs of one script),
10276 @command{configure} can optionally save the results of many checks in a
10277 @dfn{cache file} (@pxref{Cache Files}). If a @command{configure} script
10278 runs with caching enabled and finds a cache file, it reads the results
10279 of previous runs from the cache and avoids rerunning those checks. As a
10280 result, @command{configure} can then run much faster than if it had to
10281 perform all of the checks every time.
10283 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10284 @acindex{CACHE_VAL}
10285 Ensure that the results of the check identified by @var{cache-id} are
10286 available. If the results of the check were in the cache file that was
10287 read, and @command{configure} was not given the @option{--quiet} or
10288 @option{--silent} option, print a message saying that the result was
10289 cached; otherwise, run the shell commands @var{commands-to-set-it}. If
10290 the shell commands are run to determine the value, the value is
10291 saved in the cache file just before @command{configure} creates its output
10292 files. @xref{Cache Variable Names}, for how to choose the name of the
10293 @var{cache-id} variable.
10295 The @var{commands-to-set-it} @emph{must have no side effects} except for
10296 setting the variable @var{cache-id}, see below.
10299 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10300 @var{commands-to-set-it})
10301 @acindex{CACHE_CHECK}
10302 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10303 messages. This macro provides a convenient shorthand for the most
10304 common way to use these macros. It calls @code{AC_MSG_CHECKING} for
10305 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10306 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10308 The @var{commands-to-set-it} @emph{must have no side effects} except for
10309 setting the variable @var{cache-id}, see below.
10312 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10313 @code{AC_CACHE_CHECK}, because people are tempted to call
10314 @code{AC_DEFINE} in the @var{commands-to-set-it}. Instead, the code that
10315 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10316 @code{AC_DEFINE}, by examining the value of the cache variable. For
10317 instance, the following macro is broken:
10320 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10322 AC_DEFUN([AC_SHELL_TRUE],
10323 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10324 [my_cv_shell_true_works=no
10325 (true) 2>/dev/null && my_cv_shell_true_works=yes
10326 if test "x$my_cv_shell_true_works" = xyes; then
10327 AC_DEFINE([TRUE_WORKS], [1],
10328 [Define if 'true(1)' works properly.])
10335 This fails if the cache is enabled: the second time this macro is run,
10336 @code{TRUE_WORKS} @emph{will not be defined}. The proper implementation
10340 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10342 AC_DEFUN([AC_SHELL_TRUE],
10343 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10344 [my_cv_shell_true_works=no
10345 (true) 2>/dev/null && my_cv_shell_true_works=yes])
10346 if test "x$my_cv_shell_true_works" = xyes; then
10347 AC_DEFINE([TRUE_WORKS], [1],
10348 [Define if 'true(1)' works properly.])
10354 Also, @var{commands-to-set-it} should not print any messages, for
10355 example with @code{AC_MSG_CHECKING}; do that before calling
10356 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10357 the results of the check are retrieved from the cache or determined by
10358 running the shell commands.
10361 * Cache Variable Names:: Shell variables used in caches
10362 * Cache Files:: Files @command{configure} uses for caching
10363 * Cache Checkpointing:: Loading and saving the cache file
10366 @node Cache Variable Names
10367 @subsection Cache Variable Names
10368 @cindex Cache variable
10370 The names of cache variables should have the following format:
10373 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10377 for example, @samp{ac_cv_header_stat_broken} or
10378 @samp{ac_cv_prog_gcc_traditional}. The parts of the variable name are:
10381 @item @var{package-prefix}
10382 An abbreviation for your package or organization; the same prefix you
10383 begin local Autoconf macros with, except lowercase by convention.
10384 For cache values used by the distributed Autoconf macros, this value is
10388 Indicates that this shell variable is a cache value. This string
10389 @emph{must} be present in the variable name, including the leading
10392 @item @var{value-type}
10393 A convention for classifying cache values, to produce a rational naming
10394 system. The values used in Autoconf are listed in @ref{Macro Names}.
10396 @item @var{specific-value}
10397 Which member of the class of cache values this test applies to.
10398 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10399 output variable (@samp{INSTALL}).
10401 @item @var{additional-options}
10402 Any particular behavior of the specific member that this test applies to.
10403 For example, @samp{broken} or @samp{set}. This part of the name may
10404 be omitted if it does not apply.
10407 The values assigned to cache variables may not contain newlines.
10408 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10409 names of files or functions; so this is not an important restriction.
10410 @ref{Cache Variable Index} for an index of cache variables with
10411 documented semantics.
10415 @subsection Cache Files
10417 A cache file is a shell script that caches the results of configure
10418 tests run on one system so they can be shared between configure scripts
10419 and configure runs. It is not useful on other systems. If its contents
10420 are invalid for some reason, the user may delete or edit it, or override
10421 documented cache variables on the @command{configure} command line.
10423 By default, @command{configure} uses no cache file,
10424 to avoid problems caused by accidental
10425 use of stale cache files.
10427 To enable caching, @command{configure} accepts @option{--config-cache} (or
10428 @option{-C}) to cache results in the file @file{config.cache}.
10429 Alternatively, @option{--cache-file=@var{file}} specifies that
10430 @var{file} be the cache file. The cache file is created if it does not
10431 exist already. When @command{configure} calls @command{configure} scripts in
10432 subdirectories, it uses the @option{--cache-file} argument so that they
10433 share the same cache. @xref{Subdirectories}, for information on
10434 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10436 @file{config.status} only pays attention to the cache file if it is
10437 given the @option{--recheck} option, which makes it rerun
10438 @command{configure}.
10440 It is wrong to try to distribute cache files for particular system types.
10441 There is too much room for error in doing that, and too much
10442 administrative overhead in maintaining them. For any features that
10443 can't be guessed automatically, use the standard method of the canonical
10444 system type and linking files (@pxref{Manual Configuration}).
10446 The site initialization script can specify a site-wide cache file to
10447 use, instead of the usual per-program cache. In this case, the cache
10448 file gradually accumulates information whenever someone runs a new
10449 @command{configure} script. (Running @command{configure} merges the new cache
10450 results with the existing cache file.) This may cause problems,
10451 however, if the system configuration (e.g., the installed libraries or
10452 compilers) changes and the stale cache file is not deleted.
10454 If @command{configure} is interrupted at the right time when it updates
10455 a cache file outside of the build directory where the @command{configure}
10456 script is run, it may leave behind a temporary file named after the
10457 cache file with digits following it. You may safely delete such a file.
10460 @node Cache Checkpointing
10461 @subsection Cache Checkpointing
10463 If your configure script, or a macro called from @file{configure.ac}, happens
10464 to abort the configure process, it may be useful to checkpoint the cache
10465 a few times at key points using @code{AC_CACHE_SAVE}. Doing so
10466 reduces the amount of time it takes to rerun the configure script with
10467 (hopefully) the error that caused the previous abort corrected.
10469 @c FIXME: Do we really want to document this guy?
10470 @defmac AC_CACHE_LOAD
10471 @acindex{CACHE_LOAD}
10472 Loads values from existing cache file, or creates a new cache file if a
10473 cache file is not found. Called automatically from @code{AC_INIT}.
10476 @defmac AC_CACHE_SAVE
10477 @acindex{CACHE_SAVE}
10478 Flushes all cached values to the cache file. Called automatically from
10479 @code{AC_OUTPUT}, but it can be quite useful to call
10480 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10486 @r{ @dots{} AC_INIT, etc. @dots{}}
10488 # Checks for programs.
10491 @r{ @dots{} more program checks @dots{}}
10496 # Checks for libraries.
10497 AC_CHECK_LIB([nsl], [gethostbyname])
10498 AC_CHECK_LIB([socket], [connect])
10499 @r{ @dots{} more lib checks @dots{}}
10504 # Might abort@dots{}
10505 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10506 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10508 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10511 @node Printing Messages
10512 @section Printing Messages
10513 @cindex Messages, from @command{configure}
10515 @command{configure} scripts need to give users running them several kinds
10516 of information. The following macros print messages in ways appropriate
10517 for each kind. The arguments to all of them get enclosed in shell
10518 double quotes, so the shell performs variable and back-quote
10519 substitution on them.
10521 These macros are all wrappers around the @command{printf} shell command.
10522 They direct output to the appropriate file descriptor (@pxref{File
10523 Descriptor Macros}).
10524 @command{configure} scripts should rarely need to run @command{printf} directly
10525 to print messages for the user. Using these macros makes it easy to
10526 change how and when each kind of message is printed; such changes need
10527 only be made to the macro definitions and all the callers change
10530 To diagnose static issues, i.e., when @command{autoconf} is run, see
10531 @ref{Diagnostic Macros}.
10533 @defmac AC_MSG_CHECKING (@var{feature-description})
10534 @acindex{MSG_CHECKING}
10535 Notify the user that @command{configure} is checking for a particular
10536 feature. This macro prints a message that starts with @samp{checking }
10537 and ends with @samp{...} and no newline. It must be followed by a call
10538 to @code{AC_MSG_RESULT} to print the result of the check and the
10539 newline. The @var{feature-description} should be something like
10540 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10543 This macro prints nothing if @command{configure} is run with the
10544 @option{--quiet} or @option{--silent} option.
10547 @anchor{AC_MSG_RESULT}
10548 @defmac AC_MSG_RESULT (@var{result-description})
10549 @acindex{MSG_RESULT}
10550 Notify the user of the results of a check. @var{result-description} is
10551 almost always the value of the cache variable for the check, typically
10552 @samp{yes}, @samp{no}, or a file name. This macro should follow a call
10553 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10554 the completion of the message printed by the call to
10555 @code{AC_MSG_CHECKING}.
10557 This macro prints nothing if @command{configure} is run with the
10558 @option{--quiet} or @option{--silent} option.
10561 @anchor{AC_MSG_NOTICE}
10562 @defmac AC_MSG_NOTICE (@var{message})
10563 @acindex{MSG_NOTICE}
10564 Deliver the @var{message} to the user. It is useful mainly to print a
10565 general description of the overall purpose of a group of feature checks,
10569 AC_MSG_NOTICE([checking if stack overflow is detectable])
10572 This macro prints nothing if @command{configure} is run with the
10573 @option{--quiet} or @option{--silent} option.
10576 @anchor{AC_MSG_ERROR}
10577 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10578 @acindex{MSG_ERROR}
10579 Notify the user of an error that prevents @command{configure} from
10580 completing. This macro prints an error message to the standard error
10581 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10582 by default, except that @samp{0} is converted to @samp{1}).
10583 @var{error-description} should be something like @samp{invalid value
10586 The @var{error-description} should start with a lower-case letter, and
10587 ``cannot'' is preferred to ``can't''.
10590 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10591 @acindex{MSG_FAILURE}
10592 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10593 prevents @command{configure} from completing @emph{and} that additional
10594 details are provided in @file{config.log}. This is typically used when
10595 abnormal results are found during a compilation.
10598 @anchor{AC_MSG_WARN}
10599 @defmac AC_MSG_WARN (@var{problem-description})
10601 Notify the @command{configure} user of a possible problem. This macro
10602 prints the message to the standard error output; @command{configure}
10603 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10604 provide a default (back-up) behavior for the situations they warn about.
10605 @var{problem-description} should be something like @samp{ln -s seems to
10611 @c ====================================================== Programming in M4.
10613 @node Programming in M4
10614 @chapter Programming in M4
10617 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10618 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10619 provides macros dedicated to shell script generation.
10621 As of this version of Autoconf, these two layers still contain
10622 experimental macros, whose interface might change in the future. As a
10623 matter of fact, @emph{anything that is not documented must not be used}.
10626 * M4 Quotation:: Protecting macros from unwanted expansion
10627 * Using autom4te:: The Autoconf executables backbone
10628 * Programming in M4sugar:: Convenient pure M4 macros
10629 * Debugging via autom4te:: Figuring out what M4 was doing
10633 @section M4 Quotation
10634 @cindex M4 quotation
10637 The most common problem with existing macros is an improper quotation.
10638 This section, which users of Autoconf can skip, but which macro writers
10639 @emph{must} read, first justifies the quotation scheme that was chosen
10640 for Autoconf and then ends with a rule of thumb. Understanding the
10641 former helps one to follow the latter.
10644 * Active Characters:: Characters that change the behavior of M4
10645 * One Macro Call:: Quotation and one macro call
10646 * Quoting and Parameters:: M4 vs. shell parameters
10647 * Quotation and Nested Macros:: Macros calling macros
10648 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
10649 * Quadrigraphs:: Another way to escape special characters
10650 * Balancing Parentheses:: Dealing with unbalanced parentheses
10651 * Quotation Rule Of Thumb:: One parenthesis, one quote
10654 @node Active Characters
10655 @subsection Active Characters
10657 To fully understand where proper quotation is important, you first need
10658 to know what the special characters are in Autoconf: @samp{#} introduces
10659 a comment inside which no macro expansion is performed, @samp{,}
10660 separates arguments, @samp{[} and @samp{]} are the quotes
10661 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10662 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10663 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10664 @samp{$} inside a macro definition.
10666 In order to understand the delicate case of macro calls, we first have
10667 to present some obvious failures. Below they are ``obvious-ified'',
10668 but when you find them in real life, they are usually in disguise.
10670 Comments, introduced by a hash and running up to the newline, are opaque
10671 tokens to the top level: active characters are turned off, and there is
10672 no macro expansion:
10675 # define([def], ine)
10676 @result{}# define([def], ine)
10679 Each time there can be a macro expansion, there is a quotation
10680 expansion, i.e., one level of quotes is stripped:
10684 @result{}int tab10;
10686 @result{}int tab[10];
10689 Without this in mind, the reader might try hopelessly to use her macro
10693 define([array], [int tab[10];])
10695 @result{}int tab10;
10701 How can you correctly output the intended results@footnote{Using
10705 @node One Macro Call
10706 @subsection One Macro Call
10708 Let's proceed on the interaction between active characters and macros
10709 with this small macro, which just returns its first argument:
10712 define([car], [$1])
10716 The two pairs of quotes above are not part of the arguments of
10717 @code{define}; rather, they are understood by the top level when it
10718 tries to find the arguments of @code{define}. Therefore, assuming
10719 @code{car} is not already defined, it is equivalent to write:
10726 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10727 quotes, it is bad practice for Autoconf macros which must both be more
10728 robust and also advocate perfect style.
10730 At the top level, there are only two possibilities: either you
10731 quote or you don't:
10736 [car(foo, bar, baz)]
10737 @result{}car(foo, bar, baz)
10740 Let's pay attention to the special characters:
10744 @error{}EOF in argument list
10747 The closing parenthesis is hidden in the comment; with a hypothetical
10748 quoting, the top level understood it this way:
10755 Proper quotation, of course, fixes the problem:
10762 Here are more examples:
10770 @result{}(foo, bar)
10771 car([(foo], [bar)])
10785 @node Quoting and Parameters
10786 @subsection Quoting and Parameters
10788 When M4 encounters @samp{$} within a macro definition, followed
10789 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10790 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10791 expansion. This happens regardless of how many layers of quotes the
10792 parameter expansion is nested within, or even if it occurs in text that
10793 will be rescanned as a comment.
10796 define([none], [$1])
10798 define([one], [[$1]])
10800 define([two], [[[$1]]])
10802 define([comment], [# $1])
10804 define([active], [ACTIVE])
10816 On the other hand, since autoconf generates shell code, you often want
10817 to output shell variable expansion, rather than performing M4 parameter
10818 expansion. To do this, you must use M4 quoting to separate the @samp{$}
10819 from the next character in the definition of your macro. If the macro
10820 definition occurs in single-quoted text, then insert another level of
10821 quoting; if the usage is already inside a double-quoted string, then
10822 split it into concatenated strings.
10825 define([foo], [a single-quoted $[]1 definition])
10827 define([bar], [[a double-quoted $][1 definition]])
10830 @result{}a single-quoted $1 definition
10832 @result{}a double-quoted $1 definition
10835 POSIX states that M4 implementations are free to provide implementation
10836 extensions when @samp{$@{} is encountered in a macro definition.
10837 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10838 extensions that will be available in the future GNU M4 2.0,
10839 but guarantees that all other instances of @samp{$@{} will be output
10840 literally. Therefore, this idiom can also be used to output shell code
10841 parameter references:
10844 define([first], [$@{1@}])first
10848 POSIX also states that @samp{$11} should expand to the first parameter
10849 concatenated with a literal @samp{1}, although some versions of
10850 GNU M4 expand the eleventh parameter instead. For
10851 portability, you should only use single-digit M4 parameter expansion.
10853 With this in mind, we can explore the cases where macros invoke
10856 @node Quotation and Nested Macros
10857 @subsection Quotation and Nested Macros
10859 The examples below use the following macros:
10862 define([car], [$1])
10863 define([active], [ACT, IVE])
10864 define([array], [int tab[10]])
10867 Each additional embedded macro call introduces other possible
10868 interesting quotations:
10879 In the first case, the top level looks for the arguments of @code{car},
10880 and finds @samp{active}. Because M4 evaluates its arguments
10881 before applying the macro, @samp{active} is expanded, which results in:
10889 In the second case, the top level gives @samp{active} as first and only
10890 argument of @code{car}, which results in:
10898 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10899 In the third case, @code{car} receives @samp{[active]}, which results in:
10907 exactly as we already saw above.
10909 The example above, applied to a more realistic example, gives:
10913 @result{}int tab10;
10914 car([int tab[10];])
10915 @result{}int tab10;
10916 car([[int tab[10];]])
10917 @result{}int tab[10];
10921 Huh? The first case is easily understood, but why is the second wrong,
10922 and the third right? To understand that, you must know that after
10923 M4 expands a macro, the resulting text is immediately subjected
10924 to macro expansion and quote removal. This means that the quote removal
10925 occurs twice---first before the argument is passed to the @code{car}
10926 macro, and second after the @code{car} macro expands to the first
10929 As the author of the Autoconf macro @code{car}, you then consider it to
10930 be incorrect that your users have to double-quote the arguments of
10931 @code{car}, so you ``fix'' your macro. Let's call it @code{qar} for
10935 define([qar], [[$1]])
10939 and check that @code{qar} is properly fixed:
10942 qar([int tab[10];])
10943 @result{}int tab[10];
10947 Ahhh! That's much better.
10949 But note what you've done: now that the result of @code{qar} is always
10950 a literal string, the only time a user can use nested macros is if she
10951 relies on an @emph{unquoted} macro call:
10961 leaving no way for her to reproduce what she used to do with @code{car}:
10969 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10973 define([my_includes], [#include <stdio.h>])
10975 @result{}#include <stdio.h>
10977 @error{}EOF in argument list
10980 This macro, @code{qar}, because it double quotes its arguments, forces
10981 its users to leave their macro calls unquoted, which is dangerous.
10982 Commas and other active symbols are interpreted by M4 before
10983 they are given to the macro, often not in the way the users expect.
10984 Also, because @code{qar} behaves differently from the other macros,
10985 it's an exception that should be avoided in Autoconf.
10987 @node Changequote is Evil
10988 @subsection @code{changequote} is Evil
10989 @cindex @code{changequote}
10991 The temptation is often high to bypass proper quotation, in particular
10992 when it's late at night. Then, many experienced Autoconf hackers
10993 finally surrender to the dark side of the force and use the ultimate
10994 weapon: @code{changequote}.
10996 The M4 builtin @code{changequote} belongs to a set of primitives that
10997 allow one to adjust the syntax of the language to adjust it to one's
10998 needs. For instance, by default M4 uses @samp{`} and @samp{'} as
10999 quotes, but in the context of shell programming (and actually of most
11000 programming languages), that's about the worst choice one can make:
11001 because of strings and back-quoted expressions in shell code (such as
11002 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
11003 programming languages (as in @samp{'0'}), there are many unbalanced
11004 @samp{`} and @samp{'}. Proper M4 quotation then becomes a nightmare, if
11005 not impossible. In order to make M4 useful in such a context, its
11006 designers have equipped it with @code{changequote}, which makes it
11007 possible to choose another pair of quotes. M4sugar, M4sh, Autoconf, and
11008 Autotest all have chosen to use @samp{[} and @samp{]}. Not especially
11009 because they are unlikely characters, but @emph{because they are
11010 characters unlikely to be unbalanced}.
11012 There are other magic primitives, such as @code{changecom} to specify
11013 what syntactic forms are comments (it is common to see
11014 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
11015 @code{changeword} and @code{changesyntax} to change other syntactic
11016 details (such as the character to denote the @var{n}th argument, @samp{$} by
11017 default, the parentheses around arguments, etc.).
11019 These primitives are really meant to make M4 more useful for specific
11020 domains: they should be considered like command line options:
11021 @option{--quotes}, @option{--comments}, @option{--words}, and
11022 @option{--syntax}. Nevertheless, they are implemented as M4 builtins, as
11023 it makes M4 libraries self contained (no need for additional options).
11025 There lies the problem@enddots{}
11029 The problem is that it is then tempting to use them in the middle of an
11030 M4 script, as opposed to its initialization. This, if not carefully
11031 thought out, can lead to disastrous effects: @emph{you are changing the
11032 language in the middle of the execution}. Changing and restoring the
11033 syntax is often not enough: if you happened to invoke macros in between,
11034 these macros are lost, as the current syntax is probably not
11035 the one they were implemented with.
11037 @c FIXME: I've been looking for a short, real case example, but I
11038 @c lost them all :(
11042 @subsection Quadrigraphs
11043 @cindex quadrigraphs
11044 @cindex @samp{@@S|@@}
11045 @cindex @samp{@@&t@@}
11046 @c Info cannot handle ':' in index entries.
11048 @cindex @samp{@@<:@@}
11049 @cindex @samp{@@:>@@}
11050 @cindex @samp{@@%:@@}
11051 @cindex @samp{@@@{:@@}
11052 @cindex @samp{@@:@}@@}
11055 When writing an Autoconf macro you may occasionally need to generate
11056 special characters that are difficult to express with the standard
11057 Autoconf quoting rules. For example, you may need to output the regular
11058 expression @samp{[^[]}, which matches any character other than @samp{[}.
11059 This expression contains unbalanced brackets so it cannot be put easily
11062 Additionally, there are a few m4sugar macros (such as @code{m4_split}
11063 and @code{m4_expand}) which internally use special markers in addition
11064 to the regular quoting characters. If the arguments to these macros
11065 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
11066 might behave incorrectly.
11068 You can work around these problems by using one of the following
11069 @dfn{quadrigraphs}:
11085 Expands to nothing.
11088 Quadrigraphs are replaced at a late stage of the translation process,
11089 after @command{m4} is run, so they do not get in the way of M4 quoting.
11090 For example, the string @samp{^@@<:@@}, independently of its quotation,
11091 appears as @samp{^[} in the output.
11093 The empty quadrigraph can be used:
11096 @item to mark trailing spaces explicitly
11098 Trailing spaces are smashed by @command{autom4te}. This is a feature.
11100 @item to produce quadrigraphs and other strings reserved by m4sugar
11102 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}. For a more
11106 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
11107 m4_split([a )@}>=- b -=<@{( c])
11108 @result{}[a], [], [B], [], [c]
11109 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
11110 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
11113 @item to escape @emph{occurrences} of forbidden patterns
11115 For instance you might want to mention @code{AC_FOO} in a comment, while
11116 still being sure that @command{autom4te} still catches unexpanded
11117 @samp{AC_*}. Then write @samp{AC@@&t@@_FOO}.
11120 The name @samp{@@&t@@} was suggested by Paul Eggert:
11123 I should give some credit to the @samp{@@&t@@} pun. The @samp{&} is my
11124 own invention, but the @samp{t} came from the source code of the
11125 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
11126 and which used @samp{mt} to denote the empty string. In C, it would
11127 have looked like something like:
11130 char const mt[] = "";
11134 but of course the source code was written in Algol 68.
11136 I don't know where he got @samp{mt} from: it could have been his own
11137 invention, and I suppose it could have been a common pun around the
11138 Cambridge University computer lab at the time.
11142 @node Balancing Parentheses
11143 @subsection Dealing with unbalanced parentheses
11144 @cindex balancing parentheses
11145 @cindex parentheses, balancing
11146 @cindex unbalanced parentheses, managing
11148 One of the pitfalls of portable shell programming is that
11149 if you intend your script to run with obsolescent shells,
11150 @command{case} statements require unbalanced parentheses.
11151 @xref{case, , Limitations of Shell Builtins}.
11152 With syntax highlighting
11153 editors, the presence of unbalanced @samp{)} can interfere with editors
11154 that perform syntax highlighting of macro contents based on finding the
11155 matching @samp{(}. Another concern is how much editing must be done
11156 when transferring code snippets between shell scripts and macro
11157 definitions. But most importantly, the presence of unbalanced
11158 parentheses can introduce expansion bugs.
11160 For an example, here is an underquoted attempt to use the macro
11161 @code{my_case}, which happens to expand to a portable @command{case}
11165 AC_DEFUN([my_case],
11166 [case $file_name in
11167 *.c) file_type='C source code';;
11173 In the above example, the @code{AS_IF} call under-quotes its arguments.
11174 As a result, the unbalanced @samp{)} generated by the premature
11175 expansion of @code{my_case} results in expanding @code{AS_IF} with a
11176 truncated parameter, and the expansion is syntactically invalid:
11183 fi file_type='C source code';;
11187 If nothing else, this should emphasize the importance of the quoting
11188 arguments to macro calls. On the other hand, there are several
11189 variations for defining @code{my_case} to be more robust, even when used
11190 without proper quoting, each with some benefits and some drawbacks.
11193 @item Use left parenthesis before pattern
11195 AC_DEFUN([my_case],
11196 [case $file_name in
11197 (*.c) file_type='C source code';;
11201 This is simple and provides balanced parentheses. Although this is not
11202 portable to obsolescent shells (notably Solaris 10 @command{/bin/sh}),
11203 platforms with these shells invariably have a more-modern shell
11204 available somewhere so this approach typically suffices nowadays.
11206 @item Creative literal shell comment
11208 AC_DEFUN([my_case],
11209 [case $file_name in #(
11210 *.c) file_type='C source code';;
11214 This version provides balanced parentheses to several editors, and can
11215 be copied and pasted into a terminal as is. Unfortunately, it is still
11216 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
11217 that masks the normal properties of @samp{(}.
11219 @item Quadrigraph shell comment
11221 AC_DEFUN([my_case],
11222 [case $file_name in @@%:@@(
11223 *.c) file_type='C source code';;
11227 This version provides balanced parentheses to even more editors, and can
11228 be used as a balanced Autoconf argument. Unfortunately, it requires
11229 some editing before it can be copied and pasted into a terminal, and the
11230 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
11232 @item Quoting just the parenthesis
11234 AC_DEFUN([my_case],
11235 [case $file_name in
11236 *.c[)] file_type='C source code';;
11240 This version quotes the @samp{)}, so that it can be used as a balanced
11241 Autoconf argument. As written, this is not balanced to an editor, but
11242 it can be coupled with @samp{[#(]} to meet that need, too. However, it
11243 still requires some edits before it can be copied and pasted into a
11246 @item Double-quoting the entire statement
11248 AC_DEFUN([my_case],
11249 [[case $file_name in #(
11250 *.c) file_type='C source code';;
11254 Since the entire macro is double-quoted, there is no problem with using
11255 this as an Autoconf argument; and since the double-quoting is over the
11256 entire statement, this code can be easily copied and pasted into a
11257 terminal. However, the double quoting prevents the expansion of any
11258 macros inside the case statement, which may cause its own set of
11261 @item Using @code{AS_CASE}
11263 AC_DEFUN([my_case],
11264 [AS_CASE([$file_name],
11265 [*.c], [file_type='C source code'])])
11268 This version avoids the balancing issue altogether, by relying on
11269 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11270 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11271 statement, rather than within a branch of the case statement that might
11272 not be taken. However, the abstraction comes with a penalty that it is
11273 no longer a quick copy, paste, and edit to get back to shell code.
11277 @node Quotation Rule Of Thumb
11278 @subsection Quotation Rule Of Thumb
11280 To conclude, the quotation rule of thumb is:
11282 @center @emph{One pair of quotes per pair of parentheses.}
11284 Never over-quote, never under-quote, in particular in the definition of
11285 macros. In the few places where the macros need to use brackets
11286 (usually in C program text or regular expressions), properly quote
11287 @emph{the arguments}!
11289 It is common to read Autoconf programs with snippets like:
11293 changequote(<<, >>)dnl
11294 <<#include <time.h>
11295 #ifndef tzname /* For SGI. */
11296 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11298 changequote([, ])dnl
11299 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11303 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11304 double quoting, so you just need:
11309 #ifndef tzname /* For SGI. */
11310 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11313 [ac_cv_var_tzname=yes],
11314 [ac_cv_var_tzname=no])
11318 The M4-fluent reader might note that these two examples are rigorously
11319 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11320 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11321 quotes are not part of the arguments!
11323 Simplified, the example above is just doing this:
11326 changequote(<<, >>)dnl
11328 changequote([, ])dnl
11338 With macros that do not double quote their arguments (which is the
11339 rule), double-quote the (risky) literals:
11342 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11343 [[#include <time.h>
11344 #ifndef tzname /* For SGI. */
11345 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11347 [atoi (*tzname);])],
11348 [ac_cv_var_tzname=yes],
11349 [ac_cv_var_tzname=no])
11352 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11353 should be using @code{AC_LINK_IFELSE} instead.
11355 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11356 where quoting does not suffice.
11358 When you create a @command{configure} script using newly written macros,
11359 examine it carefully to check whether you need to add more quotes in
11360 your macros. If one or more words have disappeared in the M4
11361 output, you need more quotes. When in doubt, quote.
11363 However, it's also possible to put on too many layers of quotes. If
11364 this happens, the resulting @command{configure} script may contain
11365 unexpanded macros. The @command{autoconf} program checks for this problem
11366 by looking for the string @samp{AC_} in @file{configure}. However, this
11367 heuristic does not work in general: for example, it does not catch
11368 overquoting in @code{AC_DEFINE} descriptions.
11371 @c ---------------------------------------- Using autom4te
11373 @node Using autom4te
11374 @section Using @command{autom4te}
11376 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11377 to Autoconf per se, heavily rely on M4. All these different uses
11378 revealed common needs factored into a layer over M4:
11379 @command{autom4te}@footnote{
11381 Yet another great name from Lars J. Aas.
11385 @command{autom4te} is a preprocessor that is like @command{m4}.
11386 It supports M4 extensions designed for use in tools like Autoconf.
11389 * autom4te Invocation:: A GNU M4 wrapper
11390 * Customizing autom4te:: Customizing the Autoconf package
11393 @node autom4te Invocation
11394 @subsection Invoking @command{autom4te}
11396 The command line arguments are modeled after M4's:
11399 autom4te @var{options} @var{files}
11404 where the @var{files} are directly passed to @command{m4}. By default,
11405 GNU M4 is found during configuration, but the environment
11407 @env{M4} can be set to tell @command{autom4te} where to look. In addition
11408 to the regular expansion, it handles the replacement of the quadrigraphs
11409 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11410 output. It supports an extended syntax for the @var{files}:
11413 @item @var{file}.m4f
11414 This file is an M4 frozen file. Note that @emph{all the previous files
11415 are ignored}. See the @option{--melt} option for the rationale.
11418 If found in the library path, the @var{file} is included for expansion,
11419 otherwise it is ignored instead of triggering a failure.
11424 Of course, it supports the Autoconf common subset of options:
11429 Print a summary of the command line options and exit.
11433 Print the version number of Autoconf and exit.
11437 Report processing steps.
11441 Don't remove the temporary files and be even more verbose.
11443 @item --include=@var{dir}
11444 @itemx -I @var{dir}
11445 Also look for input files in @var{dir}. Multiple invocations
11448 @item --output=@var{file}
11449 @itemx -o @var{file}
11450 Save output (script or trace) to @var{file}. The file @option{-} stands
11451 for the standard output.
11456 As an extension of @command{m4}, it includes the following options:
11460 @item --warnings=@var{category}[,@var{category}...]
11461 @itemx -W@var{category}[,@var{category}...]
11463 Enable or disable warnings related to each @var{category}.
11464 @xref{m4_warn}, for a comprehensive list of categories.
11465 Special values include:
11469 Enable all categories of warnings.
11472 Disable all categories of warnings.
11475 Treat all warnings as errors.
11477 @item no-@var{category}
11478 Disable warnings falling into @var{category}.
11481 The environment variable @env{WARNINGS} may also be set to a
11482 comma-separated list of warning categories to enable or disable.
11483 It is interpreted exactly the same way as the argument of
11484 @option{--warnings}, but unknown categories are silently ignored.
11485 The command line takes precedence; for instance, if @env{WARNINGS}
11486 is set to @code{obsolete}, but @option{-Wnone} is given on the
11487 command line, no warnings will be issued.
11489 Some categories of warnings are on by default.
11490 Again, for details see @ref{m4_warn}.
11494 Do not use frozen files. Any argument @code{@var{file}.m4f} is
11495 replaced by @code{@var{file}.m4}. This helps tracing the macros which
11496 are executed only when the files are frozen, typically
11497 @code{m4_define}. For instance, running:
11500 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11504 is roughly equivalent to running:
11507 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11514 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11521 m4 --reload-state=4.m4f input.m4
11526 Produce a frozen state file. @command{autom4te} freezing is stricter
11527 than M4's: it must produce no warnings, and no output other than empty
11528 lines (a line with white space is @emph{not} empty) and comments
11529 (starting with @samp{#}). Unlike @command{m4}'s similarly-named option,
11530 this option takes no argument:
11533 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11540 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11543 @item --mode=@var{octal-mode}
11544 @itemx -m @var{octal-mode}
11545 Set the mode of the non-traces output to @var{octal-mode}; by default
11551 @cindex @file{autom4te.cache}
11552 As another additional feature over @command{m4}, @command{autom4te}
11553 caches its results. GNU M4 is able to produce a regular
11554 output and traces at the same time. Traces are heavily used in the
11555 GNU Build System: @command{autoheader} uses them to build
11556 @file{config.h.in}, @command{autoreconf} to determine what
11557 GNU Build System components are used, @command{automake} to
11558 ``parse'' @file{configure.ac} etc. To avoid recomputation,
11559 traces are cached while performing regular expansion,
11560 and conversely. This cache is (actually, the caches are) stored in
11561 the directory @file{autom4te.cache}. @emph{It can safely be removed}
11562 at any moment (especially if for some reason @command{autom4te}
11563 considers it trashed).
11566 @item --cache=@var{directory}
11567 @itemx -C @var{directory}
11568 Specify the name of the directory where the result should be cached.
11569 Passing an empty value disables caching. Be sure to pass a relative
11570 file name, as for the time being, global caches are not supported.
11573 Don't cache the results.
11577 If a cache is used, consider it obsolete (but update it anyway).
11582 Because traces are so important to the GNU Build System,
11583 @command{autom4te} provides high level tracing features as compared to
11584 M4, and helps exploiting the cache:
11587 @item --trace=@var{macro}[:@var{format}]
11588 @itemx -t @var{macro}[:@var{format}]
11589 Trace the invocations of @var{macro} according to the @var{format}.
11590 Multiple @option{--trace} arguments can be used to list several macros.
11591 Multiple @option{--trace} arguments for a single macro are not
11592 cumulative; instead, you should just make @var{format} as long as
11595 The @var{format} is a regular string, with newlines if desired, and
11596 several special escape codes. It defaults to @samp{$f:$l:$n:$%}. It can
11597 use the following special escapes:
11601 @c $$ restore font-lock
11602 The character @samp{$}.
11605 The file name from which @var{macro} is called.
11608 The line number from which @var{macro} is called.
11611 The depth of the @var{macro} call. This is an M4 technical detail that
11612 you probably don't want to know about.
11615 The name of the @var{macro}.
11618 The @var{num}th argument of the call to @var{macro}.
11621 @itemx $@var{sep}@@
11622 @itemx $@{@var{separator}@}@@
11623 All the arguments passed to @var{macro}, separated by the character
11624 @var{sep} or the string @var{separator} (@samp{,} by default). Each
11625 argument is quoted, i.e., enclosed in a pair of square brackets.
11629 @itemx $@{@var{separator}@}*
11630 As above, but the arguments are not quoted.
11634 @itemx $@{@var{separator}@}%
11635 As above, but the arguments are not quoted, all new line characters in
11636 the arguments are smashed, and the default separator is @samp{:}.
11638 The escape @samp{$%} produces single-line trace outputs (unless you put
11639 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11643 @xref{autoconf Invocation}, for examples of trace uses.
11645 @item --preselect=@var{macro}
11646 @itemx -p @var{macro}
11647 Cache the traces of @var{macro}, but do not enable traces. This is
11648 especially important to save CPU cycles in the future. For instance,
11649 when invoked, @command{autoconf} pre-selects all the macros that
11650 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11651 trace, so that running @command{m4} is not needed to trace them: the
11652 cache suffices. This results in a huge speed-up.
11657 @cindex Autom4te Library
11658 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11659 libraries}. They consists in a powerful yet extremely simple feature:
11660 sets of combined command line arguments:
11663 @item --language=@var{language}
11664 @itemx -l @var{language}
11665 Use the @var{language} Autom4te library. Current languages include:
11669 create M4sugar output.
11672 create M4sh executable shell scripts.
11675 create Autotest executable test suites.
11677 @item Autoconf-without-aclocal-m4
11678 create Autoconf executable configure scripts without
11679 reading @file{aclocal.m4}.
11682 create Autoconf executable configure scripts. This language inherits
11683 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11684 additionally reads @file{aclocal.m4}.
11687 @item --prepend-include=@var{dir}
11688 @itemx -B @var{dir}
11689 Prepend directory @var{dir} to the search path. This is used to include
11690 the language-specific files before any third-party macros.
11694 @cindex @file{autom4te.cfg}
11695 As an example, if Autoconf is installed in its default location,
11696 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11697 strictly equivalent to the command:
11700 autom4te --prepend-include /usr/local/share/autoconf \
11701 m4sugar/m4sugar.m4f foo.m4
11705 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11706 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11710 autom4te --prepend-include /usr/local/share/autoconf \
11711 m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11715 The definition of the languages is stored in @file{autom4te.cfg}.
11717 @node Customizing autom4te
11718 @subsection Customizing @command{autom4te}
11720 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11721 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11722 as found in the directory from which @command{autom4te} is run). The
11723 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11724 then @file{./.autom4te.cfg}, and finally the command line arguments.
11726 In these text files, comments are introduced with @code{#}, and empty
11727 lines are ignored. Customization is performed on a per-language basis,
11728 wrapped in between a @samp{begin-language: "@var{language}"},
11729 @samp{end-language: "@var{language}"} pair.
11731 Customizing a language stands for appending options (@pxref{autom4te
11732 Invocation}) to the current definition of the language. Options, and
11733 more generally arguments, are introduced by @samp{args:
11734 @var{arguments}}. You may use the traditional shell syntax to quote the
11737 As an example, to disable Autoconf caches (@file{autom4te.cache})
11738 globally, include the following lines in @file{~/.autom4te.cfg}:
11741 ## ------------------ ##
11742 ## User Preferences. ##
11743 ## ------------------ ##
11745 begin-language: "Autoconf-without-aclocal-m4"
11747 end-language: "Autoconf-without-aclocal-m4"
11751 @node Programming in M4sugar
11752 @section Programming in M4sugar
11755 M4 by itself provides only a small, but sufficient, set of all-purpose
11756 macros. M4sugar introduces additional generic macros. Its name was
11757 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11760 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11761 the macro namespace @samp{^m4_} for M4sugar macros. You should not
11762 define your own macros into these namespaces.
11765 * Redefined M4 Macros:: M4 builtins changed in M4sugar
11766 * Diagnostic Macros:: Diagnostic messages from M4sugar
11767 * Diversion support:: Diversions in M4sugar
11768 * Conditional constructs:: Conditions in M4
11769 * Looping constructs:: Iteration in M4
11770 * Evaluation Macros:: More quotation and evaluation control
11771 * Text processing Macros:: String manipulation in M4
11772 * Number processing Macros:: Arithmetic computation in M4
11773 * Set manipulation Macros:: Set manipulation in M4
11774 * Forbidden Patterns:: Catching unexpanded macros
11777 @node Redefined M4 Macros
11778 @subsection Redefined M4 Macros
11781 @msindex{changecom}
11782 @msindex{changequote}
11783 @msindex{debugfile}
11784 @msindex{debugmode}
11805 With a few exceptions, all the M4 native macros are moved in the
11806 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11807 @code{m4_define} etc.
11809 The list of macros unchanged from M4, except for their name, is:
11813 @item m4_changequote
11838 Some M4 macros are redefined, and are slightly incompatible with their
11845 All M4 macros starting with @samp{__} retain their original name: for
11846 example, no @code{m4__file__} is defined.
11851 This is not technically a macro, but a feature of Autom4te. The
11852 sequence @code{__oline__} can be used similarly to the other m4sugar
11853 location macros, but rather than expanding to the location of the input
11854 file, it is translated to the line number where it appears in the output
11855 file after all other M4 expansions.
11860 This macro kept its original name: no @code{m4_dnl} is defined.
11863 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11864 @msindex{bpatsubst}
11865 This macro corresponds to @code{patsubst}. The name @code{m4_patsubst}
11866 is kept for future versions of M4sugar, once GNU M4 2.0 is
11867 released and supports extended regular expression syntax.
11870 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11872 This macro corresponds to @code{regexp}. The name @code{m4_regexp}
11873 is kept for future versions of M4sugar, once GNU M4 2.0 is
11874 released and supports extended regular expression syntax.
11877 @defmac m4_copy (@var{source}, @var{dest})
11878 @defmacx m4_copy_force (@var{source}, @var{dest})
11879 @defmacx m4_rename (@var{source}, @var{dest})
11880 @defmacx m4_rename_force (@var{source}, @var{dest})
11882 @msindex{copy_force}
11884 @msindex{rename_force}
11885 These macros aren't directly builtins, but are closely related to
11886 @code{m4_pushdef} and @code{m4_defn}. @code{m4_copy} and
11887 @code{m4_rename} ensure that @var{dest} is undefined, while
11888 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11889 definition. All four macros then proceed to copy the entire pushdef
11890 stack of definitions of @var{source} over to @var{dest}. @code{m4_copy}
11891 and @code{m4_copy_force} preserve the source (including in the special
11892 case where @var{source} is undefined), while @code{m4_rename} and
11893 @code{m4_rename_force} undefine the original macro name (making it an
11894 error to rename an undefined @var{source}).
11896 Note that attempting to invoke a renamed macro might not work, since the
11897 macro may have a dependence on helper macros accessed via composition of
11898 @samp{$0} but that were not also renamed; likewise, other macros may
11899 have a hard-coded dependence on @var{source} and could break if
11900 @var{source} has been deleted. On the other hand, it is always safe to
11901 rename a macro to temporarily move it out of the way, then rename it
11902 back later to restore original semantics.
11905 @defmac m4_defn (@var{macro}@dots{})
11907 This macro fails if @var{macro} is not defined, even when using older
11908 versions of M4 that did not warn. See @code{m4_undefine}.
11909 Unfortunately, in order to support these older versions of M4, there are
11910 some situations involving unbalanced quotes where concatenating multiple
11911 macros together will work in newer M4 but not in m4sugar; use
11912 quadrigraphs to work around this.
11915 @defmac m4_divert (@var{diversion})
11917 M4sugar relies heavily on diversions, so rather than behaving as a
11918 primitive, @code{m4_divert} behaves like:
11920 m4_divert_pop()m4_divert_push([@var{diversion}])
11923 @xref{Diversion support}, for more details about the use of the
11924 diversion stack. In particular, this implies that @var{diversion}
11925 should be a named diversion rather than a raw number. But be aware that
11926 it is seldom necessary to explicitly change the diversion stack, and
11927 that when done incorrectly, it can lead to syntactically invalid
11931 @defmac m4_dumpdef (@var{name}@dots{})
11932 @defmacx m4_dumpdefs (@var{name}@dots{})
11935 @code{m4_dumpdef} is like the M4 builtin, except that this version
11936 requires at least one argument, output always goes to standard error
11937 rather than the current debug file, no sorting is done on multiple
11938 arguments, and an error is issued if any
11939 @var{name} is undefined. @code{m4_dumpdefs} is a convenience macro that
11940 calls @code{m4_dumpdef} for all of the
11941 @code{m4_pushdef} stack of definitions, starting with the current, and
11942 silently does nothing if @var{name} is undefined.
11944 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11945 builtin is output as the empty string. This behavior is rectified by
11946 using M4 1.6 or newer. However, this behavior difference means that
11947 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11948 and never in the final published form of a macro.
11951 @defmac m4_esyscmd_s (@var{command})
11952 @msindex{esyscmd_s}
11953 Like @code{m4_esyscmd}, this macro expands to the result of running
11954 @var{command} in a shell. The difference is that any trailing newlines
11955 are removed, so that the output behaves more like shell command
11959 @defmac m4_exit (@var{exit-status})
11961 This macro corresponds to @code{m4exit}.
11964 @defmac m4_if (@var{comment})
11965 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11966 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11967 @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11969 This macro corresponds to @code{ifelse}. @var{string-1} and
11970 @var{string-2} are compared literally, so usually one of the two
11971 arguments is passed unquoted. @xref{Conditional constructs}, for more
11972 conditional idioms.
11975 @defmac m4_include (@var{file})
11976 @defmacx m4_sinclude (@var{file})
11979 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11982 @defmac m4_mkstemp (@var{template})
11983 @defmacx m4_maketemp (@var{template})
11986 POSIX requires @code{maketemp} to replace the trailing @samp{X}
11987 characters in @var{template} with the process id, without regards to the
11988 existence of a file by that name, but this a security hole. When this
11989 was pointed out to the POSIX folks, they agreed to invent a new macro
11990 @code{mkstemp} that always creates a uniquely named file, but not all
11991 versions of GNU M4 support the new macro. In M4sugar,
11992 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11993 and both have the secure semantics regardless of which macro the
11994 underlying M4 provides.
11997 @defmac m4_popdef (@var{macro}@dots{})
11999 This macro fails if @var{macro} is not defined, even when using older
12000 versions of M4 that did not warn. See @code{m4_undefine}.
12003 @defmac m4_undefine (@var{macro}@dots{})
12005 This macro fails if @var{macro} is not defined, even when using older
12006 versions of M4 that did not warn. Use
12009 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
12013 if you are not sure whether @var{macro} is defined.
12016 @defmac m4_undivert (@var{diversion}@dots{})
12018 Unlike the M4 builtin, at least one @var{diversion} must be specified.
12019 Also, since the M4sugar diversion stack prefers named
12020 diversions, the use of @code{m4_undivert} to include files is risky.
12021 @xref{Diversion support}, for more details about the use of the
12022 diversion stack. But be aware that it is seldom necessary to explicitly
12023 change the diversion stack, and that when done incorrectly, it can lead
12024 to syntactically invalid scripts.
12027 @defmac m4_wrap (@var{text})
12028 @defmacx m4_wrap_lifo (@var{text})
12030 @msindex{wrap_lifo}
12031 These macros correspond to @code{m4wrap}. POSIX requires arguments of
12032 multiple wrap calls to be reprocessed at EOF in the same order
12033 as the original calls (first-in, first-out). GNU M4 versions
12034 through 1.4.10, however, reprocess them in reverse order (last-in,
12035 first-out). Both orders are useful, therefore, you can rely on
12036 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
12037 LIFO semantics, regardless of the underlying GNU M4 version.
12039 Unlike the GNU M4 builtin, these macros only recognize one
12040 argument, and avoid token pasting between consecutive invocations. On
12041 the other hand, nested calls to @code{m4_wrap} from within wrapped text
12042 work just as in the builtin.
12046 @node Diagnostic Macros
12047 @subsection Diagnostic messages from M4sugar
12048 @cindex Messages, from @command{M4sugar}
12050 When macros statically diagnose abnormal situations, benign or fatal,
12051 they should report them using these macros. For issuing dynamic issues,
12052 i.e., when @command{configure} is run, see @ref{Printing Messages}.
12054 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
12056 Assert that the arithmetic @var{expression} evaluates to non-zero.
12057 Otherwise, issue a fatal error, and exit @command{autom4te} with
12061 @defmac m4_errprintn (@var{message})
12062 @msindex{errprintn}
12063 Similar to the builtin @code{m4_errprint}, except that a newline is
12064 guaranteed after @var{message}.
12068 @defmac m4_fatal (@var{message})
12070 Report a severe error @var{message} prefixed with the current location,
12071 and have @command{autom4te} die.
12074 @defmac m4_location
12076 Useful as a prefix in a message line. Short for:
12083 @defmac m4_warn (@var{category}, @var{message})
12085 Report @var{message} as a warning (or as an error if requested by the
12086 user) if warnings of the @var{category} are turned on. If the message
12087 is emitted, it is prefixed with the current location, and followed by a
12088 call trace of all macros defined via @code{AC_DEFUN} used to get to the
12091 The @var{category} must be one of:
12095 Warnings about constructs that may interfere with cross-compilation,
12096 such as using @code{AC_RUN_IFELSE} without a default.
12099 Warnings related to the GNU Coding Standards
12100 (@pxref{Top,,, standards, The GNU Coding Standards}).
12104 Warnings about obsolete features. On by default.
12107 Warnings about redefinitions of Autoconf internals.
12110 Warnings about non-portable constructs.
12112 @item portability-recursive
12113 Warnings about recursive Make variable expansions (@code{$(foo$(x))}).
12115 @item extra-portability
12116 Extra warnings about non-portable constructs, covering rarely-used
12120 Warnings about questionable syntactic constructs, incorrectly ordered
12121 macro calls, typos, etc. On by default.
12124 Warnings about unsupported features. On by default.
12127 @strong{Hacking Note:} The set of categories is defined by code in
12128 @command{autom4te}, not by M4sugar itself. Additions should be
12129 coordinated with Automake, so that both sets of tools accept the same
12133 @node Diversion support
12134 @subsection Diversion support
12136 M4sugar makes heavy use of diversions under the hood, because it is
12137 often the case that
12138 text that must appear early in the output is not discovered until late
12139 in the input. Additionally, some of the topological sorting algorithms
12140 used in resolving macro dependencies use diversions. However, most
12141 macros should not need to change diversions directly, but rather rely on
12142 higher-level M4sugar macros to manage diversions transparently. If you
12143 change diversions improperly, you risk generating a syntactically
12144 invalid script, because an incorrect diversion will violate assumptions
12145 made by many macros about whether prerequisite text has been previously
12146 output. In short, if you manually change the diversion, you should not
12147 expect any macros provided by the Autoconf package to work until you
12148 have restored the diversion stack back to its original state.
12150 In the rare case that it is necessary to write a macro that explicitly
12151 outputs text to a different diversion, it is important to be aware of an
12152 M4 limitation regarding diversions: text only goes to a diversion if it
12153 is not part of argument collection. Therefore, any macro that changes
12154 the current diversion cannot be used as an unquoted argument to another
12155 macro, but must be expanded at the top level. The macro
12156 @code{m4_expand} will diagnose any attempt to change diversions, since
12157 it is generally useful only as an argument to another macro. The
12158 following example shows what happens when diversion manipulation is
12159 attempted within macro arguments:
12162 m4_do([normal text]
12163 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
12164 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
12165 @result{}normal text
12170 Notice that the unquoted text @code{unwanted} is output, even though it
12171 was processed while the current diversion was @code{KILL}, because it
12172 was collected as part of the argument to @code{m4_do}. However, the
12173 text @code{discarded} disappeared as desired, because the diversion
12174 changes were single-quoted, and were not expanded until the top-level
12175 rescan of the output of @code{m4_do}.
12177 To make diversion management easier, M4sugar uses the concept of named
12178 diversions. Rather than using diversion numbers directly, it is nicer
12179 to associate a name with each diversion. The diversion number associated
12180 with a particular diversion name is an implementation detail, and a
12181 syntax warning is issued if a diversion number is used instead of a
12182 name. In general, you should not output text
12183 to a named diversion until after calling the appropriate initialization
12184 routine for your language (@code{m4_init}, @code{AS_INIT},
12185 @code{AT_INIT}, @dots{}), although there are some exceptions documented
12188 M4sugar defines two named diversions.
12191 Text written to this diversion is discarded. This is the default
12192 diversion once M4sugar is initialized.
12194 This diversion is used behind the scenes by topological sorting macros,
12195 such as @code{AC_REQUIRE}.
12198 M4sh adds several more named diversions.
12201 This diversion is reserved for the @samp{#!} interpreter line.
12202 @item HEADER-REVISION
12203 This diversion holds text from @code{AC_REVISION}.
12204 @item HEADER-COMMENT
12205 This diversion holds comments about the purpose of a file.
12206 @item HEADER-COPYRIGHT
12207 This diversion is managed by @code{AC_COPYRIGHT}.
12208 @item M4SH-SANITIZE
12209 This diversion contains M4sh sanitization code, used to ensure M4sh is
12210 executing in a reasonable shell environment.
12212 This diversion contains M4sh initialization code, initializing variables
12213 that are required by other M4sh macros.
12215 This diversion contains the body of the shell code, and is the default
12216 diversion once M4sh is initialized.
12219 Autotest inherits diversions from M4sh, and changes the default
12220 diversion from @code{BODY} back to @code{KILL}. It also adds several
12221 more named diversions, with the following subset designed for developer
12224 @item PREPARE_TESTS
12225 This diversion contains initialization sequences which are executed
12226 after @file{atconfig} and @file{atlocal}, and after all command line
12227 arguments have been parsed, but prior to running any tests. It can be
12228 used to set up state that is required across all tests. This diversion
12229 will work even before @code{AT_INIT}.
12232 Autoconf inherits diversions from M4sh, and adds the following named
12233 diversions which developers can utilize.
12236 This diversion contains shell variable assignments to set defaults that
12237 must be in place before arguments are parsed. This diversion is placed
12238 early enough in @file{configure} that it is unsafe to expand any
12239 autoconf macros into this diversion.
12241 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
12242 diversion will be included as part of a quoted here-doc providing all of
12243 the @option{--help} output of @file{configure} related to options
12244 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
12246 This diversion occurs after all command line options have been parsed,
12247 but prior to the main body of the @file{configure} script. This
12248 diversion is the last chance to insert shell code such as variable
12249 assignments or shell function declarations that will used by the
12250 expansion of other macros.
12253 For now, the remaining named diversions of Autoconf, Autoheader, and
12254 Autotest are not documented. In other words,
12255 intentionally outputting text into an undocumented diversion is subject
12256 to breakage in a future release of Autoconf.
12258 @defmac m4_cleardivert (@var{diversion}@dots{})
12259 @msindex{cleardivert}
12260 Permanently discard any text that has been diverted into
12264 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12265 @msindex{divert_once}
12266 Similar to @code{m4_divert_text}, except that @var{content} is only
12267 output to @var{diversion} if this is the first time that
12268 @code{m4_divert_once} has been called with its particular arguments.
12271 @defmac m4_divert_pop (@ovar{diversion})
12272 @msindex{divert_pop}
12273 If provided, check that the current diversion is indeed @var{diversion}.
12274 Then change to the diversion located earlier on the stack, giving an
12275 error if an attempt is made to pop beyond the initial m4sugar diversion
12279 @defmac m4_divert_push (@var{diversion})
12280 @msindex{divert_push}
12281 Remember the former diversion on the diversion stack, and output
12282 subsequent text into @var{diversion}. M4sugar maintains a diversion
12283 stack, and issues an error if there is not a matching pop for every
12287 @anchor{m4_divert_text}
12288 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12289 @msindex{divert_text}
12290 Output @var{content} and a newline into @var{diversion}, without
12291 affecting the current diversion. Shorthand for:
12293 m4_divert_push([@var{diversion}])@var{content}
12294 m4_divert_pop([@var{diversion}])dnl
12297 One use of @code{m4_divert_text} is to develop two related macros, where
12298 macro @samp{MY_A} does the work, but adjusts what work is performed
12299 based on whether the optional macro @samp{MY_B} has also been expanded.
12300 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12301 require that @samp{MY_B} occurs first, if it occurs at all. But this
12302 imposes an ordering restriction on the user; it would be nicer if macros
12303 @samp{MY_A} and @samp{MY_B} can be invoked in either order. The trick
12304 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12305 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12311 if test -n "$b_was_used"; then
12315 [AC_REQUIRE([MY_A])dnl
12316 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12323 Initialize the M4sugar environment, setting up the default named
12324 diversion to be @code{KILL}.
12327 @node Conditional constructs
12328 @subsection Conditional constructs
12330 The following macros provide additional conditional constructs as
12331 convenience wrappers around @code{m4_if}.
12333 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12334 @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12336 The string @var{string} is repeatedly compared against a series of
12337 @var{regex} arguments; if a match is found, the expansion is the
12338 corresponding @var{value}, otherwise, the macro moves on to the next
12339 @var{regex}. If no @var{regex} match, then the result is the optional
12340 @var{default}, or nothing.
12343 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12344 @ovar{regex-2}, @ovar{subst-2}, @dots{})
12345 @msindex{bpatsubsts}
12346 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12349 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12353 The result of the substitution is then passed through the next set of
12354 @var{regex} and @var{subst}, and so forth. An empty @var{subst} implies
12355 deletion of any matched portions in the current string. Note that this
12356 macro over-quotes @var{string}; this behavior is intentional, so that
12357 the result of each step of the recursion remains as a quoted string.
12358 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12359 will line up with the extra quotations, and not the characters of the
12360 original string. The overquoting is removed after the final
12364 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12365 @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12367 Test @var{string} against multiple @var{value} possibilities, resulting
12368 in the first @var{if-value} for a match, or in the optional
12369 @var{default}. This is shorthand for:
12371 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12372 [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12377 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12378 @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12380 This macro was introduced in Autoconf 2.62. Similar to @code{m4_if},
12381 except that each @var{test} is expanded only when it is encountered.
12382 This is useful for short-circuiting expensive tests; while @code{m4_if}
12383 requires all its strings to be expanded up front before doing
12384 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12387 For an example, these two sequences give the same result, but in the
12388 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12389 version only expands @code{m4_index} once, instead of five times, for
12390 faster computation if this is a common case for @samp{$1}. Notice that
12391 every third argument is unquoted for @code{m4_if}, and quoted for
12395 m4_if(m4_index([$1], [\]), [-1], [$2],
12396 m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12397 m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12398 m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12399 m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12401 m4_cond([m4_index([$1], [\])], [-1], [$2],
12402 [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12403 [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12404 [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12405 [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12410 @defmac m4_default (@var{expr-1}, @var{expr-2})
12411 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12412 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12413 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12415 @msindex{default_quoted}
12416 @msindex{default_nblank}
12417 @msindex{default_nblank_quoted}
12418 If @var{expr-1} contains text, use it. Otherwise, select @var{expr-2}.
12419 @code{m4_default} expands the result, while @code{m4_default_quoted}
12420 does not. Useful for providing a fixed default if the expression that
12421 results in @var{expr-1} would otherwise be empty. The difference
12422 between @code{m4_default} and @code{m4_default_nblank} is whether an
12423 argument consisting of just blanks (space, tab, newline) is
12424 significant. When using the expanding versions, note that an argument
12425 may contain text but still expand to an empty string.
12428 m4_define([active], [ACTIVE])dnl
12429 m4_define([empty], [])dnl
12430 m4_define([demo1], [m4_default([$1], [$2])])dnl
12431 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12432 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12433 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12434 demo1([active], [default])
12436 demo1([], [active])
12438 demo1([empty], [text])
12440 -demo1([ ], [active])-
12442 demo2([active], [default])
12444 demo2([], [active])
12446 demo2([empty], [text])
12448 -demo2([ ], [active])-
12450 demo3([active], [default])
12452 demo3([], [active])
12454 demo3([empty], [text])
12456 -demo3([ ], [active])-
12458 demo4([active], [default])
12460 demo4([], [active])
12462 demo4([empty], [text])
12464 -demo4([ ], [active])-
12469 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12470 @msindex{define_default}
12471 If @var{macro} does not already have a definition, then define it to
12472 @var{default-definition}.
12475 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12476 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12479 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12480 then expand @var{if-blank}; otherwise, expand @var{if-text}. Two
12481 variants exist, in order to make it easier to select the correct logical
12482 sense when using only two parameters. Note that this is more efficient
12483 than the equivalent behavior of:
12485 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12489 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12491 This is shorthand for:
12493 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12497 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12499 If @var{macro} is undefined, or is defined as the empty string, expand
12500 to @var{if-false}. Otherwise, expands to @var{if-true}. Similar to:
12502 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12505 except that it is not an error if @var{macro} is undefined.
12508 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12510 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12511 @var{if-false}. This is shorthand for:
12513 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12517 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12519 Similar to @code{m4_ifval}, except guarantee that a newline is present
12520 after any non-empty expansion. Often followed by @code{dnl}.
12523 @defmac m4_n (@var{text})
12525 Expand to @var{text}, and add a newline if @var{text} is not empty.
12526 Often followed by @code{dnl}.
12530 @node Looping constructs
12531 @subsection Looping constructs
12533 The following macros are useful in implementing recursive algorithms in
12534 M4, including loop operations. An M4 list is formed by quoting a list
12535 of quoted elements; generally the lists are comma-separated, although
12536 @code{m4_foreach_w} is whitespace-separated. For example, the list
12537 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12538 It is common to see lists with unquoted elements when those elements are
12539 not likely to be macro names, as in @samp{[fputc_unlocked,
12542 Although not generally recommended, it is possible for quoted lists to
12543 have side effects; all side effects are expanded only once, and prior to
12544 visiting any list element. On the other hand, the fact that unquoted
12545 macros are expanded exactly once means that macros without side effects
12546 can be used to generate lists. For example,
12549 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12552 m4_define([list], [[1], [2], [3]])
12554 m4_foreach([i], [list], [i])
12558 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12560 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12561 If there are too few arguments, the empty string is used. For any
12562 @var{n} besides 1, this is more efficient than the similar
12563 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12566 @defmac m4_car (@var{arg}@dots{})
12568 Expands to the quoted first @var{arg}. Can be used with @code{m4_cdr}
12569 to recursively iterate
12570 through a list. Generally, when using quoted lists of quoted elements,
12571 @code{m4_car} should be called without any extra quotes.
12574 @defmac m4_cdr (@var{arg}@dots{})
12576 Expands to a quoted list of all but the first @var{arg}, or the empty
12577 string if there was only one argument. Generally, when using quoted
12578 lists of quoted elements, @code{m4_cdr} should be called without any
12581 For example, this is a simple implementation of @code{m4_map}; note how
12582 each iteration checks for the end of recursion, then merely applies the
12583 first argument to the first element of the list, then repeats with the
12584 rest of the list. (The actual implementation in M4sugar is a bit more
12585 involved, to gain some speed and share code with @code{m4_map_sep}, and
12586 also to avoid expanding side effects in @samp{$2} twice).
12588 m4_define([m4_map], [m4_ifval([$2],
12589 [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12590 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12595 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12598 Loop over the numeric values between @var{first} and @var{last}
12599 including bounds by increments of @var{step}. For each iteration,
12600 expand @var{expression} with the numeric value assigned to @var{var}.
12601 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12602 on the order of the limits. If given, @var{step} has to match this
12603 order. The number of iterations is determined independently from
12604 definition of @var{var}; iteration cannot be short-circuited or
12605 lengthened by modifying @var{var} from within @var{expression}.
12608 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12610 Loop over the comma-separated M4 list @var{list}, assigning each value
12611 to @var{var}, and expand @var{expression}. The following example
12615 m4_foreach([myvar], [[foo], [bar, baz]],
12619 @result{}echo bar, baz
12622 Note that for some forms of @var{expression}, it may be faster to use
12623 @code{m4_map_args}.
12626 @anchor{m4_foreach_w}
12627 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12628 @msindex{foreach_w}
12629 Loop over the white-space-separated list @var{list}, assigning each value
12630 to @var{var}, and expand @var{expression}. If @var{var} is only
12631 referenced once in @var{expression}, it is more efficient to use
12632 @code{m4_map_args_w}.
12634 The deprecated macro @code{AC_FOREACH} is an alias of
12635 @code{m4_foreach_w}.
12638 @defmac m4_map (@var{macro}, @var{list})
12639 @defmacx m4_mapall (@var{macro}, @var{list})
12640 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12641 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12645 @msindex{mapall_sep}
12646 Loop over the comma separated quoted list of argument descriptions in
12647 @var{list}, and invoke @var{macro} with the arguments. An argument
12648 description is in turn a comma-separated quoted list of quoted elements,
12649 suitable for @code{m4_apply}. The macros @code{m4_map} and
12650 @code{m4_map_sep} ignore empty argument descriptions, while
12651 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12652 arguments. The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12653 additionally expand @var{separator} between invocations of @var{macro}.
12655 Note that @var{separator} is expanded, unlike in @code{m4_join}. When
12656 separating output with commas, this means that the map result can be
12657 used as a series of arguments, by using a single-quoted comma as
12658 @var{separator}, or as a single string, by using a double-quoted comma.
12661 m4_map([m4_count], [])
12663 m4_map([ m4_count], [[],
12667 m4_mapall([ m4_count], [[],
12671 m4_map_sep([m4_eval], [,], [[[1+2]],
12674 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12676 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12678 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12680 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12685 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12687 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12688 argument. In the following example, three solutions are presented with
12689 the same expansion; the solution using @code{m4_map_args} is the most
12692 m4_define([active], [ACTIVE])dnl
12693 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12694 @result{} plain active
12695 m4_map([ m4_echo], [[[plain]], [[active]]])
12696 @result{} plain active
12697 m4_map_args([ m4_echo], [plain], [active])
12698 @result{} plain active
12701 In cases where it is useful to operate on additional parameters besides
12702 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12703 to supply the argument currying necessary to generate the desired
12704 argument list. In the following example, @code{list_add_n} is more
12705 efficient than @code{list_add_x}. On the other hand, using
12706 @code{m4_map_args_sep} can be even more efficient.
12709 m4_define([list], [[1], [2], [3]])dnl
12710 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12711 dnl list_add_n(N, ARG...)
12712 dnl Output a list consisting of each ARG added to N
12713 m4_define([list_add_n],
12714 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12715 list_add_n([1], list)
12717 list_add_n([2], list)
12719 m4_define([list_add_x],
12720 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12721 [,add([$1],m4_defn([var]))]))])dnl
12722 list_add_x([1], list)
12727 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12729 @msindex{map_args_pair}
12730 For every pair of arguments @var{arg}, invoke @var{macro} with two
12731 arguments. If there is an odd number of arguments, invoke
12732 @var{macro-end}, which defaults to @var{macro}, with the remaining
12736 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12738 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12739 @result{}, 2, 1, [3]
12740 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12741 @result{}, 2, 1, 4, 3
12745 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12746 @msindex{map_args_sep}
12747 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12748 argument, additionally expanding @var{sep} between arguments. One
12749 common use of this macro is constructing a macro call, where the opening
12750 and closing parentheses are split between @var{pre} and @var{post}; in
12751 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12752 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}. This
12753 macro provides the most efficient means for iterating over an arbitrary
12754 list of arguments, particularly when repeatedly constructing a macro
12755 call with more arguments than @var{arg}.
12758 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12759 @msindex{map_args_w}
12760 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12761 the whitespace-separated @var{string}, additionally expanding @var{sep}
12762 between words. This macro provides the most efficient means for
12763 iterating over a whitespace-separated string. In particular,
12764 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12765 efficient than @code{m4_foreach_w([var], [@var{string}],
12766 [@var{action}(m4_defn([var]))])}.
12769 @defmac m4_shiftn (@var{count}, @dots{})
12770 @defmacx m4_shift2 (@dots{})
12771 @defmacx m4_shift3 (@dots{})
12775 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12776 along with validation that enough arguments were passed in to match the
12777 shift count, and that the count is positive. @code{m4_shift2} and
12778 @code{m4_shift3} are specializations
12779 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12780 for two and three shifts, respectively.
12783 @defmac m4_stack_foreach (@var{macro}, @var{action})
12784 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12785 @msindex{stack_foreach}
12786 @msindex{stack_foreach_lifo}
12787 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12788 @var{action} with the single argument of a definition of @var{macro}.
12789 @code{m4_stack_foreach} starts with the oldest definition, while
12790 @code{m4_stack_foreach_lifo} starts with the current definition.
12791 @var{action} should not push or pop definitions of @var{macro}, nor is
12792 there any guarantee that the current definition of @var{macro} matches
12793 the argument that was passed to @var{action}. The macro @code{m4_curry}
12794 can be used if @var{action} needs more than one argument, although in
12795 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12797 Due to technical limitations, there are a few low-level m4sugar
12798 functions, such as @code{m4_pushdef}, that cannot be used as the
12799 @var{macro} argument.
12802 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12803 m4_stack_foreach([a], [ m4_incr])
12805 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12810 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12811 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12813 @msindex{stack_foreach_sep}
12814 @msindex{stack_foreach_sep_lifo}
12815 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12816 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12817 @var{sep} between definitions. @code{m4_stack_foreach_sep} visits the
12818 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12819 the current definition first. This macro provides the most efficient
12820 means for iterating over a pushdef stack. In particular,
12821 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12822 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12825 @node Evaluation Macros
12826 @subsection Evaluation Macros
12828 The following macros give some control over the order of the evaluation
12829 by adding or removing levels of quotes.
12831 @defmac m4_apply (@var{macro}, @var{list})
12833 Apply the elements of the quoted, comma-separated @var{list} as the
12834 arguments to @var{macro}. If @var{list} is empty, invoke @var{macro}
12835 without arguments. Note the difference between @code{m4_indir}, which
12836 expects its first argument to be a macro name but can use names that are
12837 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12838 other text, but must end in a valid macro name.
12840 m4_apply([m4_count], [])
12842 m4_apply([m4_count], [[]])
12844 m4_apply([m4_count], [[1], [2]])
12846 m4_apply([m4_join], [[|], [1], [2]])
12851 @defmac m4_count (@var{arg}, @dots{})
12853 This macro returns the number of arguments it was passed.
12856 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12858 This macro performs argument currying. The expansion of this macro is
12859 another macro name that expects exactly one argument; that argument is
12860 then appended to the @var{arg} list, and then @var{macro} is expanded
12861 with the resulting argument list.
12864 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12868 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12869 pass the definition of a builtin macro as the argument to the output of
12870 @code{m4_curry}; the empty string is used instead of the builtin token.
12871 This behavior is rectified by using M4 1.6 or newer.
12874 @defmac m4_do (@var{arg}, @dots{})
12876 This macro loops over its arguments and expands each @var{arg} in
12877 sequence. Its main use is for readability; it allows the use of
12878 indentation and fewer @code{dnl} to result in the same expansion. This
12879 macro guarantees that no expansion will be concatenated with subsequent
12880 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12881 @var{arg@dots{}}))}.
12884 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12887 m4_unquote(m4_join([],[a],[b]))c
12889 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12890 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12893 m4_unquote(m4_join([],[a],[b]))c
12898 @defmac m4_dquote (@var{arg}, @dots{})
12900 Return the arguments as a quoted list of quoted arguments.
12901 Conveniently, if there is just one @var{arg}, this effectively adds a
12905 @defmac m4_dquote_elt (@var{arg}, @dots{})
12906 @msindex{dquote_elt}
12907 Return the arguments as a series of double-quoted arguments. Whereas
12908 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12909 as many arguments as it was passed.
12912 @defmac m4_echo (@var{arg}, @dots{})
12914 Return the arguments, with the same level of quoting. Other than
12915 discarding whitespace after unquoted commas, this macro is a no-op.
12918 @defmac m4_expand (@var{arg})
12920 Return the expansion of @var{arg} as a quoted string. Whereas
12921 @code{m4_quote} is designed to collect expanded text into a single
12922 argument, @code{m4_expand} is designed to perform one level of expansion
12923 on quoted text. One distinction is in the treatment of whitespace
12924 following a comma in the original @var{arg}. Any time multiple
12925 arguments are collected into one with @code{m4_quote}, the M4 argument
12926 collection rules discard the whitespace. However, with @code{m4_expand},
12927 whitespace is preserved, even after the expansion of macros contained in
12928 @var{arg}. Additionally, @code{m4_expand} is able to expand text that
12929 would involve an unterminated comment, whereas expanding that same text
12930 as the argument to @code{m4_quote} runs into difficulty in finding the
12931 end of the argument. Since manipulating diversions during argument
12932 collection is inherently unsafe, @code{m4_expand} issues an error if
12933 @var{arg} attempts to change the current diversion (@pxref{Diversion
12937 m4_define([active], [ACT, IVE])dnl
12938 m4_define([active2], [[ACT, IVE]])dnl
12939 m4_quote(active, active)
12940 @result{}ACT,IVE,ACT,IVE
12941 m4_expand([active, active])
12942 @result{}ACT, IVE, ACT, IVE
12943 m4_quote(active2, active2)
12944 @result{}ACT, IVE,ACT, IVE
12945 m4_expand([active2, active2])
12946 @result{}ACT, IVE, ACT, IVE
12947 m4_expand([# m4_echo])
12949 m4_quote(# m4_echo)
12951 @result{}# m4_echo)
12955 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12956 literal unbalanced quotes, but that quadrigraphs can be used when
12957 unbalanced output is necessary. Likewise, unbalanced parentheses should
12958 be supplied with double quoting or a quadrigraph.
12961 m4_define([pattern], [[!@@<:@@]])dnl
12962 m4_define([bar], [BAR])dnl
12963 m4_expand([case $foo in
12964 m4_defn([pattern])@@:@}@@ bar ;;
12967 @result{}case $foo in
12968 @result{} [![]) BAR ;;
12969 @result{} *) blah ;;
12974 @defmac m4_ignore (@dots{})
12976 This macro was introduced in Autoconf 2.62. Expands to nothing,
12977 ignoring all of its arguments. By itself, this isn't very useful.
12978 However, it can be used to conditionally ignore an arbitrary number of
12979 arguments, by deciding which macro name to apply to a list of arguments.
12981 dnl foo outputs a message only if [debug] is defined.
12983 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12986 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12987 serve the same purpose, although it is less readable.
12990 @defmac m4_make_list (@var{arg}, @dots{})
12991 @msindex{make_list}
12992 This macro exists to aid debugging of M4sugar algorithms. Its net
12993 effect is similar to @code{m4_dquote}---it produces a quoted list of
12994 quoted arguments, for each @var{arg}. The difference is that this
12995 version uses a comma-newline separator instead of just comma, to improve
12996 readability of the list; with the result that it is less efficient than
12999 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
13000 m4_dquote(zero, [one], [[two]])
13001 @result{}[0],[one],[[two]]
13002 m4_make_list(zero, [one], [[two]])
13006 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
13008 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
13013 @c m4_noquote is too dangerous to document - it invokes macros that
13014 @c probably rely on @samp{[]} nested quoting for proper operation. The
13015 @c user should generally prefer m4_unquote instead.
13017 @defmac m4_quote (@var{arg}, @dots{})
13019 Return the arguments as a single entity, i.e., wrap them into a pair of
13020 quotes. This effectively collapses multiple arguments into one,
13021 although it loses whitespace after unquoted commas in the process.
13024 @defmac m4_reverse (@var{arg}, @dots{})
13026 Outputs each argument with the same level of quoting, but in reverse
13027 order, and with space following each comma for readability.
13030 m4_define([active], [ACT,IVE])
13032 m4_reverse(active, [active])
13033 @result{}active, IVE, ACT
13037 @defmac m4_unquote (@var{arg}, @dots{})
13039 This macro was introduced in Autoconf 2.62. Expand each argument,
13040 separated by commas. For a single @var{arg}, this effectively removes a
13041 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
13042 than the equivalent @code{m4_do([@var{arg}])}. For multiple arguments,
13043 this results in an unquoted list of expansions. This is commonly used
13044 with @code{m4_split}, in order to convert a single quoted list into a
13045 series of quoted elements.
13048 The following example aims at emphasizing the difference between several
13049 scenarios: not using these macros, using @code{m4_defn}, using
13050 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
13053 $ @kbd{cat example.m4}
13054 dnl Overquote, so that quotes are visible.
13055 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
13056 m4_define([a], [A])
13057 m4_define([mkargs], [1, 2[,] 3])
13058 m4_define([arg1], [[$1]])
13062 show(m4_quote(a, b))
13063 show(m4_dquote(a, b))
13064 show(m4_expand([a, b]))
13068 arg1(m4_defn([mkargs]))
13069 arg1(m4_quote(mkargs))
13070 arg1(m4_dquote(mkargs))
13071 arg1(m4_expand([mkargs]))
13072 $ @kbd{autom4te -l m4sugar example.m4}
13073 $1 = A, $@@ = [A],[b]
13074 $1 = a, b, $@@ = [a, b]
13075 $1 = A,b, $@@ = [A,b]
13076 $1 = [A],[b], $@@ = [[A],[b]]
13077 $1 = A, b, $@@ = [A, b]
13088 @node Text processing Macros
13089 @subsection String manipulation in M4
13091 The following macros may be used to manipulate strings in M4. Many of
13092 the macros in this section intentionally result in quoted strings as
13093 output, rather than subjecting the arguments to further expansions. As
13094 a result, if you are manipulating text that contains active M4
13095 characters, the arguments are passed with single quoting rather than
13098 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
13099 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
13100 @ovar{if-uniq}, @ovar{if-duplicate})
13102 @msindex{append_uniq}
13103 Redefine @var{macro-name} to its former contents with @var{separator}
13104 and @var{string} added at the end. If @var{macro-name} was undefined
13105 before (but not if it was defined but empty), then no @var{separator} is
13106 added. As of Autoconf 2.62, neither @var{string} nor @var{separator}
13107 are expanded during this macro; instead, they are expanded when
13108 @var{macro-name} is invoked.
13110 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
13111 to grow strings without duplicating substrings. Additionally,
13112 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
13113 @var{if-uniq} is expanded if @var{string} was appended, and
13114 @var{if-duplicate} is expanded if @var{string} was already present.
13115 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
13116 occurs within @var{string}, since that can lead to duplicates.
13118 Note that @code{m4_append} can scale linearly in the length of the final
13119 string, depending on the quality of the underlying M4 implementation,
13120 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
13121 If an algorithm can tolerate duplicates in the final string, use the
13122 former for speed. If duplicates must be avoided, consider using
13123 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
13126 m4_define([active], [ACTIVE])dnl
13127 m4_append([sentence], [This is an])dnl
13128 m4_append([sentence], [ active ])dnl
13129 m4_append([sentence], [symbol.])dnl
13131 @result{}This is an ACTIVE symbol.
13132 m4_undefine([active])dnl
13133 @result{}This is an active symbol.
13134 m4_append_uniq([list], [one], [, ], [new], [existing])
13136 m4_append_uniq([list], [one], [, ], [new], [existing])
13138 m4_append_uniq([list], [two], [, ], [new], [existing])
13140 m4_append_uniq([list], [three], [, ], [new], [existing])
13142 m4_append_uniq([list], [two], [, ], [new], [existing])
13145 @result{}one, two, three
13147 @result{}[one],[two],[three]
13148 m4_append([list2], [one], [[, ]])dnl
13149 m4_append_uniq([list2], [two], [[, ]])dnl
13150 m4_append([list2], [three], [[, ]])dnl
13152 @result{}one, two, three
13154 @result{}[one, two, three]
13158 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
13159 @msindex{append_uniq_w}
13160 This macro was introduced in Autoconf 2.62. It is similar to
13161 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
13162 separated list of words to append, and only appends unique words.
13163 @var{macro-name} is updated with a single space between new words.
13165 m4_append_uniq_w([numbers], [1 1 2])dnl
13166 m4_append_uniq_w([numbers], [ 2 3 ])dnl
13172 @defmac m4_chomp (@var{string})
13173 @defmacx m4_chomp_all (@var{string})
13175 @msindex{chomp_all}
13176 Output @var{string} in quotes, but without a trailing newline. The
13177 macro @code{m4_chomp} is slightly faster, and removes at most one
13178 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
13179 newlines. Unlike @code{m4_flatten}, embedded newlines are left intact,
13180 and backslash does not influence the result.
13183 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
13184 @var{suffix-1}, @ovar{suffix-2}, @dots{})
13186 This macro produces a quoted string containing the pairwise combination
13187 of every element of the quoted, comma-separated @var{prefix-list}, and
13188 every element from the @var{suffix} arguments. Each pairwise
13189 combination is joined with @var{infix} in the middle, and successive
13190 pairs are joined by @var{separator}. No expansion occurs on any of the
13191 arguments. No output occurs if either the @var{prefix} or @var{suffix}
13192 list is empty, but the lists can contain empty elements.
13194 m4_define([a], [oops])dnl
13195 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
13196 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
13197 m4_combine([, ], [[a], [b]], [-])
13199 m4_combine([, ], [[a], [b]], [-], [])
13201 m4_combine([, ], [], [-], [1], [2])
13203 m4_combine([, ], [[]], [-], [1], [2])
13208 @defmac m4_escape (@var{string})
13210 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
13211 within @var{string} into their respective quadrigraphs. The result is
13212 still a quoted string.
13215 @defmac m4_flatten (@var{string})
13217 Flatten @var{string} into a single line. Delete all backslash-newline
13218 pairs, and replace all remaining newlines with a space. The result is
13219 still a quoted string.
13222 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
13223 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
13226 Concatenate each @var{arg}, separated by @var{separator}.
13227 @code{joinall} uses every argument, while @code{join} omits empty
13228 arguments so that there are no back-to-back separators in the output.
13229 The result is a quoted string.
13231 m4_define([active], [ACTIVE])dnl
13232 m4_join([|], [one], [], [active], [two])
13233 @result{}one|active|two
13234 m4_joinall([|], [one], [], [active], [two])
13235 @result{}one||active|two
13238 Note that if all you intend to do is join @var{args} with commas between
13239 them, to form a quoted list suitable for @code{m4_foreach}, it is more
13240 efficient to use @code{m4_dquote}.
13243 @defmac m4_newline (@ovar{text})
13245 This macro was introduced in Autoconf 2.62, and expands to a newline,
13246 followed by any @var{text}.
13247 It is primarily useful for maintaining macro formatting, and ensuring
13248 that M4 does not discard leading whitespace during argument collection.
13251 @defmac m4_normalize (@var{string})
13252 @msindex{normalize}
13253 Remove leading and trailing spaces and tabs, sequences of
13254 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13255 with a single space. This is a combination of @code{m4_flatten} and
13256 @code{m4_strip}. To determine if @var{string} consists only of bytes
13257 that would be removed by @code{m4_normalize}, you can use
13261 @defmac m4_re_escape (@var{string})
13262 @msindex{re_escape}
13263 Backslash-escape all characters in @var{string} that are active in
13267 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13268 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13270 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13271 @samp{]}, while keeping white space at the beginning and at the end.
13272 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13273 If @var{string} is empty, the result is an empty list.
13276 @defmac m4_strip (@var{string})
13278 Strip whitespace from @var{string}. Sequences of spaces and tabs are
13279 reduced to a single space, then leading and trailing spaces are removed.
13280 The result is still a quoted string. Note that this does not interfere
13281 with newlines; if you want newlines stripped as well, consider
13282 @code{m4_flatten}, or do it all at once with @code{m4_normalize}. To
13283 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13286 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13288 Add a text box around @var{message}, using @var{frame} as the border
13289 character above and below the message. The @var{frame} argument must be
13290 a single byte, and does not support quadrigraphs.
13291 The frame correctly accounts for
13292 the subsequent expansion of @var{message}. For example:
13294 m4_define([macro], [abc])dnl
13295 m4_text_box([macro])
13301 The @var{message} must contain balanced quotes and parentheses, although
13302 quadrigraphs can be used to work around this.
13305 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13306 @dvarv{prefix1, prefix}, @dvar{width, 79})
13307 @msindex{text_wrap}
13308 Break @var{string} into a series of whitespace-separated words, then
13309 output those words separated by spaces, and wrapping lines any time the
13310 output would exceed @var{width} columns. If given, @var{prefix1} begins
13311 the first line, and @var{prefix} begins all wrapped lines. If
13312 @var{prefix1} is longer than @var{prefix}, then the first line consists
13313 of just @var{prefix1}. If @var{prefix} is longer than @var{prefix1},
13314 padding is inserted so that the first word of @var{string} begins at the
13315 same indentation as all wrapped lines. Note that using literal tab
13316 characters in any of the arguments will interfere with the calculation
13317 of width. No expansions occur on @var{prefix}, @var{prefix1}, or the
13318 words of @var{string}, although quadrigraphs are recognized.
13322 m4_text_wrap([Short string */], [ ], [/* ], [20])
13323 @result{}/* Short string */
13324 m4_text_wrap([Much longer string */], [ ], [/* ], [20])
13325 @result{}/* Much longer
13326 @result{} string */
13327 m4_text_wrap([Short doc.], [ ], [ --short ], [30])
13328 @result{} --short Short doc.
13329 m4_text_wrap([Short doc.], [ ], [ --too-wide ], [30])
13330 @result{} --too-wide
13331 @result{} Short doc.
13332 m4_text_wrap([Super long documentation.], [ ],
13333 [ --too-wide ], 30)
13334 @result{} --too-wide
13335 @result{} Super long
13336 @result{} documentation.
13340 @defmac m4_tolower (@var{string})
13341 @defmacx m4_toupper (@var{string})
13344 Return @var{string} with letters converted to upper or lower case,
13348 @node Number processing Macros
13349 @subsection Arithmetic computation in M4
13351 The following macros facilitate integer arithmetic operations.
13353 Where a parameter is documented as taking an arithmetic expression, you
13354 can use anything that can be parsed by @code{m4_eval}.
13355 Any other numeric parameter should consist of an optional sign followed
13356 by one or more decimal digits; it is treated as a decimal integer.
13358 Macros that expand to a number do so as either @samp{0}, or an optional
13359 @samp{-} followed by a nonzero decimal digit followed by zero or more
13362 Due to @command{m4} limitations, arithmetic expressions and numeric
13363 parameters should use only numbers that fit into a 32-bit signed
13366 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13368 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13369 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13370 equal, and @samp{1} if @var{expr-1} is larger.
13373 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13375 Compare the two M4 lists consisting of comma-separated arithmetic
13376 expressions, left to right. Expand to @samp{-1} for the first element
13377 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13378 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13379 same values. If one list is shorter than the other, the remaining
13380 elements of the longer list are compared against zero.
13382 m4_list_cmp([1, 0], [1])
13384 m4_list_cmp([1, [1 * 0]], [1, 0])
13386 m4_list_cmp([1, 2], [1, 0])
13388 m4_list_cmp([1, [1+1], 3],[1, 2])
13390 m4_list_cmp([1, 2, -3], [1, 2])
13392 m4_list_cmp([1, 0], [1, 2])
13394 m4_list_cmp([1], [1, 2])
13399 @defmac m4_max (@var{arg}, @dots{})
13401 This macro was introduced in Autoconf 2.62. Expand to the value
13402 of the maximum arithmetic expression among all the arguments.
13405 @defmac m4_min (@var{arg}, @dots{})
13407 This macro was introduced in Autoconf 2.62. Expand to the value
13408 of the minimum arithmetic expression among all the arguments.
13411 @defmac m4_sign (@var{expr})
13413 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13414 @samp{1} if it is positive, and @samp{0} if it is zero.
13417 @anchor{m4_version_compare}
13418 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13419 @msindex{version_compare}
13420 This macro was introduced in Autoconf 2.53, but had a number of
13421 usability limitations that were not lifted until Autoconf 2.62. Compare
13422 the version strings @var{version-1} and @var{version-2}, and expand to
13423 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13424 or @samp{1} @var{version-2} is smaller. Version strings must be a list
13425 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13426 element is a number along with optional case-insensitive letters
13427 designating beta releases. The comparison stops at the leftmost element
13428 that contains a difference, although a 0 element compares equal to a
13431 It is permissible to include commit identifiers in @var{version}, such
13432 as an abbreviated SHA1 of the commit, provided there is still a
13433 monotonically increasing prefix to allow for accurate version-based
13434 comparisons. For example, this paragraph was written when the
13435 development snapshot of autoconf claimed to be at version
13436 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13437 abbreviated commit identification of @samp{dc51}.
13440 m4_version_compare([1.1], [2.0])
13442 m4_version_compare([2.0b], [2.0a])
13444 m4_version_compare([1.1.1], [1.1.1a])
13446 m4_version_compare([1.2], [1.1.1a])
13448 m4_version_compare([1.0], [1])
13450 m4_version_compare([1.1pre], [1.1PRE])
13452 m4_version_compare([1.1a], [1,10])
13454 m4_version_compare([2.61a], [2.61a-248-dc51])
13456 m4_version_compare([2.61b], [2.61a-248-dc51])
13461 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13462 @dvar{if-old, m4_fatal})
13463 @msindex{version_prereq}
13464 Compares @var{version} against the version of Autoconf currently
13465 running. If the running version is at @var{version} or newer, expand
13466 @var{if-new-enough}, but if @var{version} is larger than the version
13467 currently executing, expand @var{if-old}, which defaults to printing an
13468 error message and exiting m4sugar with status 63. When given only one
13469 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13470 Remember that the autoconf philosophy favors feature checks over version
13474 @node Set manipulation Macros
13475 @subsection Set manipulation in M4
13476 @cindex Set manipulation
13477 @cindex Data structure, set
13478 @cindex Unordered set manipulation
13480 Sometimes, it is necessary to track a set of data, where the order does
13481 not matter and where there are no duplicates in the set. The following
13482 macros facilitate set manipulations. Each set is an opaque object,
13483 which can only be accessed via these basic operations. The underlying
13484 implementation guarantees linear scaling for set creation, which is more
13485 efficient than using the quadratic @code{m4_append_uniq}. Both set
13486 names and values can be arbitrary strings, except for unbalanced quotes.
13487 This implementation ties up memory for removed elements until the next
13488 operation that must traverse all the elements of a set; and although
13489 that may slow down some operations until the memory for removed elements
13490 is pruned, it still guarantees linear performance.
13492 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13494 Adds the string @var{value} as a member of set @var{set}. Expand
13495 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13496 previously in the set. Operates in amortized constant time, so that set
13497 creation scales linearly.
13500 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13501 @msindex{set_add_all}
13502 Adds each @var{value} to the set @var{set}. This is slightly more
13503 efficient than repeatedly invoking @code{m4_set_add}.
13506 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13508 @msindex{set_contains}
13509 Expands @var{if-present} if the string @var{value} is a member of
13510 @var{set}, otherwise @var{if-absent}.
13513 m4_set_contains([a], [1], [yes], [no])
13515 m4_set_add([a], [1], [added], [dup])
13517 m4_set_add([a], [1], [added], [dup])
13519 m4_set_contains([a], [1], [yes], [no])
13521 m4_set_remove([a], [1], [removed], [missing])
13523 m4_set_contains([a], [1], [yes], [no])
13525 m4_set_remove([a], [1], [removed], [missing])
13530 @defmac m4_set_contents (@var{set}, @ovar{sep})
13531 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13532 @msindex{set_contents}
13534 Expands to a single string consisting of all the members of the set
13535 @var{set}, each separated by @var{sep}, which is not expanded.
13536 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13537 memory occupied by removed elements, while @code{m4_set_dump} is a
13538 faster one-shot action that also deletes the set. No provision is made
13539 for disambiguating members that contain a non-empty @var{sep} as a
13540 substring; use @code{m4_set_empty} to distinguish between an empty set
13541 and the set containing only the empty string. The order of the output
13542 is unspecified; in the current implementation, part of the speed of
13543 @code{m4_set_dump} results from using a different output order than
13544 @code{m4_set_contents}. These macros scale linearly in the size of the
13545 set before memory pruning, and @code{m4_set_contents([@var{set}],
13546 [@var{sep}])} is faster than
13547 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13550 m4_set_add_all([a], [1], [2], [3])
13552 m4_set_contents([a], [-])
13554 m4_joinall([-]m4_set_listc([a]))
13556 m4_set_dump([a], [-])
13558 m4_set_contents([a])
13560 m4_set_add([a], [])
13562 m4_set_contents([a], [-])
13567 @defmac m4_set_delete (@var{set})
13568 @msindex{set_delete}
13569 Delete all elements and memory associated with @var{set}. This is
13570 linear in the set size, and faster than removing one element at a time.
13573 @defmac m4_set_difference (@var{seta}, @var{setb})
13574 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13575 @defmacx m4_set_union (@var{seta}, @var{setb})
13576 @msindex{set_difference}
13577 @msindex{set_intersection}
13578 @msindex{set_union}
13579 Compute the relation between @var{seta} and @var{setb}, and output the
13580 result as a list of quoted arguments without duplicates and with a
13581 leading comma. Set difference selects the elements in @var{seta} but
13582 not @var{setb}, intersection selects only elements in both sets, and
13583 union selects elements in either set. These actions are linear in the
13584 sum of the set sizes. The leading comma is necessary to distinguish
13585 between no elements and the empty string as the only element.
13588 m4_set_add_all([a], [1], [2], [3])
13590 m4_set_add_all([b], [3], [], [4])
13592 m4_set_difference([a], [b])
13594 m4_set_difference([b], [a])
13596 m4_set_intersection([a], [b])
13598 m4_set_union([a], [b])
13603 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13604 @msindex{set_empty}
13605 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13606 expand @var{if-elements}. This macro operates in constant time. Using
13607 this macro can help disambiguate output from @code{m4_set_contents} or
13608 @code{m4_set_list}.
13611 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13612 @msindex{set_foreach}
13613 For each element in the set @var{set}, expand @var{action} with the
13614 macro @var{variable} defined as the set element. Behavior is
13615 unspecified if @var{action} recursively lists the contents of @var{set}
13616 (although listing other sets is acceptable), or if it modifies the set
13617 in any way other than removing the element currently contained in
13618 @var{variable}. This macro is faster than the corresponding
13619 @code{m4_foreach([@var{variable}],
13620 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13621 although @code{m4_set_map} might be faster still.
13624 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13626 m4_set_contents([a])
13628 m4_set_foreach([a], [i],
13629 [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13631 m4_set_contents([a])
13636 @defmac m4_set_list (@var{set})
13637 @defmacx m4_set_listc (@var{set})
13639 @msindex{set_listc}
13640 Produce a list of arguments, where each argument is a quoted element
13641 from the set @var{set}. The variant @code{m4_set_listc} is unambiguous,
13642 by adding a leading comma if there are any set elements, whereas the
13643 variant @code{m4_set_list} cannot distinguish between an empty set and a
13644 set containing only the empty string. These can be directly used in
13645 macros that take multiple arguments, such as @code{m4_join} or
13646 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13647 take a quoted list, such as @code{m4_map} or @code{m4_foreach}. Any
13648 memory occupied by removed elements is reclaimed during these macros.
13651 m4_set_add_all([a], [1], [2], [3])
13659 m4_count(m4_set_list([b]))
13661 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13663 m4_set_add([b], [])
13669 m4_count(m4_set_list([b]))
13671 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13676 @defmac m4_set_map (@var{set}, @var{action})
13678 For each element in the set @var{set}, expand @var{action} with a single
13679 argument of the set element. Behavior is unspecified if @var{action}
13680 recursively lists the contents of @var{set} (although listing other sets
13681 is acceptable), or if it modifies the set in any way other than removing
13682 the element passed as an argument. This macro is faster than either
13683 corresponding counterpart of
13684 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13685 @code{m4_set_foreach([@var{set}], [var],
13686 [@var{action}(m4_defn([var]))])}. It is possible to use @code{m4_curry}
13687 if more than one argument is needed for @var{action}, although it is
13688 more efficient to use @code{m4_set_map_sep} in that case.
13691 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13692 @msindex{set_map_sep}
13693 For each element in the set @var{set}, expand
13694 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13695 between elements. Behavior is unspecified if the expansion recursively
13696 lists the contents of @var{set} (although listing other sets
13697 is acceptable), or if it modifies the set in any way other than removing
13698 the element visited by the expansion. This macro provides the most
13699 efficient means for non-destructively visiting the elements of a set; in
13700 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13701 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13704 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13706 @msindex{set_remove}
13707 If @var{value} is an element in the set @var{set}, then remove it and
13708 expand @var{if-present}. Otherwise expand @var{if-absent}. This macro
13709 operates in constant time so that multiple removals will scale linearly
13710 rather than quadratically; but when used outside of
13711 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13712 until the set is later
13713 compacted by @code{m4_set_contents} or @code{m4_set_list}. Several
13714 other set operations are then less efficient between the time of element
13715 removal and subsequent memory compaction, but still maintain their
13716 guaranteed scaling performance.
13719 @defmac m4_set_size (@var{set})
13721 Expand to the size of the set @var{set}. This implementation operates
13722 in constant time, and is thus more efficient than
13723 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13727 @node Forbidden Patterns
13728 @subsection Forbidden Patterns
13729 @cindex Forbidden patterns
13730 @cindex Patterns, forbidden
13732 M4sugar provides a means to define suspicious patterns, patterns
13733 describing tokens which should not be found in the output. For
13734 instance, if an Autoconf @file{configure} script includes tokens such as
13735 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13736 wrong (typically a macro was not evaluated because of overquotation).
13738 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13739 Additional layers, such as M4sh and Autoconf, add additional forbidden
13740 patterns to the list.
13742 @defmac m4_pattern_forbid (@var{pattern})
13743 @msindex{pattern_forbid}
13744 Declare that no token matching @var{pattern} must be found in the
13745 output. The output file is (temporarily) split into one word per line
13746 as part of the @command{autom4te} post-processing, with each line (and
13747 therefore word) then being checked against the Perl regular expression
13748 @var{pattern}. If the regular expression matches, and
13749 @code{m4_pattern_allow} does not also match, then an error is raised.
13751 Comments are not checked; this can be a problem if, for instance, you
13752 have some macro left unexpanded after an @samp{#include}. No consensus
13753 is currently found in the Autoconf community, as some people consider it
13754 should be valid to name macros in comments (which doesn't make sense to
13755 the authors of this documentation: input, such as macros, should be
13756 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13757 document the output).
13759 As an example, if you define your own macros that begin with @samp{M_}
13760 and are composed from capital letters and underscores, the specification
13761 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13762 are expanded when not used in comments.
13764 As an example of a common use of this macro, consider what happens in
13765 packages that want to use the @command{pkg-config} script via the
13766 third-party @code{PKG_CHECK_MODULES} macro. By default, if a developer
13767 checks out the development tree but has not yet installed the pkg-config
13768 macros locally, they can manage to successfully run @command{autoconf}
13769 on the package, but the resulting @file{configure} file will likely
13770 result in a confusing shell message about a syntax error on the line
13771 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro. On the other hand,
13772 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13773 missing pkg-config macros will be detected immediately without allowing
13774 @command{autoconf} to succeed.
13777 Of course, you might encounter exceptions to these generic rules, for
13778 instance you might have to refer to @samp{$m4_flags}.
13780 @defmac m4_pattern_allow (@var{pattern})
13781 @msindex{pattern_allow}
13782 Any token matching @var{pattern} is allowed, including if it matches an
13783 @code{m4_pattern_forbid} pattern.
13785 For example, Gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13786 @code{gl_} namespace for itself, but also uses
13787 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13791 @node Debugging via autom4te
13792 @section Debugging via autom4te
13793 @cindex debugging tips
13794 @cindex autom4te debugging tips
13795 @cindex m4sugar debugging tips
13796 At times, it is desirable to see what was happening inside m4, to see
13797 why output was not matching expectations. However, post-processing done
13798 by @command{autom4te} means that directly using the m4 builtin
13799 @code{m4_traceon} is likely to interfere with operation. Also, frequent
13800 diversion changes and the concept of forbidden tokens make it difficult
13801 to use @code{m4_defn} to generate inline comments in the final output.
13803 There are a couple of tools to help with this. One is the use of the
13804 @option{--trace} option provided by @command{autom4te} (as well as each
13805 of the programs that wrap @command{autom4te}, such as
13806 @command{autoconf}), in order to inspect when a macro is called and with
13807 which arguments. For example, when this paragraph was written, the
13808 autoconf version could be found by:
13811 $ @kbd{autoconf --trace=AC_INIT}
13812 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13813 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13814 version is 2.63b.95-3963
13817 Another trick is to print out the expansion of various m4 expressions to
13818 standard error or to an independent file, with no further m4 expansion,
13819 and without interfering with diversion changes or the post-processing
13820 done to standard output. @code{m4_errprintn} shows a given expression
13821 on standard error. For example, if you want to see the expansion of an
13822 autoconf primitive or of one of your autoconf macros, you can do it like
13826 $ @kbd{cat <<\EOF > configure.ac}
13828 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13829 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13833 @error{}The definition of AC_DEFINE_UNQUOTED:
13834 @error{}_AC_DEFINE_Q([], $@@)
13837 @node Programming in M4sh
13838 @chapter Programming in M4sh
13840 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13841 scripts. This name was coined by Lars J. Aas, who notes that,
13842 according to the Webster's Revised Unabridged Dictionary (1913):
13845 Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische, mash,
13846 wash, and prob.@: to AS. miscian to mix. See ``Mix''.]
13850 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13854 A mixture of meal or bran and water fed to animals.
13857 A mess; trouble. [Obs.] --Beau.@: & Fl.
13861 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13862 the namespace @samp{^AS_} for M4sh macros. It also reserves the shell
13863 and environment variable namespace @samp{^as_}, and the here-document
13864 delimiter namespace @samp{^_AS[A-Z]} in the output file. You should not
13865 define your own macros or output shell code that conflicts with these
13869 * Common Shell Constructs:: Portability layer for common shell constructs
13870 * Polymorphic Variables:: Support for indirect variable names
13871 * Initialization Macros:: Macros to establish a sane shell environment
13872 * File Descriptor Macros:: File descriptor macros for input and output
13875 @node Common Shell Constructs
13876 @section Common Shell Constructs
13878 M4sh provides portable alternatives for some common shell constructs
13879 that unfortunately are not portable in practice.
13881 @c Deprecated, to be replaced by a better API
13883 @defmac AS_BASENAME (@var{file-name})
13885 Output the non-directory portion of @var{file-name}. For example,
13886 if @code{$file} is @samp{/one/two/three}, the command
13887 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13891 @defmac AS_BOX (@var{text}, @dvar{char, -})
13893 Expand into shell code that will output @var{text} surrounded by a box
13894 with @var{char} in the top and bottom border. @var{text} should not
13895 contain a newline, but may contain shell expansions valid for unquoted
13896 here-documents. @var{char} defaults to @samp{-}, but can be any
13897 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13898 @samp{&}, or @samp{`}. This is useful for outputting a comment box into
13899 log files to separate distinct phases of script operation.
13902 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13903 @dots{}, @ovar{default})
13905 Expand into a shell @samp{case} statement, where @var{word} is matched
13906 against one or more patterns. @var{if-matched} is run if the
13907 corresponding pattern matched @var{word}, else @var{default} is run.
13908 @xref{Prerequisite Macros} for why
13909 this macro should be used instead of plain @samp{case} in code
13910 outside of an @code{AC_DEFUN} macro, when the contents of the
13911 @samp{case} use @code{AC_REQUIRE} directly or indirectly.
13912 @xref{case, , Limitations of Shell Builtins},
13913 for how this macro avoids some portability issues.
13914 @xref{Balancing Parentheses}
13915 for how this macro lets you write code with balanced parentheses
13916 even if your code must run on obsolescent shells.
13919 @c Deprecated, to be replaced by a better API
13920 @defmac AS_DIRNAME (@var{file-name})
13922 Output the directory portion of @var{file-name}. For example,
13923 if @code{$file} is @samp{/one/two/three}, the command
13924 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13926 @code{AS_DIRNAME} was designed long ago when
13927 the @command{dirname} command was not universally supported.
13928 Nowadays one can safely use @code{dir=`dirname -- "$file"`} instead.
13929 This interface may be improved in the future to avoid forks and losing
13933 @defmac AS_ECHO (@var{word})
13935 Emit @var{word} to the standard output, followed by a newline.
13936 The @var{word} must be a single shell word (typically a quoted string).
13937 Output the shell expansion of @var{word} as-is,
13938 even if it starts with @samp{-} or contains @samp{\}.
13939 Redirections can be placed outside the macro invocation.
13941 If the shell variable @var{foo} could contain @samp{\} or leading @samp{-}.
13942 @code{AS_ECHO(["$foo"])} is more portable than @command{echo "$foo"}.
13943 @xref{echo, , Limitations of Shell Builtins}.
13945 Also, @code{AS_ECHO(["$foo"])} is often easier to read than the
13946 @samp{printf '%s\n' "$foo"} that it stands for.
13947 However, because it employs @samp{'} characters,
13948 in contexts where @samp{'} is not allowed
13949 it is better to use @command{printf} directly.
13950 For example, @samp{`eval 'foo=$@{'AS_ESCAPE([[$1]], [`\])'@};printf
13951 "%s\\n" "$foo")'`} would not work if @command{printf} were replaced
13952 with @code{AS_ECHO}.
13956 @defmac AS_ECHO_N (@var{word})
13958 Act like @code{AS_ECHO(@var{word})}, except do not output a following newline.
13961 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13962 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13964 Expands to @var{string}, with any characters in @var{chars} escaped with
13965 a backslash (@samp{\}). @var{chars} should be at most four bytes long,
13966 and only contain characters from the set @samp{`\"$}; however,
13967 characters may be safely listed more than once in @var{chars} for the
13968 sake of syntax highlighting editors. The current implementation expands
13969 @var{string} after adding escapes; if @var{string} contains macro calls
13970 that in turn expand to text needing shell quoting, you can use
13971 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13973 The default for @var{chars} (@samp{\"$`}) is the set of characters
13974 needing escapes when @var{string} will be used literally within double
13975 quotes. One common variant is the set of characters to protect when
13976 @var{string} will be used literally within back-ticks or an unquoted
13977 here-document (@samp{\$`}). Another common variant is @samp{""}, which can
13978 be used to form a double-quoted string containing the same expansions
13979 that would have occurred if @var{string} were expanded in an unquoted
13980 here-document; however, when using this variant, care must be taken that
13981 @var{string} does not use double quotes within complex variable
13982 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13983 with improper escapes.
13985 This macro is often used with @code{AS_ECHO}. For an example, observe
13986 the output generated by the shell code generated from this snippet:
13990 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13991 @result{}"$foo" = "bar"
13992 m4_define([macro], [a, [\b]])
13993 AS_ECHO(["AS_ESCAPE([[macro]])"])
13995 AS_ECHO(["AS_ESCAPE([macro])"])
13997 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
14001 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
14002 @comment the case of @var{string} that does not contain '.
14003 To escape a string that will be placed within single quotes, use:
14006 m4_bpatsubst([[@var{string}]], ['], ['\\''])
14010 @defmac AS_EXECUTABLE_P (@var{file})
14011 @asindex{EXECUTABLE_P}
14012 Emit code to probe whether @var{file} is a regular file with executable
14013 permissions (and not a directory with search permissions). The caller
14014 is responsible for quoting @var{file}.
14017 @defmac AS_EXIT (@dvar{status, $?})
14019 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
14021 works around shells that see the exit status of the command prior to
14022 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
14023 of Shell Builtins}).
14026 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
14028 Run shell code @var{test1}. If @var{test1} exits with a zero status then
14029 run shell code @var{run-if-true1}, else examine further tests. If no test
14030 exits with a zero status, run shell code @var{run-if-false}, with
14031 simplifications if either @var{run-if-true1} or @var{run-if-false}
14032 is empty. For example,
14035 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
14036 [test "x$foo" != xno], [HANDLE_FOO([maybe])],
14037 [echo foo not specified])
14041 ensures any required macros of @code{HANDLE_FOO}
14042 are expanded before the first test.
14044 This macro should be used instead of plain @samp{if} in code
14045 outside of an @code{AC_DEFUN} macro, when the contents of the @samp{if}
14046 use @code{AC_REQUIRE} directly or indirectly (@pxref{Prerequisite Macros}).
14049 @defmac AS_MKDIR_P (@var{file-name})
14051 Make the directory @var{file-name}, including intervening directories
14052 as necessary. This is equivalent to @samp{mkdir -p -- @var{file-name}}.
14053 If creation of @var{file-name} fails, exit the script.
14055 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
14058 @defmac AS_SET_STATUS (@var{status})
14059 @asindex{SET_STATUS}
14060 Emit shell code to set the value of @samp{$?} to @var{status}, as
14061 efficiently as possible. However, this is not guaranteed to abort a
14062 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
14063 Builtins}). This should also be used at the end of a complex shell
14064 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
14068 @defmac AS_TR_CPP (@var{expression})
14070 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
14074 # This outputs "#define HAVE_CHAR_P 1".
14075 # Notice the m4 quoting around #, to prevent an m4 comment
14077 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
14081 @defmac AS_TR_SH (@var{expression})
14083 Transform @var{expression} into shell code that generates a valid shell
14084 variable name. The result is literal when possible at m4 time, but must
14085 be used with @code{eval} if @var{expression} causes shell indirections.
14089 # This outputs "Have it!".
14090 header="sys/some file.h"
14091 eval AS_TR_SH([HAVE_$header])=yes
14092 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
14096 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
14097 @asindex{SET_CATFILE}
14098 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
14099 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
14100 @var{file} is absolute, etc.).
14103 @defmac AS_UNSET (@var{var})
14105 Unsets the shell variable @var{var}, working around bugs in older
14106 shells (@pxref{unset, , Limitations of Shell
14107 Builtins}). @var{var} can be a literal or indirect variable name.
14110 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
14111 @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
14112 @asindex{VERSION_COMPARE}
14113 Compare two strings @var{version-1} and @var{version-2}, possibly
14114 containing shell variables, as version strings, and expand
14115 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
14116 depending upon the result.
14117 The algorithm to compare is similar to the one used by strverscmp in
14118 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
14119 The GNU C Library}).
14122 @node Polymorphic Variables
14123 @section Support for indirect variable names
14124 @cindex variable name indirection
14125 @cindex polymorphic variable name
14126 @cindex indirection, variable name
14128 Often, it is convenient to write a macro that will emit shell code
14129 operating on a shell variable. The simplest case is when the variable
14130 name is known. But a more powerful idiom is writing shell code that can
14131 work through an indirection, where another variable or command
14132 substitution produces the name of the variable to actually manipulate.
14133 M4sh supports the notion of polymorphic shell variables, making it easy
14134 to write a macro that can deal with either literal or indirect variable
14135 names and output shell code appropriate for both use cases. Behavior is
14136 undefined if expansion of an indirect variable does not result in a
14137 literal variable name.
14139 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
14140 @dvarv{if-simple-ref, if-not})
14141 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
14142 @ovar{if-not}, @dvarv{if-simple-ref, if-not})
14143 @asindex{LITERAL_IF}
14144 @asindex{LITERAL_WORD_IF}
14145 If the expansion of @var{expression} is definitely a shell literal,
14146 expand @var{if-literal}. If the expansion of @var{expression} looks
14147 like it might contain shell indirections (such as @code{$var} or
14148 @code{`expr`}), then @var{if-not} is expanded. Sometimes, it is
14149 possible to output optimized code if @var{expression} consists only of
14150 shell variable expansions (such as @code{$@{var@}}), in which case
14151 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
14152 should always be safe. @code{AS_LITERAL_WORD_IF} only expands
14153 @var{if-literal} if @var{expression} looks like a single shell word,
14154 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
14155 in @var{expression}.
14157 In order to reduce the time spent recognizing whether an
14158 @var{expression} qualifies as a literal or a simple indirection, the
14159 implementation is somewhat conservative: @var{expression} must be a
14160 single shell word (possibly after stripping whitespace), consisting only
14161 of bytes that would have the same meaning whether unquoted or enclosed
14162 in double quotes (for example, @samp{a.b} results in @var{if-literal},
14163 even though it is not a valid shell variable name; while both @samp{'a'}
14164 and @samp{[$]} result in @var{if-not}, because they behave differently
14165 than @samp{"'a'"} and @samp{"[$]"}). This macro can be used in contexts
14166 for recognizing portable file names (such as in the implementation of
14167 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
14168 valid variable names (such as in the implementation of @code{AS_TR_SH},
14169 which uses an additional @code{m4_translit} to convert @samp{.} to
14172 This example shows how to read the contents of the shell variable
14173 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}. It
14174 results in a script that will output the line @samp{hello} three times.
14177 AC_DEFUN([MY_ACTION],
14178 [AS_LITERAL_IF([$1],
14179 [AS_ECHO(["$$1"])],
14181 [AS_VAR_COPY([var], [$1])
14182 AS_ECHO(["$var"])],
14183 [AS_ECHO(["$'"$1"\"])])])
14186 MY_ACTION([`echo bar`])
14191 @defmac AS_VAR_APPEND (@var{var}, @var{text})
14192 @asindex{VAR_APPEND}
14193 Emit shell code to append the shell expansion of @var{text} to the end
14194 of the current contents of the polymorphic shell variable @var{var},
14195 taking advantage of shells that provide the @samp{+=} extension for more
14198 For situations where the final contents of @var{var} are relatively
14199 short (less than 256 bytes), it is more efficient to use the simpler
14200 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
14201 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
14202 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}). But in the case
14203 when the script will be repeatedly appending text into @code{var},
14204 issues of scaling start to become apparent. A naive implementation
14205 requires execution time linear to the length of the current contents of
14206 @var{var} as well as the length of @var{text} for a single append, for
14207 an overall quadratic scaling with multiple appends. This macro takes
14208 advantage of shells which provide the extension
14209 @code{@var{var}+=@var{text}}, which can provide amortized constant time
14210 for a single append, for an overall linear scaling with multiple
14211 appends. Note that unlike @code{AS_VAR_SET}, this macro requires that
14212 @var{text} be quoted properly to avoid field splitting and file name
14216 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
14217 @asindex{VAR_ARITH}
14218 Emit shell code to compute the arithmetic expansion of @var{expression},
14219 assigning the result as the contents of the polymorphic shell variable
14220 @var{var}. The code takes advantage of shells that provide @samp{$(())}
14221 for fewer forks, but uses @command{expr} as a fallback. Therefore, the
14222 syntax for a valid @var{expression} is rather limited: all operators
14223 must occur as separate shell arguments and with proper quoting;
14224 the only operators supported are @samp{*}, @samp{/}, @samp{%}, binary
14225 @samp{+}, binary @samp{-}, @samp{>}, @samp{>=}, @samp{<}, @samp{<=},
14226 @samp{!=}, @samp{&}, and @samp{|};
14227 all variables containing numbers must be expanded prior to the computation;
14228 the first shell argument must not start with @samp{-};
14229 and each number must be an optional @samp{-} followed by one or more
14230 decimal digits, where the first digit is nonzero if there is more than
14231 one digit. In the following example, this snippet
14232 will print @samp{(2+3)*4 == 20}.
14236 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
14237 echo "(2+$bar)*4 == $foo"
14241 @defmac AS_VAR_COPY (@var{dest}, @var{source})
14243 Emit shell code to assign the contents of the polymorphic shell variable
14244 @var{source} to the polymorphic shell variable @var{dest}. For example,
14245 executing this M4sh snippet will output @samp{bar hi}:
14249 AS_VAR_COPY([a], [foo])
14250 AS_VAR_COPY([b], [$foo])
14254 When it is necessary to access the contents of an indirect variable
14255 inside a shell double-quoted context, the recommended idiom is to first
14256 copy the contents into a temporary literal shell variable.
14259 for header in stdint_h inttypes_h ; do
14260 AS_VAR_COPY([var], [ac_cv_header_$header])
14261 AS_ECHO(["$header detected: $var"])
14266 @comment AS_VAR_GET is intentionally undocumented; it can't handle
14267 @comment trailing newlines uniformly, and forks too much.
14269 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
14270 @ovar{if-not-equal})
14272 Output a shell conditional statement. If the contents of the
14273 polymorphic shell variable @var{var} match the string @var{word},
14274 execute @var{if-equal}; otherwise execute @var{if-not-equal}. @var{word}
14275 must be a single shell word (typically a quoted string). Avoids
14276 shell bugs if an interrupt signal arrives while a command substitution
14277 in @var{var} is being expanded.
14280 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
14281 @defmacx AS_VAR_POPDEF (@var{m4-name})
14282 @asindex{VAR_PUSHDEF}
14283 @asindex{VAR_POPDEF}
14284 @cindex composing variable names
14285 @cindex variable names, composing
14286 A common M4sh idiom involves composing shell variable names from an m4
14287 argument (for example, writing a macro that uses a cache variable).
14288 @var{value} can be an arbitrary string, which will be transliterated
14289 into a valid shell name by @code{AS_TR_SH}. In order to access the
14290 composed variable name based on @var{value}, it is easier to declare a
14291 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14292 that macro as the argument to subsequent @code{AS_VAR} macros as a
14293 polymorphic variable name, and finally free the temporary macro with
14294 @code{AS_VAR_POPDEF}. These macros are often followed with @code{dnl},
14295 to avoid excess newlines in the output.
14297 Here is an involved example, that shows the power of writing macros that
14298 can handle composed shell variable names:
14301 m4_define([MY_CHECK_HEADER],
14302 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14303 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14304 AS_VAR_POPDEF([my_Header])dnl
14306 MY_CHECK_HEADER([stdint.h])
14307 for header in inttypes.h stdlib.h ; do
14308 MY_CHECK_HEADER([$header])
14313 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14314 variable names. In the first invocation, the m4 argument is
14315 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14316 As a result, the temporary macro @code{my_Header} expands to the literal
14317 shell name @samp{ac_cv_header_stdint_h}. In the second invocation, the
14318 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14319 temporary macro @code{my_Header} expands to the indirect shell name
14320 @samp{$as_my_Header}. During the shell execution of the for loop, when
14321 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14322 contains @samp{ac_cv_header_inttypes_h}. If this script is then run on a
14323 platform where all three headers have been previously detected, the
14324 output of the script will include:
14327 header stdint.h detected
14328 header inttypes.h detected
14329 header stdlib.h detected
14333 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14335 Emit shell code to assign the contents of the polymorphic shell variable
14336 @var{var} to the shell expansion of @var{value}. @var{value} is not
14337 subject to field splitting or file name expansion, so if command
14338 substitution is used, it may be done with @samp{`""`} rather than using
14339 an intermediate variable (@pxref{Shell Substitutions}). However,
14340 @var{value} does undergo rescanning for additional macro names; behavior
14341 is unspecified if late expansion results in any shell meta-characters.
14344 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14345 @asindex{VAR_SET_IF}
14346 Emit a shell conditional statement, which executes @var{if-set} if the
14347 polymorphic shell variable @code{var} is set to any value, and
14348 @var{if-undef} otherwise.
14351 @defmac AS_VAR_TEST_SET (@var{var})
14352 @asindex{VAR_TEST_SET}
14353 Emit a shell statement that results in a successful exit status only if
14354 the polymorphic shell variable @code{var} is set.
14357 @node Initialization Macros
14358 @section Initialization Macros
14360 @defmac AS_BOURNE_COMPATIBLE
14361 @asindex{BOURNE_COMPATIBLE}
14362 Set up the shell to be more compatible with the Bourne shell as
14363 standardized by POSIX, if possible. This may involve setting
14364 environment variables, or setting options, or similar
14365 implementation-specific actions. This macro is deprecated, since
14366 @code{AS_INIT} already invokes it.
14373 Initialize the M4sh environment. This macro calls @code{m4_init}, then
14374 outputs the @code{#! /bin/sh} line, a notice about where the output was
14375 generated from, and code to sanitize the environment for the rest of the
14376 script. Among other initializations, this sets @env{SHELL} to the shell
14377 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14378 ensure the C locale. Finally, it changes the current diversion to
14379 @code{BODY}. @code{AS_INIT} is called automatically by @code{AC_INIT}
14380 and @code{AT_INIT}, so shell code in @file{configure},
14381 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14385 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14386 @asindex{INIT_GENERATED}
14387 Emit shell code to start the creation of a subsidiary shell script in
14388 @var{file}, including changing @var{file} to be executable. This macro
14389 populates the child script with information learned from the parent
14390 (thus, the emitted code is equivalent in effect, but more efficient,
14391 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14392 @code{AS_SHELL_SANITIZE}). If present, @var{comment} is output near the
14393 beginning of the child, prior to the shell initialization code, and is
14394 subject to parameter expansion, command substitution, and backslash
14396 parent script should check the exit status after this macro, in case
14397 @var{file} could not be properly created (for example, if the disk was
14398 full). If successfully created, the parent script can then proceed to
14399 append additional M4sh constructs into the child script.
14401 Note that the child script starts life without a log file open, so if
14402 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14403 must temporarily disable any attempts to use the log file until after
14404 emitting code to open a log within the child. On the other hand, if the
14405 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14406 @samp{1}, then the child script already has code that copies stdout to
14407 that descriptor. Currently, the suggested
14408 idiom for writing a M4sh shell script from within another script is:
14411 AS_INIT_GENERATED([@var{file}], [[# My child script.
14412 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14413 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14414 cat >> "@var{file}" <<\__EOF__
14415 # Code to initialize AS_MESSAGE_LOG_FD
14416 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14421 This, however, may change in the future as the M4sh interface is
14422 stabilized further.
14424 Also, be aware that use of @env{LINENO} within the child script may
14425 report line numbers relative to their location in the parent script,
14426 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14427 unable to locate a shell with working @env{LINENO} support.
14430 @defmac AS_LINENO_PREPARE
14431 @asindex{LINENO_PREPARE}
14433 Find a shell that supports the special variable @env{LINENO}, which
14434 contains the number of the currently executing line. This macro is
14435 automatically invoked by @code{AC_INIT} in configure scripts.
14438 @defmac AS_ME_PREPARE
14439 @asindex{ME_PREPARE}
14440 Set up variable @env{as_me} to be the basename of the currently executing
14441 script. This macro is automatically invoked by @code{AC_INIT} in
14445 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14449 Create, as safely as possible, a temporary sub-directory within
14450 @var{dir} with a name starting with @var{prefix}. @var{prefix} should
14451 be 2--4 characters, to make it slightly easier to identify the owner of
14452 the directory. If @var{dir} is omitted, then the value of @env{TMPDIR}
14453 will be used (defaulting to @samp{/tmp}). On success, the name of the
14454 newly created directory is stored in the shell variable @code{tmp}. On
14455 error, the script is aborted.
14457 Typically, this macro is coupled with some exit traps to delete the created
14458 directory and its contents on exit or interrupt. However, there is a
14459 slight window between when the directory is created and when the name is
14460 actually known to the shell, so an interrupt at the right moment might
14461 leave the temporary directory behind. Hence it is important to use a
14462 @var{prefix} that makes it easier to determine if a leftover temporary
14463 directory from an interrupted script is safe to delete.
14465 If you set @code{TMPDIR=$tmp} after invoking this macro, you should
14466 reset @code{TMPDIR} before deleting the created directory, to avoid
14467 breaking commands that rely on @code{$TMPDIR}.
14469 The use of the output variable @samp{$tmp} rather than something in the
14470 @samp{as_} namespace is historical; it has the unfortunate consequence
14471 that reusing this otherwise common name for any other purpose inside
14472 your script has the potential to break any cleanup traps designed to
14473 remove the temporary directory.
14476 @defmac AS_SHELL_SANITIZE
14477 @asindex{SHELL_SANITIZE}
14478 Initialize the shell suitably for @command{configure} scripts. This has
14479 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14480 environment variables for predictable results from configuration tests.
14481 For example, it sets @env{LC_ALL} to change to the default C locale.
14482 @xref{Special Shell Variables}. This macro is deprecated, since
14483 @code{AS_INIT} already invokes it.
14487 @node File Descriptor Macros
14488 @section File Descriptor Macros
14490 @cindex standard input
14491 @cindex file descriptors
14492 @cindex descriptors
14493 @cindex low-level output
14494 @cindex output, low-level
14496 The following macros define file descriptors used to output messages
14497 (or input values) from @file{configure} scripts.
14501 AS_ECHO(["$wombats found"]) >&AS_MESSAGE_LOG_FD
14502 AS_ECHO_N(['Enter desired kangaroo count: ']) >&AS_MESSAGE_FD
14503 read kangaroos <&AS_ORIGINAL_STDIN_FD
14507 However doing so is seldom needed, because Autoconf provides higher
14508 level macros as described below.
14510 @defmac AS_MESSAGE_FD
14511 @asindex{MESSAGE_FD}
14512 The file descriptor for @samp{checking for...} messages and results.
14513 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14514 clients. However, @code{AC_INIT} shuffles things around to another file
14515 descriptor, in order to allow the @option{-q} option of
14516 @command{configure} to choose whether messages should go to the script's
14517 standard output or be discarded.
14519 If you want to display some messages, consider using one of the printing
14520 macros (@pxref{Printing Messages}) instead. Copies of messages output
14521 via these macros are also recorded in @file{config.log}.
14524 @anchor{AS_MESSAGE_LOG_FD}
14525 @defmac AS_MESSAGE_LOG_FD
14526 @asindex{MESSAGE_LOG_FD}
14527 This must either be empty, or expand to a file descriptor for log
14528 messages. By default, @code{AS_INIT} sets this macro to the empty
14529 string for standalone M4sh clients, thus disabling logging. However,
14530 @code{AC_INIT} shuffles things around so that both @command{configure}
14531 and @command{config.status} use @file{config.log} for log messages.
14532 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14533 Compiler}), redirect all output to this descriptor. You may want to do
14534 so if you develop such a low-level macro.
14537 @defmac AS_ORIGINAL_STDIN_FD
14538 @asindex{ORIGINAL_STDIN_FD}
14539 This must expand to a file descriptor for the original standard input.
14540 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14541 M4sh clients. However, @code{AC_INIT} shuffles things around for
14544 When @command{configure} runs, it may accidentally execute an
14545 interactive command that has the same name as the non-interactive meant
14546 to be used or checked. If the standard input was the terminal, such
14547 interactive programs would cause @command{configure} to stop, pending
14548 some user input. Therefore @command{configure} redirects its standard
14549 input from @file{/dev/null} during its initialization. This is not
14550 normally a problem, since @command{configure} normally does not need
14553 In the extreme case where your @file{configure} script really needs to
14554 obtain some values from the original standard input, you can read them
14555 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14559 @c =================================================== Writing Autoconf Macros.
14561 @node Writing Autoconf Macros
14562 @chapter Writing Autoconf Macros
14564 When you write a feature test that could be applicable to more than one
14565 software package, the best thing to do is encapsulate it in a new macro.
14566 Here are some instructions and guidelines for writing Autoconf macros.
14567 You should also familiarize yourself with M4sugar (@pxref{Programming in M4})
14568 and M4sh (@pxref{Programming in M4sh}).
14571 * Macro Definitions:: Basic format of an Autoconf macro
14572 * Macro Names:: What to call your new macros
14573 * Dependencies Between Macros:: What to do when macros depend on other macros
14574 * Obsoleting Macros:: Warning about old ways of doing things
14575 * Coding Style:: Writing Autoconf macros à la Autoconf
14578 @node Macro Definitions
14579 @section Macro Definitions
14581 @defmac AC_DEFUN (@var{name}, @ovar{body})
14583 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14584 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14585 named @var{name} and with @var{body} as its expansion. In addition to
14586 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14587 constrain the order in which macros are called, while avoiding redundant
14588 output (@pxref{Prerequisite Macros}).
14591 An Autoconf macro definition looks like this:
14594 AC_DEFUN(@var{macro-name}, @var{macro-body})
14597 You can refer to any arguments passed to the macro as @samp{$1},
14598 @samp{$2}, etc. @xref{Definitions, , How to define new macros, m4,
14599 GNU M4}, for more complete information on writing M4 macros.
14601 Most macros fall in one of two general categories. The first category
14602 includes macros which take arguments, in order to generate output
14603 parameterized by those arguments. Macros in this category are designed
14604 to be directly expanded, often multiple times, and should not be used as
14605 the argument to @code{AC_REQUIRE}. The other category includes macros
14606 which are shorthand for a fixed block of text, and therefore do not take
14607 arguments. For this category of macros, directly expanding the macro
14608 multiple times results in redundant output, so it is more common to use
14609 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14610 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14612 Be sure to properly quote both the @var{macro-body} @emph{and} the
14613 @var{macro-name} to avoid any problems if the macro happens to have
14614 been previously defined.
14616 Each macro should have a header comment that gives its prototype, and a
14617 brief description. When arguments have default values, display them in
14618 the prototype. For example:
14621 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14622 # --------------------------------------
14623 m4_define([AC_MSG_ERROR],
14624 [@{ AS_MESSAGE([error: $1], [2])
14625 exit m4_default([$2], [1]); @}])
14628 Comments about the macro should be left in the header comment. Most
14629 other comments make their way into @file{configure}, so just keep
14630 using @samp{#} to introduce comments.
14633 If you have some special comments about pure M4 code, comments
14634 that make no sense in @file{configure} and in the header comment, then
14635 use the builtin @code{dnl}: it causes M4 to discard the text
14636 through the next newline.
14638 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14639 @code{dnl} is more useful to get rid of the newlines following macros
14640 that produce no output, such as @code{AC_REQUIRE}.
14642 Public third-party macros need to use @code{AC_DEFUN}, and not
14643 @code{m4_define}, in order to be found by @command{aclocal}
14644 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14645 Additionally, if it is ever determined that a macro should be made
14646 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14647 in order to have @command{autoupdate} assist the user in choosing a
14648 better alternative, but there is no corresponding way to make
14649 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14651 There is another subtle, but important, difference between using
14652 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14653 @code{AC_REQUIRE}. When writing a file, it is always safe to replace a
14654 block of text with a @code{m4_define} macro that will expand to the same
14655 text. But replacing a block of text with an @code{AC_DEFUN} macro with
14656 the same content does not necessarily give the same results, because it
14657 changes the location where any embedded but unsatisfied
14658 @code{AC_REQUIRE} invocations within the block will be expanded. For an
14659 example of this, see @ref{Expanded Before Required}.
14662 @section Macro Names
14664 All of the public Autoconf macros have all-uppercase names in the
14665 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14666 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14667 internal macros. All shell variables that they use for internal
14668 purposes have mostly-lowercase names starting with @samp{ac_}. Autoconf
14669 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}. During
14670 @command{configure}, files produced by Autoconf make heavy use of the
14671 file system namespace @samp{^conf}.
14673 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14674 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14675 of those namespaces (@samp{^_?\(m4\|AS\)_}). And since
14676 @file{configure.ac} is also designed to be scanned by Autoheader,
14677 Autoscan, Autoupdate, and Automake, you should be aware of the
14678 @samp{^_?A[HNUM]_} namespaces. In general, you @emph{should not use}
14679 the namespace of a package that does not own the macro or shell code you
14682 To ensure that your macros don't conflict with present or future
14683 Autoconf macros, you should prefix your own macro names and any shell
14684 variables they use with some other sequence. Possibilities include your
14685 initials, or an abbreviation for the name of your organization or
14686 software package. Historically, people have not always followed the
14687 rule of using a namespace appropriate for their package, and this has
14688 made it difficult for determining the origin of a macro (and where to
14689 report bugs about that macro), as well as difficult for the true
14690 namespace owner to add new macros without interference from pre-existing
14691 uses of third-party macros. Perhaps the best example of this confusion
14692 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14695 Most of the Autoconf macros' names follow a structured naming convention
14696 that indicates the kind of feature check by the name. The macro names
14697 consist of several words, separated by underscores, going from most
14698 general to most specific. The names of their cache variables use the
14699 same convention (@pxref{Cache Variable Names}, for more information on
14702 The first word of the name after the namespace initials (such as
14703 @samp{AC_}) usually tells the category
14704 of the feature being tested. Here are the categories used in Autoconf for
14705 specific test macros, the kind of macro that you are more likely to
14706 write. They are also used for cache variables, in all-lowercase. Use
14707 them where applicable; where they're not, invent your own categories.
14711 C language builtin features.
14713 Declarations of C variables in header files.
14715 Functions in libraries.
14717 POSIX group owners of files.
14723 The base names of programs.
14725 Members of aggregates.
14727 Operating system features.
14729 C builtin or declared types.
14731 C variables in libraries.
14734 After the category comes the name of the particular feature being
14735 tested. Any further words in the macro name indicate particular aspects
14736 of the feature. For example, @code{AC_PROG_MAKE_SET} checks whether
14737 @command{make} sets a variable to its own name.
14739 An internal macro should have a name that starts with an underscore;
14740 Autoconf internals should therefore start with @samp{_AC_}.
14741 Additionally, a macro that is an internal subroutine of another macro
14742 should have a name that starts with an underscore and the name of that
14743 other macro, followed by one or more words saying what the internal
14744 macro does. For example, @code{AC_PATH_X} has internal macros
14745 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14747 @node Dependencies Between Macros
14748 @section Dependencies Between Macros
14749 @cindex Dependencies between macros
14751 Some Autoconf macros depend on other macros having been called first in
14752 order to work correctly. Autoconf provides a way to ensure that certain
14753 macros are called if needed and a way to warn the user if macros are
14754 called in an order that might cause incorrect operation.
14757 * Prerequisite Macros:: Ensuring required information
14758 * Suggested Ordering:: Warning about possible ordering problems
14759 * One-Shot Macros:: Ensuring a macro is called only once
14762 @node Prerequisite Macros
14763 @subsection Prerequisite Macros
14764 @cindex Prerequisite macros
14765 @cindex Macros, prerequisites
14767 A macro that you write might need to use values that have previously
14768 been computed by other macros. For example, @code{AC_DECL_YYTEXT}
14769 examines the output of @code{flex} or @code{lex}, so it depends on
14770 @code{AC_PROG_LEX} having been called first to set the shell variable
14773 Rather than forcing the user of the macros to keep track of the
14774 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14775 it automatically. @code{AC_REQUIRE} can ensure that a macro is only
14776 called if it is needed, and only called once.
14778 @defmac AC_REQUIRE (@var{macro-name})
14780 If the M4 macro @var{macro-name} has not already been called, call it
14781 (without any arguments). Make sure to quote @var{macro-name} with
14782 square brackets. @var{macro-name} must have been defined using
14783 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14784 that it has been called.
14786 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14787 must not be called from the top level. Also, it does not make sense to
14788 require a macro that takes parameters.
14791 @code{AC_REQUIRE} is often misunderstood. It really implements
14792 dependencies between macros in the sense that if one macro depends upon
14793 another, the latter is expanded @emph{before} the body of the
14794 former. To be more precise, the required macro is expanded before
14795 the outermost defined macro in the current expansion stack.
14796 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14797 @code{FOO}. For instance, this definition of macros:
14801 AC_DEFUN([TRAVOLTA],
14802 [test "$body_temperature_in_Celsius" -gt 38 &&
14803 dance_floor=occupied])
14804 AC_DEFUN([NEWTON_JOHN],
14805 [test "x$hair_style" = xcurly &&
14806 dance_floor=occupied])
14810 AC_DEFUN([RESERVE_DANCE_FLOOR],
14811 [if test "x`date +%A`" = xSaturday; then
14812 AC_REQUIRE([TRAVOLTA])
14813 AC_REQUIRE([NEWTON_JOHN])
14819 with this @file{configure.ac}
14822 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14823 RESERVE_DANCE_FLOOR
14824 if test "x$dance_floor" = xoccupied; then
14825 AC_MSG_ERROR([cannot pick up here, let's move])
14830 does not leave you with a better chance to meet a kindred soul on
14831 days other than Saturday, since the call to @code{RESERVE_DANCE_FLOOR}
14836 test "$body_temperature_in_Celsius" -gt 38 &&
14837 dance_floor=occupied
14838 test "x$hair_style" = xcurly &&
14839 dance_floor=occupied
14840 if test "x`date +%A`" = xSaturday; then
14847 This behavior was chosen on purpose: (i) it prevents messages in
14848 required macros from interrupting the messages in the requiring macros;
14849 (ii) it avoids bad surprises when shell conditionals are used, as in:
14854 AC_REQUIRE([SOME_CHECK])
14861 However, this implementation can lead to another class of problems.
14862 Consider the case where an outer macro first expands, then indirectly
14863 requires, an inner macro:
14866 AC_DEFUN([TESTA], [[echo in A
14867 if test -n "$SEEN_A" ; then echo duplicate ; fi
14869 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14870 if test -z "$SEEN_A" ; then echo bug ; fi]])
14871 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14872 AC_DEFUN([OUTER], [[echo in OUTER]
14879 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14880 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14881 of @code{OUTER}, but because @code{TESTA} had already been directly
14882 expanded, it failed to hoist @code{TESTA}. Therefore, the expansion of
14883 @code{TESTB} occurs prior to its prerequisites, leading to the following
14895 Newer Autoconf is smart enough to recognize this situation, and hoists
14896 @code{TESTA} even though it has already been expanded, but issues a
14897 syntax warning in the process. This is because the hoisted expansion of
14898 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14899 redundant code, and causes its own set of problems if the hoisted macro
14911 The bug is not in Autoconf, but in the macro definitions. If you ever
14912 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14913 that the macro only needs to be expanded once. But to enforce this,
14914 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14915 this only helps in Autoconf 2.64 or newer), or all
14916 uses of that macro should be through @code{AC_REQUIRE}; directly
14917 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14918 eliminate redundant expansion. In the example, this rule of thumb was
14919 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14920 directly expands it. One way of fixing the bug is to factor
14921 @code{TESTA} into two macros, the portion designed for direct and
14922 repeated use (here, named @code{TESTA}), and the portion designed for
14923 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14924 @code{TESTA_PREREQ}). Then, by fixing all clients to use the correct
14925 calling convention according to their needs:
14928 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14929 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14930 if test -n "$SEEN_A" ; then echo duplicate ; fi
14932 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14933 if test -z "$SEEN_A" ; then echo bug ; fi]])
14934 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14935 AC_DEFUN([OUTER], [[echo in OUTER]
14942 the resulting output will then obey all dependency rules and avoid any
14943 syntax warnings, whether the script is built with old or new Autoconf
14954 You can use the helper macros @code{AS_IF} and @code{AS_CASE} in
14955 top-level code to enforce expansion of required macros outside of shell
14956 conditional constructs; these helpers are not needed in the bodies of
14957 macros defined by @code{AC_DEFUN}.
14958 You are furthermore encouraged, although not required, to
14959 put all @code{AC_REQUIRE} calls
14960 at the beginning of a macro. You can use @code{dnl} to avoid the empty
14963 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14964 macro that has not been defined. However, the @command{aclocal} tool
14965 relies on parsing an incomplete set of input files to trace which macros
14966 have been required, in order to then pull in additional files that
14967 provide those macros; for this particular use case, pre-defining the
14968 macro @code{m4_require_silent_probe} will avoid the warnings.
14970 @node Suggested Ordering
14971 @subsection Suggested Ordering
14972 @cindex Macros, ordering
14973 @cindex Ordering macros
14975 Some macros should be run before another macro if both are called, but
14976 neither @emph{requires} that the other be called. For example, a macro
14977 that changes the behavior of the C compiler should be called before any
14978 macros that run the C compiler. Many of these dependencies are noted in
14981 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14982 with this kind of dependency appear out of order in a
14983 @file{configure.ac} file. The warning occurs when creating
14984 @command{configure} from @file{configure.ac}, not when running
14985 @command{configure}.
14987 For example, @code{AC_PROG_CPP} checks whether the C compiler
14988 can run the C preprocessor when given the @option{-E} option. It should
14989 therefore be called after any macros that change which C compiler is
14990 being used, such as @code{AC_PROG_CC}. So @code{AC_PROG_CC} contains:
14993 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14997 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14998 when @code{AC_PROG_CC} is called.
15000 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
15002 Make M4 print a warning message to the standard error output if
15003 @var{called-macro-name} has already been called. @var{this-macro-name}
15004 should be the name of the macro that is calling @code{AC_BEFORE}. The
15005 macro @var{called-macro-name} must have been defined using
15006 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
15007 that it has been called.
15010 @node One-Shot Macros
15011 @subsection One-Shot Macros
15012 @cindex One-shot macros
15013 @cindex Macros, called once
15015 Some macros should be called only once, either because calling them
15016 multiple time is unsafe, or because it is bad style. For instance
15017 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
15018 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
15019 sense to run these expensive checks more than once. Such one-shot
15020 macros can be defined using @code{AC_DEFUN_ONCE}.
15022 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
15023 @acindex{DEFUN_ONCE}
15024 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
15025 Definitions}), but add additional logic that guarantees that only the
15026 first use of the macro (whether by direct expansion or
15027 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
15028 expansion will occur before the start of any enclosing macro defined by
15029 @code{AC_DEFUN}. Subsequent expansions are silently ignored.
15030 Generally, it does not make sense for @var{macro-body} to use parameters
15034 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
15035 emit a warning if it was directly expanded a second time, so for
15036 portability, it is better to use @code{AC_REQUIRE} than direct
15037 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
15038 (@pxref{Prerequisite Macros}).
15040 @node Obsoleting Macros
15041 @section Obsoleting Macros
15042 @cindex Obsoleting macros
15043 @cindex Macros, obsoleting
15045 Configuration and portability technology has evolved over the years.
15046 Often better ways of solving a particular problem are developed, or
15047 ad-hoc approaches are systematized. This process has occurred in many
15048 parts of Autoconf. One result is that some of the macros are now
15049 considered @dfn{obsolete}; they still work, but are no longer considered
15050 the best thing to do, hence they should be replaced with more modern
15051 macros. Ideally, @command{autoupdate} should replace the old macro calls
15052 with their modern implementation.
15054 Autoconf provides a simple means to obsolete a macro.
15057 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message}, @ovar{silent})
15059 Define @var{old-macro} as @var{implementation}, just like
15060 @code{AC_DEFUN}, but also declare @var{old-macro} to be obsolete.
15061 When @command{autoupdate} is run, occurrences of @var{old-macro} will
15062 be replaced by the text of @var{implementation} in the updated
15063 @file{configure.ac} file.
15065 If a simple textual replacement is not enough to finish the job of
15066 updating a @file{configure.ac} to modern style, provide instructions for
15067 whatever additional manual work is required as @var{message}. These
15068 instructions will be printed by @command{autoupdate}, and embedded in the
15069 updated @file{configure.ac} file, next to the text of @var{implementation}.
15071 Normally, @command{autoconf} will also issue a warning (in the
15072 ``obsolete'' category) when it expands @var{old-macro}. This warning
15073 does not include @var{message}; it only advises the maintainer to run
15074 @command{autoupdate}. If it is inappropriate to issue this warning, set
15075 the @var{silent} argument to the word @code{silent}. One might want to
15076 use a silent @code{AU_DEFUN} when @var{old-macro} is used in a
15077 widely-distributed third-party macro. If that macro's maintainers are
15078 aware of the need to update their code, it's unnecessary to nag all
15079 of the transitive users of @var{old-macro} as well. This capability
15080 was added to @code{AU_DEFUN} in Autoconf 2.70; older versions of
15081 autoconf will ignore the @var{silent} argument and issue the warning
15084 @strong{Caution:} If @var{implementation} contains M4 or M4sugar macros,
15085 they will be evaluated when @command{autoupdate} is run, not emitted
15086 verbatim like the rest of @var{implementation}. This cannot be avoided
15087 with extra quotation, because then @var{old-macro} will not work when
15088 it is called normally. See the definition of @code{AC_FOREACH} in
15089 @file{general.m4} for a workaround.
15092 @defmac AU_ALIAS (@var{old-name}, @var{new-name}, @ovar{silent})
15094 A shorthand version of @code{AU_DEFUN}, to be used when a macro has
15095 simply been renamed. @command{autoupdate} will replace calls to
15096 @var{old-name} with calls to @var{new-name}, keeping any arguments
15097 intact. No instructions for additional manual work will be printed.
15099 The @var{silent} argument works the same as the @var{silent} argument
15100 to @code{AU_DEFUN}. It was added to @code{AU_ALIAS} in Autoconf 2.70.
15102 @strong{Caution:} @code{AU_ALIAS} cannot be used when @var{new-name} is
15103 an M4 or M4sugar macro. See above.
15107 @section Coding Style
15108 @cindex Coding style
15110 The Autoconf macros follow a strict coding style. You are encouraged to
15111 follow this style, especially if you intend to distribute your macro,
15112 either by contributing it to Autoconf itself or the
15113 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
15114 Archive}, or by other means.
15116 The first requirement is to pay great attention to the quotation. For
15117 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
15119 Do not try to invent new interfaces. It is likely that there is a macro
15120 in Autoconf that resembles the macro you are defining: try to stick to
15121 this existing interface (order of arguments, default values, etc.). We
15122 @emph{are} conscious that some of these interfaces are not perfect;
15123 nevertheless, when harmless, homogeneity should be preferred over
15126 Be careful about clashes both between M4 symbols and between shell
15129 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
15130 you are unlikely to generate conflicts. Nevertheless, when you need to
15131 set a special value, @emph{avoid using a regular macro name}; rather,
15132 use an ``impossible'' name. For instance, up to version 2.13, the macro
15133 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
15134 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
15135 But since there is a macro named @code{AC_SUBST_FILE}, it was just
15136 impossible to @samp{AC_SUBST(FILE)}! In this case,
15137 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
15138 have been used (yes, with the parentheses).
15139 @c or better yet, high-level macros such as @code{m4_expand_once}
15141 No Autoconf macro should ever enter the user-variable name space; i.e.,
15142 except for the variables that are the actual result of running the
15143 macro, all shell variables should start with @code{ac_}. In
15144 addition, small macros or any macro that is likely to be embedded in
15145 other macros should be careful not to use obvious names.
15148 Do not use @code{dnl} to introduce comments: most of the comments you
15149 are likely to write are either header comments which are not output
15150 anyway, or comments that should make their way into @file{configure}.
15151 There are exceptional cases where you do want to comment special M4
15152 constructs, in which case @code{dnl} is right, but keep in mind that it
15155 M4 ignores the leading blanks and newlines before each argument.
15156 Use this feature to
15157 indent in such a way that arguments are (more or less) aligned with the
15158 opening parenthesis of the macro being called. For instance, instead of
15161 AC_CACHE_CHECK(for EMX OS/2 environment,
15163 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
15164 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
15171 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15172 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15173 [ac_cv_emxos2=yes],
15174 [ac_cv_emxos2=no])])
15181 AC_CACHE_CHECK([for EMX OS/2 environment],
15183 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
15184 [return __EMX__;])],
15185 [ac_cv_emxos2=yes],
15186 [ac_cv_emxos2=no])])
15189 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
15190 cross-compiling, provide a pessimistic value (typically @samp{no}).
15192 Feel free to use various tricks to prevent auxiliary tools, such as
15193 syntax-highlighting editors, from behaving improperly. For instance,
15197 m4_bpatsubst([$1], [$"])
15204 m4_bpatsubst([$1], [$""])
15208 so that Emacsen do not open an endless ``string'' at the first quote.
15209 For the same reasons, avoid:
15219 test $[@@%:@@] != 0
15223 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
15224 breaking the bracket-matching highlighting from Emacsen. Note the
15225 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc. Do
15226 not escape when it is unnecessary. Common examples of useless quotation
15227 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
15230 When using @command{sed}, don't use @option{-e} except for indenting
15231 purposes. With the @code{s} and @code{y} commands, the preferred
15232 separator is @samp{/} unless @samp{/} itself might appear in the pattern
15233 or replacement, in which case you should use @samp{|}, or optionally
15234 @samp{,} if you know the pattern and replacement cannot contain a file
15235 name. If none of these characters will do, choose a printable character
15236 that cannot appear in the pattern or replacement. Characters from the
15237 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
15238 replacement might contain a file name, since they have special meaning
15239 to the shell and are less likely to occur in file names.
15241 @xref{Macro Definitions}, for details on how to define a macro. If a
15242 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
15243 of an @code{AC_REQUIRE} directive, and macros required by other macros
15244 inside arguments do not need to be expanded before this macro, then
15245 use @code{m4_define}. In case of doubt, use @code{AC_DEFUN}.
15246 Also take into account that public third-party macros need to use
15247 @code{AC_DEFUN} in order to be found by @command{aclocal}
15248 (@pxref{Extending aclocal,,, automake, GNU Automake}).
15249 All the @code{AC_REQUIRE} statements should be at the beginning of the
15250 macro, and each statement should be followed by @code{dnl}.
15252 You should not rely on the number of arguments: instead of checking
15253 whether an argument is missing, test that it is not empty. It provides
15254 both a simpler and a more predictable interface to the user, and saves
15255 room for further arguments.
15257 Unless the macro is short, try to leave the closing @samp{])} at the
15258 beginning of a line, followed by a comment that repeats the name of the
15259 macro being defined. This introduces an additional newline in
15260 @command{configure}; normally, that is not a problem, but if you want to
15261 remove it you can use @samp{[]dnl} on the last line. You can similarly
15262 use @samp{[]dnl} after a macro call to remove its newline. @samp{[]dnl}
15263 is recommended instead of @samp{dnl} to ensure that M4 does not
15264 interpret the @samp{dnl} as being attached to the preceding text or
15265 macro output. For example, instead of:
15268 AC_DEFUN([AC_PATH_X],
15269 [AC_MSG_CHECKING([for X])
15271 @r{# @dots{}omitted@dots{}}
15272 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15280 AC_DEFUN([AC_PATH_X],
15281 [AC_REQUIRE_CPP()[]dnl
15282 AC_MSG_CHECKING([for X])
15283 @r{# @dots{}omitted@dots{}}
15284 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15289 If the macro is long, try to split it into logical chunks. Typically,
15290 macros that check for a bug in a function and prepare its
15291 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15292 this setup. Do not hesitate to introduce auxiliary macros to factor
15295 In order to highlight the recommended coding style, here is a macro
15296 written the old way:
15299 dnl Check for EMX on OS/2.
15301 AC_DEFUN(_AC_EMXOS2,
15302 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15303 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15304 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15305 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15314 # Check for EMX on OS/2.
15315 m4_define([_AC_EMXOS2],
15316 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15317 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15318 [ac_cv_emxos2=yes],
15319 [ac_cv_emxos2=no])])
15320 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15327 @c ============================================= Portable Shell Programming
15329 @node Portable Shell
15330 @chapter Portable Shell Programming
15331 @cindex Portable shell programming
15333 When writing your own checks, there are some shell-script programming
15334 techniques you should avoid in order to make your code portable. The
15335 Bourne shell and upward-compatible shells like the Korn shell and Bash
15336 have evolved over the years, and many features added to the original
15337 System7 shell are now supported on all interesting porting targets.
15338 However, the following discussion between Russ Allbery and Robert Lipe
15345 The GNU assumption that @command{/bin/sh} is the one and only shell
15346 leads to a permanent deadlock. Vendors don't want to break users'
15347 existing shell scripts, and there are some corner cases in the Bourne
15348 shell that are not completely compatible with a POSIX shell. Thus,
15349 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15350 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15358 This is exactly the problem. While most (at least most System V's) do
15359 have a Bourne shell that accepts shell functions most vendor
15360 @command{/bin/sh} programs are not the POSIX shell.
15362 So while most modern systems do have a shell @emph{somewhere} that meets the
15363 POSIX standard, the challenge is to find it.
15366 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15367 is to find such a shell. But to prevent trouble, if you're not using
15368 M4sh you should not take advantage of features that were added after Unix
15369 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15370 negated character classes, or even @command{unset}. @code{#} comments,
15371 while not in Unix version 7, were retrofitted in the original Bourne
15372 shell and can be assumed to be part of the least common denominator.
15374 On the other hand, if you're using M4sh you can assume that the shell
15375 has the features that were added in SVR2 (circa 1984), including shell
15377 @command{return}, @command{unset}, and I/O redirection for builtins. For
15378 more information, refer to @uref{https://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15379 However, some pitfalls have to be avoided for portable use of these
15380 constructs; these will be documented in the rest of this chapter.
15381 See in particular @ref{Shell Functions} and @ref{Limitations of
15382 Builtins, , Limitations of Shell Builtins}.
15384 The set of external programs you should run in a @command{configure} script
15385 is fairly small. @xref{Utilities in Makefiles, , Utilities in
15386 Makefiles, standards, The GNU Coding Standards}, for the list. This
15387 restriction allows users to start out with a fairly small set of
15388 programs and build the rest, avoiding too many interdependencies between
15391 Some of these external utilities have a portable subset of features; see
15392 @ref{Limitations of Usual Tools}.
15394 There are other sources of documentation about shells. The
15395 specification for the POSIX
15396 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/V3_chap02.html,
15397 Shell Command Language}, though more generous than the restrictive shell
15398 subset described above, is fairly portable nowadays. Also please see
15399 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15402 * Systemology:: A zoology of operating systems
15403 * Shellology:: A zoology of shells
15404 * Invoking the Shell:: Invoking the shell as a command
15405 * Here-Documents:: Quirks and tricks
15406 * File Descriptors:: FDs and redirections
15407 * Signal Handling:: Shells, signals, and headaches
15408 * File System Conventions:: File names
15409 * Shell Pattern Matching:: Pattern matching
15410 * Shell Substitutions:: Variable and command expansions
15411 * Assignments:: Varying side effects of assignments
15412 * Parentheses:: Parentheses in shell scripts
15413 * Special Shell Variables:: Variables you should not change
15414 * Shell Functions:: What to look out for if you use them
15415 * Limitations of Builtins:: Portable use of not so portable /bin/sh
15416 * Limitations of Usual Tools:: Portable use of portable tools
15421 @section Systemology
15422 @cindex Systemology
15424 This section aims at presenting some systems and pointers to
15425 documentation. It may help you addressing particular problems reported
15428 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX-conforming
15429 systems} are derived from the
15430 @uref{https://@/en.wikipedia.org/@/wiki/@/Unix, Unix operating system}.
15432 The @uref{https://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
15433 contains a table correlating the features of various POSIX-conforming
15434 systems. @uref{https://@/www.levenez.com/@/unix/, Unix History} is a
15435 simplified diagram of how many Unix systems were derived from each
15438 @uref{https://@/heirloom.sourceforge.net/, The Heirloom Project}
15439 provides some variants of traditional implementations of Unix utilities.
15446 Darwin is a partially proprietary operating system maintained by Apple
15447 Computer and used by most of their products. It is also known as macOS,
15448 iOS, etc.@: depending on the exact variant. Older versions were called
15451 By default the file system will be case insensitive, albeit case
15452 preserving. This can cause nasty problems: for instance, the
15453 installation attempt for a package having an @file{INSTALL} file can
15454 result in @samp{make install} reporting that nothing is to be done!
15456 Darwin does support case-sensitive file systems, but they must be
15457 formatted specially as such, and Apple discourages use of a
15458 case-sensitive volume for the base operating system. To build software
15459 that expects case-sensitive filenames, it is best to create a separate
15460 disk volume or disk image formatted as case sensitive; this can be done
15461 using the @command{diskutil} command or the Disk Utility application.
15465 @c FIXME: Please, if you feel like writing something more precise,
15466 @c it'd be great. In particular, I can't understand the difference with
15468 QNX is a realtime operating system running on Intel architecture
15469 meant to be scalable from the small embedded systems to the hundred
15470 processor super-computer. It claims to be POSIX certified. More
15471 information is available on the
15472 @uref{https://@/blackberry.qnx.com/@/en, QNX home page}.
15474 @item Unix version 7
15475 @cindex Unix version 7
15477 Officially this was called the ``Seventh Edition'' of ``the UNIX
15478 time-sharing system'' but we use the more-common name ``Unix version 7''.
15479 Documentation is available in the
15480 @uref{https://@/s3.amazonaws.com/@/plan9-bell-labs/@/7thEdMan/@/index.html,
15481 Unix Seventh Edition Manual}.
15482 Previous versions of Unix are called ``Unix version 6'', etc., but
15483 they were not as widely used.
15488 @section Shellology
15491 There are several families of shells, most prominently the Bourne family
15492 and the C shell family which are deeply incompatible. If you want to
15493 write portable shell scripts, avoid members of the C shell family. The
15494 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15495 Shell difference FAQ} includes a small history of POSIX shells, and a
15496 comparison between several of them.
15498 Below we describe some of the members of the Bourne shell family.
15503 Ash is often used on GNU/Linux and BSD
15504 systems as a light-weight Bourne-compatible shell. Ash 0.2 has some
15505 bugs that are fixed in the 0.3.x series, but portable shell scripts
15506 should work around them, since version 0.2 is still shipped with many
15507 GNU/Linux distributions.
15509 To be compatible with Ash 0.2:
15513 don't use @samp{$?} after expanding empty or unset variables,
15514 or at the start of an @command{eval}:
15520 echo "Do not use it: $?"
15522 eval 'echo "Do not use it: $?"'
15526 don't use command substitution within variable expansion:
15533 beware that single builtin substitutions are not performed by a
15534 subshell, hence their effect applies to the current shell! @xref{Shell
15535 Substitutions}, item ``Command Substitution''.
15540 To detect whether you are running Bash, test whether
15541 @code{BASH_VERSION} is set. To require
15542 POSIX compatibility, run @samp{set -o posix}. @xref{Bash POSIX
15543 Mode, , Bash POSIX Mode, bash, The GNU Bash Reference
15544 Manual}, for details.
15546 @item Bash 2.05 and later
15547 @cindex Bash 2.05 and later
15548 Versions 2.05 and later of Bash use a different format for the
15549 output of the @command{set} builtin, designed to make evaluating its
15550 output easier. However, this output is not compatible with earlier
15551 versions of Bash (or with many other shells, probably). So if
15552 you use Bash 2.05 or higher to execute @command{configure},
15553 you'll need to use Bash 2.05 for all other build tasks as well.
15558 @prindex @samp{ksh}
15559 @prindex @samp{ksh88}
15560 @prindex @samp{ksh93}
15561 The Korn shell is compatible with the Bourne family and it mostly
15562 conforms to POSIX. It has two major variants commonly
15563 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15564 release. It is usually called @command{ksh}, but is called @command{sh}
15565 on some hosts if you set your path appropriately.
15567 On Solaris 11, @command{/bin/sh} and @command{/usr/bin/ksh} are both
15568 @samp{ksh93}. On Solaris 10 and earlier, @command{/bin/sh} is a
15569 pre-POSIX Bourne shell and the Korn shell is found elsewhere:
15570 @prindex @command{/usr/bin/ksh} on Solaris
15571 @command{/usr/bin/ksh} is @samp{ksh88} on Solaris 10,
15572 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15573 @command{/usr/xpg4/bin/sh} is a POSIX-compliant variant of
15574 @samp{ksh88} on Solaris 10 and later,
15575 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15576 and @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15577 Variants that are not standard may be parts of optional
15578 packages. There is no extra charge for these packages, but they are
15579 not part of a minimal OS install and therefore some installations may
15583 @prindex @samp{pdksh}
15584 A public-domain clone of the Korn shell called @command{pdksh} is widely
15585 available: it has most of the @samp{ksh88} features along with a few of
15586 its own. It usually sets @code{KSH_VERSION}, except if invoked as
15587 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15588 POSIX compatibility by running @samp{set -o posix}. Unfortunately, with
15589 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15590 POSIX mode is buggy and causes @command{pdksh} to depart from POSIX in
15591 at least one respect, see @ref{Shell Substitutions}.
15595 To detect whether you are running @command{zsh}, test whether
15596 @code{ZSH_VERSION} is set. By default @command{zsh} is @emph{not}
15597 compatible with the Bourne shell: you must execute @samp{emulate sh},
15598 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15599 set @code{NULLCMD} to @samp{:}. @xref{Compatibility, , Compatibility,
15600 zsh, The Z Shell Manual}, for details.
15602 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15603 Bash in Mac OS X 10.2 (2002) and changed back to Zsh in macOS 10.15 (2019).
15606 @node Invoking the Shell
15607 @section Invoking the Shell
15608 @cindex invoking the shell
15609 @cindex shell invocation
15611 The Korn shell (up to at least version M-12/28/93d) has a bug when
15612 invoked on a file whose name does not contain a slash. It first
15613 searches for the file's name in @env{PATH}, and if found it executes
15614 that rather than the original file. For example, assuming there is a
15615 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15616 command in the following example fails because the Korn shell finds
15617 @file{/usr/bin/script} and refuses to execute it as a shell script:
15620 $ @kbd{touch xxyzzyz script}
15621 $ @kbd{ksh xxyzzyz}
15622 $ @kbd{ksh ./script}
15624 ksh: script: cannot execute
15627 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15628 option-argument ends in backslash-newline, Bash incorrectly reports a
15629 syntax error. The problem does not occur if a character follows the
15633 $ @kbd{$ bash -c 'echo foo \}
15635 bash: -c: line 2: syntax error: unexpected end of file
15636 $ @kbd{bash -c 'echo foo \}
15642 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15644 @node Here-Documents
15645 @section Here-Documents
15646 @cindex Here-documents
15647 @cindex Shell here-documents
15649 Because unquoted here-documents are subject to parameter expansion and
15650 command substitution, the characters @samp{$} and @samp{`} are special
15651 in unquoted here-documents and should be escaped by @samp{\} if you want
15652 them as-is. Also, @samp{\} is special if it precedes @samp{$},
15653 @samp{`}, newline or @samp{\} itself, so @samp{\} should be doubled if
15654 it appears before these characters and you want it as-is.
15656 Using command substitutions in a here-document that is fed to a shell
15657 function is not portable. For example, with Solaris 10 @command{/bin/sh}:
15660 $ @kbd{kitty () @{ cat; @}}
15664 /tmp/sh199886: cannot open
15669 Some shells mishandle large here-documents: for example,
15670 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 POSIX shell, which are
15671 derived from Korn shell version M-12/28/93d, mishandle braced variable
15672 expansion that crosses a 1024- or 4096-byte buffer boundary
15673 within a here-document. Only the part of the variable name after the boundary
15674 is used. For example, @code{$@{variable@}} could be replaced by the expansion
15675 of @code{$@{ble@}}. If the end of the variable name is aligned with the block
15676 boundary, the shell reports an error, as if you used @code{$@{@}}.
15677 Instead of @code{$@{variable-default@}}, the shell may expand
15678 @code{$@{riable-default@}}, or even @code{$@{fault@}}. This bug can often
15679 be worked around by omitting the braces: @code{$variable}. The bug was
15681 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15682 still shipping older versions with the bug.
15684 Empty here-documents are not portable either; with the following code,
15685 @command{zsh} up to at least version 4.3.10 creates a file with a single
15686 newline, whereas other shells create an empty file:
15693 Many shells (including the Bourne shell) implement here-documents
15694 inefficiently. In particular, some shells can be extremely inefficient when
15695 a single statement contains many here-documents. For instance if your
15696 @file{configure.ac} includes something like:
15700 AS_IF([<cross_compiling>],
15701 [assume this and that],
15704 check something else
15711 A shell parses the whole @code{if}/@code{fi} construct generated by
15712 @code{AS_IF}, creating
15713 temporary files for each here-document in it. Some shells create links
15714 for such here-documents on every @code{fork}, so that the clean-up code
15715 they had installed correctly removes them. It is creating the links
15716 that can take the shell forever.
15718 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15719 @code{if}/@code{fi} constructs, would improve the performance
15720 significantly. Anyway, this kind of construct is not exactly the
15721 typical use of Autoconf. In fact, it's even not recommended, because M4
15722 macros can't look into shell conditionals, so we may fail to expand a
15723 macro when it was expanded before in a conditional path, and the
15724 condition turned out to be false at runtime, and we end up not
15725 executing the macro at all.
15727 Be careful with the use of @samp{<<-} to unindent here-documents. The
15728 behavior is only portable for stripping leading @key{TAB}s, and things
15729 can silently break if an overzealous editor converts to using leading
15730 spaces (not all shells are nice enough to warn about unterminated
15734 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15738 $ @kbd{printf 'cat <<-x\n 1\n 2\n x\n' | bash-3.2 && echo done}
15745 @node File Descriptors
15746 @section File Descriptors
15747 @cindex Descriptors
15748 @cindex File descriptors
15749 @cindex Shell file descriptors
15751 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15752 stderr, even for subshells. This might result in undesirable content
15753 if you meant to capture the standard-error output of the inner command:
15756 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15758 + eval echo foo >&2
15761 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15763 + eval 'echo foo >&2'
15766 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15767 @i{# Traces on startup files deleted here.}
15769 +zsh:1> eval echo foo >&2
15775 One workaround is to grep out uninteresting lines, hoping not to remove
15778 If you intend to redirect both standard error and standard output,
15779 redirect standard output first. This works better with HP-UX,
15780 since its shell mishandles tracing if standard error is redirected
15784 $ @kbd{sh -x -c ': 2>err >out'}
15786 + 2> err $ @kbd{cat err}
15790 Don't try to redirect the standard error of a command substitution. It
15791 must be done @emph{inside} the command substitution. When running
15792 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15793 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15795 On the other hand, some shells, such as Solaris or FreeBSD
15796 @command{/bin/sh}, warn about missing programs before performing
15797 redirections. Therefore, to silently check whether a program exists, it
15798 is necessary to perform redirections on a subshell or brace group:
15800 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15802 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15803 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15804 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15807 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15810 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15811 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15813 Some shells, like @command{ash}, don't recognize bi-directional
15814 redirection (@samp{<>}). And even on shells that recognize it, it is
15815 not portable to use on fifos: POSIX does not require read-write support
15816 for named pipes, and Cygwin does not support it:
15819 $ @kbd{mkfifo fifo}
15820 $ @kbd{exec 5<>fifo}
15821 $ @kbd{echo hi >&5}
15822 bash: echo: write error: Communication error on send
15826 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15827 regular files when using @samp{<>}:
15830 $ @kbd{echo a > file}
15831 $ @kbd{bash -c ': 1<>file'; cat file}
15833 $ @kbd{dash -c ': 1<>file'; cat file}
15837 Solaris 10 @code{/bin/sh} executes redirected compound commands
15838 in a subshell, while other shells don't:
15841 $ @kbd{/bin/sh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15843 $ @kbd{ksh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15845 $ @kbd{bash -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15849 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15850 (even if it is redirected) in a loop after the first iteration, or in a
15851 shell function after the first call:
15854 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15857 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15863 As a workaround, @command{echo} or @command{eval} can be used.
15865 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15866 subsidiary program. If any of these descriptors is closed, the
15867 operating system may open an unspecified file for the descriptor in the
15868 new process image. POSIX 2008 says this may be done only if the
15869 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15870 it even for ordinary programs, and the next version of POSIX will allow
15873 If you want a file descriptor above 2 to be inherited into a child
15874 process, then you must use redirections specific to that command or a
15875 containing subshell or command group, rather than relying on
15876 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15877 @command{sh}, file descriptors above 2 which are opened using
15878 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15879 that involved in the fork-and-exec which runs a program or script):
15882 $ @kbd{echo 'echo hello >&5' >k}
15883 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15885 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15887 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15888 ./k[1]: 5: cannot open [Bad file number]
15889 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15891 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15893 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15897 Don't rely on duplicating a closed file descriptor to cause an
15898 error. With Solaris 10 @command{/bin/sh}, failed duplication is silently
15899 ignored, which can cause unintended leaks to the original file
15900 descriptor. In this example, observe the leak to standard output:
15903 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15904 bash: 3: Bad file descriptor
15906 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15911 Fortunately, an attempt to close an already closed file descriptor will
15912 portably succeed. Likewise, it is safe to use either style of
15913 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15914 even if it doesn't match the read/write mode that the file descriptor
15917 DOS variants cannot rename or remove open files, such as in
15918 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15919 perfectly portable among POSIX hosts.
15921 A few ancient systems reserved some file descriptors. By convention,
15922 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15923 Eighth Edition (1985) through Tenth Edition Unix (1989). File
15924 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15925 1990), though we don't now remember what it was. Both these systems are
15926 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15927 other file descriptors.
15929 On the other hand, you can't portably use multi-digit file descriptors.
15930 @command{dash} and Solaris @command{ksh} don't understand any file
15931 descriptor larger than @samp{9}:
15934 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15936 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15938 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15939 ksh[1]: exec: 10: not found
15941 $ @kbd{dash -c 'exec 9>&-'; echo $?}
15943 $ @kbd{dash -c 'exec 10>&-'; echo $?}
15944 exec: 1: 10: not found
15948 @c <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15949 @node Signal Handling
15950 @section Signal Handling
15951 @cindex Signal handling in the shell
15952 @cindex Signals, shells and
15954 Portable handling of signals within the shell is another major source of
15955 headaches. This is worsened by the fact that various different, mutually
15956 incompatible approaches are possible in this area, each with its
15957 distinctive merits and demerits. A detailed description of these possible
15958 approaches, as well as of their pros and cons, can be found in
15959 @uref{https://www.cons.org/cracauer/sigint.html, this article}.
15961 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15962 the shell still exits with error upon termination by one of those signals,
15963 but in such a case the exit status might be somewhat unexpected (even if
15964 allowed by POSIX, strictly speaking):
15965 @c FIXME: We had a reference for this behavior but the website no longer
15966 @c exists and the page is not in the Internet Archive. --zw 2020-07-10.
15969 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15972 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15975 $ @kbd{for sig in 1 2 3 15; do}
15976 > @kbd{ echo $sig:}
15977 > @kbd{ /bin/sh -c "kill -$s \$\$"; echo $?}
15990 This gets even worse if one is using the POSIX ``wait'' interface to get
15991 details about the shell process terminations: it will result in the shell
15992 having exited normally, rather than by receiving a signal.
15995 $ @kbd{cat > foo.c <<'END'}
15996 #include <stdio.h> /* for printf */
15997 #include <stdlib.h> /* for system */
15998 #include <sys/wait.h> /* for WIF* macros */
16001 int status = system ("kill -15 $$");
16002 printf ("Terminated by signal: %s\n",
16003 WIFSIGNALED (status) ? "yes" : "no");
16004 printf ("Exited normally: %s\n",
16005 WIFEXITED (status) ? "yes" : "no");
16010 $ @kbd{cc -o foo foo.c}
16011 $ @kbd{./a.out} # On GNU/Linux
16012 Terminated by signal: no
16013 Exited normally: yes
16014 $ @kbd{./a.out} # On Solaris 10
16015 Terminated by signal: yes
16016 Exited normally: no
16019 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
16020 if it is not blocked, and even if the shell is not running interactively
16021 (in fact, even if the shell has no attached tty); among these shells
16022 are at least Bash (from version 2 onward), Zsh 4.3.12, Solaris 10
16023 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
16024 Still, @code{SIGQUIT} seems to be trappable quite portably within all
16025 these shells. OTOH, some other shells doesn't special-case the handling
16026 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
16027 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
16029 Some shells (especially Korn shells and derivatives) might try to
16030 propagate to themselves a signal that has killed a child process; this is
16031 not a bug, but a conscious design choice (although its overall value might
16032 be debatable). The exact details of how this is attained vary from shell
16033 to shell. For example, upon running @code{perl -e 'kill 2, $$'}, after
16034 the perl process has been interrupted, AT&T @code{ksh93} (2011) will
16035 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
16036 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
16037 128 + 2). In any case, if there is an active trap associated with
16038 @code{SIGINT}, those shells will correctly execute it.
16040 @c See: <https://www.austingroupbugs.net/view.php?id=51>
16041 Some Korn shells, when a child process die due receiving a signal with
16042 signal number @var{n}, can leave in @samp{$?} an exit status of
16043 256+@var{n} instead of the more common 128+@var{n}. Observe the
16044 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
16048 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
16049 /bin/ksh: line 1: 7837: Hangup
16051 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
16052 /bin/bash: line 1: 7861 Hangup (sh -c "kill -1 \$\$")
16057 This @command{ksh} behavior is allowed by POSIX, if implemented with
16058 due care; see this @uref{https://www.austingroupbugs.net/view.php?id=51,
16059 Austin Group discussion} for more background. However, if it is not
16060 implemented with proper care, such a behavior might cause problems
16061 in some corner cases. To see why, assume we have a ``wrapper'' script
16066 # Ignore some signals in the shell only, not in its child processes.
16068 wrapped_command "$@@"
16075 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
16076 has signal number 1), @code{ret} will be set to 257. Unless the
16077 @command{exit} shell builtin is smart enough to understand that such
16078 a value can only have originated from a signal, and adjust the final
16079 wait status of the shell appropriately, the value 257 will just get
16080 truncated to 1 by the closing @code{exit} call, so that a caller of
16081 the script will have no way to determine that termination by a signal
16082 was involved. Observe the different behavior of AT&T @code{ksh93}
16083 (2011) and @code{bash} 4.1.5 on Debian:
16092 $ @kbd{/bin/ksh foo.sh; echo $?}
16093 foo.sh: line 2: 12479: Hangup
16096 $ @kbd{/bin/bash foo.sh; echo $?}
16097 foo.sh: line 2: 12487 Hangup (sh -c 'kill -1 $$')
16102 @node File System Conventions
16103 @section File System Conventions
16104 @cindex File system conventions
16106 Autoconf uses shell-script processing extensively, so the file names
16107 that it processes should not contain characters that are special to the
16108 shell. Special characters include space, tab, newline, NUL, and
16112 " # $ & ' ( ) * ; < = > ? [ \ ` |
16115 Also, file names should not begin with @samp{~} or @samp{-}, and should
16116 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
16117 immediately after @samp{:}. On POSIX-like platforms, directory names
16118 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
16121 These restrictions apply not only to the files that you distribute, but
16122 also to the absolute file names of your source, build, and destination
16125 On some POSIX-like platforms, @samp{!} and @samp{^} are special too, so
16126 they should be avoided.
16128 POSIX lets implementations treat leading @file{//} specially, but
16129 requires leading @file{///} and beyond to be equivalent to @file{/}.
16130 Most Unix variants treat @file{//} like @file{/}. However, some treat
16131 @file{//} as a ``super-root'' that can provide access to files that are
16132 not otherwise reachable from @file{/}. The super-root tradition began
16133 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
16136 While @command{autoconf} and friends are usually run on some POSIX
16137 variety, they can be used on other systems, most notably DOS
16138 variants. This impacts several assumptions regarding file names.
16141 For example, the following code:
16148 foo_dir=$dots$foo_dir ;;
16153 fails to properly detect absolute file names on those systems, because
16154 they can use a drivespec, and usually use a backslash as directory
16155 separator. If you want to be portable to DOS variants (at the
16156 price of rejecting valid but oddball POSIX file names like @file{a:\b}),
16157 you can check for absolute file names like this:
16159 @cindex absolute file names, detect
16162 [\\/]* | ?:[\\/]* ) # Absolute
16165 foo_dir=$dots$foo_dir ;;
16170 Make sure you quote the brackets if appropriate and keep the backslash as
16171 first character. @xref{case, , Limitations of Shell Builtins}.
16173 Also, because the colon is used as part of a drivespec, these systems don't
16174 use it as path separator. When creating or accessing paths, you can use the
16175 @code{PATH_SEPARATOR} output variable instead. @command{configure} sets this
16176 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
16179 File names need extra care as well. While DOS variants
16180 that are POSIXy enough to run @command{autoconf} (such as DJGPP)
16181 are usually able to handle long file names properly, there are still
16182 limitations that can seriously break packages. Several of these issues
16183 can be easily detected by the
16184 @uref{https://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
16187 A short overview follows; problems are marked with SFN/LFN to
16188 indicate where they apply: SFN means the issues are only relevant to
16189 plain DOS, not to DOS under Microsoft Windows
16190 variants, while LFN identifies problems that exist even under
16191 Microsoft Windows variants.
16194 @item No multiple dots (SFN)
16195 DOS cannot handle multiple dots in file names. This is an especially
16196 important thing to remember when building a portable configure script,
16197 as @command{autoconf} uses a .in suffix for template files.
16199 This is perfectly OK on POSIX variants:
16202 AC_CONFIG_HEADERS([config.h])
16203 AC_CONFIG_FILES([source.c foo.bar])
16208 but it causes problems on DOS, as it requires @samp{config.h.in},
16209 @samp{source.c.in} and @samp{foo.bar.in}. To make your package more portable
16210 to DOS-based environments, you should use this instead:
16213 AC_CONFIG_HEADERS([config.h:config.hin])
16214 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
16218 @item No leading dot (SFN)
16219 DOS cannot handle file names that start with a dot. This is usually
16220 not important for @command{autoconf}.
16222 @item Case insensitivity (LFN)
16223 DOS is case insensitive, so you cannot, for example, have both a
16224 file called @samp{INSTALL} and a directory called @samp{install}. This
16225 also affects @command{make}; if there's a file called @samp{INSTALL} in
16226 the directory, @samp{make install} does nothing (unless the
16227 @samp{install} target is marked as PHONY).
16229 @item The 8+3 limit (SFN)
16230 Because the DOS file system only stores the first 8 characters of
16231 the file name and the first 3 of the extension, those must be unique.
16232 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
16233 @file{foobar-prettybird.c} all resolve to the same file name
16234 (@file{FOOBAR-P.C}). The same goes for @file{foo.bar} and
16235 @file{foo.bartender}.
16237 The 8+3 limit is not usually a problem under Microsoft Windows, as it
16239 tails in the short version of file names to make them unique. However, a
16240 registry setting can turn this behavior off. While this makes it
16241 possible to share file trees containing long file names between SFN
16242 and LFN environments, it also means the above problem applies there
16245 @item Invalid characters (LFN)
16246 Some characters are invalid in DOS file names, and should therefore
16247 be avoided. In a LFN environment, these are @samp{/}, @samp{\},
16248 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
16249 In a SFN environment, other characters are also invalid. These
16250 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
16252 @item Invalid names (LFN)
16253 Some DOS file names are reserved, and cause problems if you
16254 try to use files with those names. These names include @file{CON},
16255 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
16256 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
16257 File names are case insensitive, so even names like
16258 @file{aux/config.guess} are disallowed.
16262 @node Shell Pattern Matching
16263 @section Shell Pattern Matching
16264 @cindex Shell pattern matching
16266 Nowadays portable patterns can use negated character classes like
16267 @samp{[!-aeiou]}. The older syntax @samp{[^-aeiou]} is supported by
16268 some shells but not others; hence portable scripts should never use
16269 @samp{^} as the first character of a bracket pattern.
16271 Outside the C locale, patterns like @samp{[a-z]} are problematic since
16272 they may match characters that are not lower-case letters.
16274 @node Shell Substitutions
16275 @section Shell Substitutions
16276 @cindex Shell substitutions
16278 Contrary to a persistent urban legend, the Bourne shell does not
16279 systematically split variables and back-quoted expressions, in particular
16280 on the right-hand side of assignments and in the argument of @code{case}.
16281 For instance, the following code:
16284 case "$given_srcdir" in
16285 .) top_srcdir="`printf '%s\n' "$dots" | sed 's|/$||'`" ;;
16286 *) top_srcdir="$dots$given_srcdir" ;;
16291 is more readable when written as:
16294 case $given_srcdir in
16295 .) top_srcdir=`printf '%s\n' "$dots" | sed 's|/$||'` ;;
16296 *) top_srcdir=$dots$given_srcdir ;;
16301 and in fact it is even @emph{more} portable: in the first case of the
16302 first attempt, the computation of @code{top_srcdir} is not portable,
16303 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16304 for example Solaris 10 @command{ksh}:
16307 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16308 ksh: : cannot execute
16309 ksh: bar | sed 's, ,,': cannot execute
16313 POSIX does not specify behavior for this sequence. On the other hand,
16314 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by POSIX,
16315 but in practice, not all shells understand it the same way: pdksh 5.2.14
16316 prints spurious quotes when in POSIX mode:
16319 $ @kbd{echo "`echo \"hello\"`"}
16321 $ @kbd{set -o posix}
16322 $ @kbd{echo "`echo \"hello\"`"}
16327 There is just no portable way to use double-quoted strings inside
16328 double-quoted back-quoted expressions (pfew!).
16330 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16331 parameter expansions are elided during word splitting. Meanwhile, zsh
16332 does not perform word splitting except when in Bourne compatibility
16333 mode. In the example below, the correct behavior is to have five
16334 arguments to the function, and exactly two spaces on either side of the
16335 middle @samp{-}, since word splitting collapses multiple spaces in
16336 @samp{$f} but leaves empty arguments intact.
16339 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16341 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16343 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16345 $ @kbd{zsh -c 'emulate sh;}
16346 > @kbd{n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16351 You can work around this by doing manual word splitting, such as using
16352 @samp{"$str" $list} rather than @samp{"$str"$list}.
16354 There are also portability pitfalls with particular expansions:
16358 @cindex @code{"$@@"}
16359 Autoconf macros often use the @command{set} command to update
16360 @samp{$@@}, so if you are writing shell code intended for
16361 @command{configure} you should not assume that the value of @samp{$@@}
16362 persists for any length of time.
16364 You may see usages like @samp{$@{1+"$@@"@}} in older shell scripts
16365 designed to work around a portability problem in ancient shells.
16366 Unfortunately this runs afoul of bugs in more-recent shells, and
16367 nowadays it is better to use plain @samp{"$@@"} instead.
16369 The portability problem with ancient shells was significant.
16370 When there are no positional arguments @samp{"$@@"} should be discarded,
16371 but the original Unix version 7 Bourne shell mistakenly treated it as
16372 equivalent to @samp{""} instead, and many ancient shells followed its lead.
16374 For many years shell scripts worked around this portability problem by
16375 using @samp{$@{1+"$@@"@}} instead of @samp{"$@@"}, and you may see this
16376 usage in older scripts. Unfortunately, @samp{$@{1+"$@@"@}} does not
16377 work with @command{ksh93} M 93t+ (2009) as shipped in AIX 7.2 (2015),
16378 as this shell drops a trailing empty argument:
16381 $ @kbd{set a b c ""}
16382 $ @kbd{set $@{1+"$@@"@}}
16387 Also, @samp{$@{1+"$@@"@}} does not work with Zsh 4.2.6 (2005) and
16388 earlier, as shipped in Mac OS X releases before 10.5, as this old Zsh
16389 incorrectly word splits the result:
16392 zsh $ @kbd{emulate sh}
16393 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16396 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16402 To work around these problems Autoconf does two things. First, in the
16403 shell code that it generates Autoconf avoids @samp{"$@@"} if it is
16404 possible that there may be no positional arguments. You can use this
16405 workaround in your own code, too, if you want it to be portable to
16406 ancient shells. For example, instead of:
16409 cat conftest.c "$@@"
16416 0) cat conftest.c;;
16417 *) cat conftest.c "$@@";;
16422 Second, Autoconf-generated @command{configure} scripts work around most
16423 of the old Zsh problem by using Zsh's ``global aliases'' to convert
16424 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16427 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16430 This workaround is for the benefit of any instances of
16431 @samp{$@{1+"$@@"@}} in user-written code appearing in
16432 @command{configure} scripts. However, it is not a complete solution, as
16433 Zsh recognizes the alias only when a shell word matches it exactly,
16434 which means older Zsh still mishandles more-complicated cases like
16435 @samp{"foo"$@{1+"$@@"@}}.
16438 @cindex positional parameters
16439 The 10th, 11th, @dots{} positional parameters can be accessed only after
16440 a @code{shift}. The 7th Edition shell reported an error if given
16441 @code{$@{10@}}, and
16442 Solaris 10 @command{/bin/sh} still acts that way:
16445 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16446 $ @kbd{echo $@{10@}}
16450 Conversely, not all shells obey the POSIX rule that when braces are
16451 omitted, multiple digits beyond a @samp{$} imply the single-digit
16452 positional parameter expansion concatenated with the remaining literal
16453 digits. To work around the issue, you must use braces.
16456 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16458 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16462 @item $@{@var{var}-@var{value}@}
16463 @itemx $@{@var{var}:-@var{value}@}
16464 @itemx $@{@var{var}=@var{value}@}
16465 @itemx $@{@var{var}:=@var{value}@}
16466 @itemx $@{@var{var}?@var{value}@}
16467 @itemx $@{@var{var}:?@var{value}@}
16468 @itemx $@{@var{var}+@var{value}@}
16469 @itemx $@{@var{var}:+@var{value}@}
16470 @cindex @code{$@{@var{var}-@var{value}@}}
16471 @cindex @code{$@{@var{var}=@var{value}@}}
16472 @cindex @code{$@{@var{var}?@var{value}@}}
16473 @cindex @code{$@{@var{var}+@var{value}@}}
16474 @c Info cannot handle ':' in index entries.
16476 @cindex @code{$@{@var{var}:-@var{value}@}}
16477 @cindex @code{$@{@var{var}:=@var{value}@}}
16478 @cindex @code{$@{@var{var}:?@var{value}@}}
16479 @cindex @code{$@{@var{var}:+@var{value}@}}
16481 When using @samp{$@{@var{var}-@var{value}@}} or
16482 similar notations that modify a parameter expansion,
16483 POSIX requires that @var{value} must be a single shell word,
16484 which can contain quoted strings but cannot contain unquoted spaces.
16485 If this requirement is not met Solaris 10 @command{/bin/sh}
16486 sometimes complains, and anyway the behavior is not portable.
16489 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16490 /bin/sh: bad substitution
16491 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16493 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16495 $ @kbd{/bin/sh -c 'cat <<EOF
16501 Most shells treat the special parameters @code{*} and @code{@@} as being
16502 unset if there are no positional parameters. However, some shells treat
16503 them as being set to the empty string. POSIX does not clearly specify
16507 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16509 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16513 According to POSIX, if an expansion occurs inside double quotes, then
16514 the use of unquoted double quotes within @var{value} is unspecified, and
16515 any single quotes become literal characters; in that case, escaping must
16516 be done with backslash. Likewise, the use of unquoted here-documents is
16517 a case where double quotes have unspecified results:
16520 $ @kbd{/bin/sh -c 'echo "$@{a-"b c"@}"'}
16521 /bin/sh: bad substitution
16522 $ @kbd{ksh -c 'echo "$@{a-"b c"@}"'}
16524 $ @kbd{bash -c 'echo "$@{a-"b c"@}"'}
16526 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b c'\''@}'}
16528 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b c'\''@}"'}
16530 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b c\"@}"'}
16532 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b c@}"'}
16534 $ @kbd{/bin/sh -c 'cat <<EOF
16538 $ @kbd{/bin/sh -c 'cat <<EOF
16542 $ @kbd{bash -c 'cat <<EOF
16546 $ @kbd{bash -c 'cat <<EOF
16552 Perhaps the easiest way to work around quoting issues in a manner
16553 portable to all shells is to place the results in a temporary variable,
16554 then use @samp{$t} as the @var{value}, rather than trying to inline
16555 the expression needing quoting.
16558 $ @kbd{/bin/sh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16560 $ @kbd{ksh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16562 $ @kbd{bash -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16566 @item $@{@var{var}=@var{value}@}
16567 @cindex @code{$@{@var{var}=@var{value}@}}
16568 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16569 to @var{var}, remember that even though the assignment to @var{var} does
16570 not undergo file name expansion, the result of the variable expansion
16571 does unless the expansion occurred within double quotes. In particular,
16572 when using @command{:} followed by unquoted variable expansion for the
16573 side effect of setting a default value, if the final value of
16574 @samp{$var} contains any globbing characters (either from @var{value} or
16575 from prior contents), the shell has to spend time performing file name
16576 expansion and field splitting even though those results will not be
16577 used. Therefore, it is a good idea to consider double quotes when performing
16578 default initialization; while remembering how this impacts any quoting
16579 characters appearing in @var{value}.
16582 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16588 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16594 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16601 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16609 As with @samp{+} and @samp{-}, @var{value} must be a single shell word,
16610 otherwise some shells, such as Solaris 10 @command{/bin/sh} or on Digital
16611 Unix V 5.0, die because of a ``bad substitution''. Meanwhile, POSIX
16612 requires that with @samp{=}, quote removal happens prior to the
16613 assignment, and the expansion be the final contents of @var{var} without
16614 quoting (and thus subject to field splitting), in contrast to the
16615 behavior with @samp{-} passing the quoting through to the final
16616 expansion. However, @command{bash} 4.1 does not obey this rule.
16619 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16621 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16623 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16627 Finally, POSIX states that when mixing @samp{$@{a=b@}} with regular
16628 commands, it is unspecified whether the assignments affect the parent
16629 shell environment. It is best to perform assignments independently from
16630 commands, to avoid the problems demonstrated in this example running on
16634 $ @kbd{cmd='x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";printf "%s\\n" -$x-'}
16635 $ @kbd{bash -c "$cmd"}
16638 $ @kbd{/bin/sh -c "$cmd"}
16641 $ @kbd{ksh -c "$cmd"}
16646 @item $@{@var{var}=@var{value}@}
16647 @cindex @code{$@{@var{var}=@var{literal}@}}
16648 Solaris 10 @command{/bin/sh} has a frightening bug in its handling of
16649 literal assignments. Imagine you need set a variable to a string containing
16650 @samp{@}}. This @samp{@}} character confuses Solaris 10 @command{/bin/sh}
16651 when the affected variable was already set. This bug can be exercised
16656 $ @kbd{foo=$@{foo='@}'@}}
16659 $ @kbd{foo=$@{foo='@}' # no error; this hints to what the bug is}
16662 $ @kbd{foo=$@{foo='@}'@}}
16668 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16669 though it is enclosed in single quotes. The problem doesn't happen
16670 using double quotes, or when using a temporary variable holding the
16671 problematic string.
16673 @item $@{@var{var}=@var{expanded-value}@}
16674 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16675 On shells so old that they are no longer relevant, the command
16678 # Set the shell variable to a default value
16679 # if it is not already set.
16680 : $@{var="$default"@}
16684 misbehaved badly in some cases. Older scripts worked around the bugs by
16685 using one of following two lines, the latter of which was more portable:
16688 var=$@{var="$default"@}
16689 test $@{var+y@} || var=$default
16693 However, these workarounds are no longer needed.
16695 @item $@{#@var{var}@}
16696 @itemx $@{@var{var}%@var{word}@}
16697 @itemx $@{@var{var}%%@var{word}@}
16698 @itemx $@{@var{var}#@var{word}@}
16699 @itemx $@{@var{var}##@var{word}@}
16700 @cindex @code{$@{#@var{var}@}}
16701 @cindex @code{$@{@var{var}%@var{word}@}}
16702 @cindex @code{$@{@var{var}%%@var{word}@}}
16703 @cindex @code{$@{@var{var}#@var{word}@}}
16704 @cindex @code{$@{@var{var}##@var{word}@}}
16705 POSIX requires support for these usages, but they do not work with many
16706 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16708 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms. For
16709 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16710 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16711 yields the empty string.
16714 @item `@var{commands}`
16715 @cindex @code{`@var{commands}`}
16716 @cindex Command Substitution
16717 POSIX requires shells to trim all trailing newlines from command
16718 output before substituting it, so assignments like
16719 @samp{dir=`printf '%s\n' "$file" | tr a A`} do not work as expected if
16720 @samp{$file} ends in a newline.
16722 While in general it makes no sense, do not substitute a single builtin
16723 with side effects, because Ash 0.2, trying to optimize, does not fork a
16724 subshell to perform the command.
16725 For instance, if you wanted to check that @command{cd} is silent, do not
16726 use @samp{test -z "`cd /`"} because the following can happen:
16731 $ @kbd{test -z "`cd /`" && pwd}
16736 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16738 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16739 command substitution of a native program, if the end of the substitution
16740 is not aligned with the end of the double quote. This may be worked
16741 around by inserting another pair of quotes:
16744 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16745 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16746 - broken differ: char 4, line 1
16749 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16750 replace it with a null string, and wrongly evaluate the enclosing
16751 command before entering the trap or ending the script. This can lead to
16755 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16757 sh: test: hi: unexpected operator/operand
16761 You can avoid this by assigning the command substitution to a temporary
16765 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16766 if test "x$res" = xhi; then echo yes; fi'}
16770 @item $(@var{commands})
16771 @cindex @code{$(@var{commands})}
16772 This construct is meant to replace @samp{`@var{commands}`},
16773 and it has most of the problems listed under @code{`@var{commands}`}.
16775 This construct can be
16776 nested while this is impossible to do portably with back quotes.
16777 Although it is almost universally supported, unfortunately Solaris 10
16778 and earlier releases lack it:
16781 $ @kbd{showrev -c /bin/sh | grep version}
16782 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16783 $ @kbd{echo $(echo blah)}
16784 syntax error: `(' unexpected
16787 If you do use @samp{$(@var{commands})}, make sure that the commands
16788 do not start with a parenthesis, as that would cause confusion with
16789 a different notation @samp{$((@var{expression}))} that in modern
16790 shells is an arithmetic expression not a command. To avoid the
16791 confusion, insert a space between the two opening parentheses.
16793 Avoid @var{commands} that contain unbalanced parentheses in
16794 here-documents, comments, or case statement patterns, as many shells
16795 mishandle them. For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16796 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16799 echo $(case x in x) echo hello;; esac)
16803 @item $((@var{expression}))
16804 @cindex @code{$((@var{expression}))}
16805 Arithmetic expansion is not portable as some shells (most
16806 notably Solaris 10 @command{/bin/sh}) don't support it.
16808 Among shells that do support @samp{$(( ))}, not all of them obey the
16809 POSIX rule that octal and hexadecimal constants must be recognized:
16812 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16814 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16816 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16818 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16819 pdksh: 010 + 0x10 : bad number `0x10'
16820 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16824 When it is available, using arithmetic expansion provides a noticeable
16825 speedup in script execution; but testing for support requires
16826 @command{eval} to avoid syntax errors. The following construct is used
16827 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16828 arguments are decimal integers without leading zeros, and all
16829 operators are properly quoted and appear as distinct arguments:
16832 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16833 eval 'func_arith ()
16835 func_arith_result=$(( $* ))
16840 func_arith_result=`expr "$@@"`
16844 foo=$func_arith_result
16849 @cindex @code{^} quoting
16850 Always quote @samp{^}, otherwise traditional shells such as
16851 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16857 @section Assignments
16858 @cindex Shell assignments
16860 When setting several variables in a row, be aware that the order of the
16861 evaluation is undefined. For instance @samp{foo=1 foo=2; echo $foo}
16862 gives @samp{1} with Solaris 10 @command{/bin/sh}, but @samp{2} with Bash.
16864 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16866 Don't rely on the following to find @file{subdir/program}:
16869 PATH=subdir$PATH_SEPARATOR$PATH program
16873 as this does not work with Zsh 3.0.6. Use something like this
16877 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16880 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16881 the status and propagates that of the last statement:
16884 $ @kbd{false || foo=bar; echo $?}
16886 $ @kbd{false || foo=`:`; echo $?}
16891 and to make things even worse, QNX 4.25 just sets the exit status
16895 $ @kbd{foo=`exit 1`; echo $?}
16899 To assign default values, follow this algorithm:
16903 If the default value is a literal and does not contain any closing
16907 : "$@{var='my literal'@}"
16911 If the default value contains no closing brace, has to be expanded, and
16912 the variable being initialized is not intended to be IFS-split
16913 (i.e., it's not a list), then use:
16916 : $@{var="$default"@}
16920 If the default value contains no closing brace, has to be expanded, and
16921 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16925 var=$@{var="$default"@}
16929 If the default value contains a closing brace, then use:
16932 test $@{var+y@} || var="has a '@}'"
16936 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16937 doubt, just use the last form. @xref{Shell Substitutions}, items
16938 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16942 @section Parentheses in Shell Scripts
16943 @cindex Shell parentheses
16945 Beware of two opening parentheses in a row, as many shell
16946 implementations treat them specially, and POSIX says that a portable
16947 script cannot use @samp{((} outside the @samp{$((} form used for shell
16948 arithmetic. In traditional shells, @samp{((cat))} behaves like
16949 @samp{(cat)}; but many shells, including
16950 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16951 expression equivalent to @samp{let "cat"}, and may or may not report an
16952 error when they detect that @samp{cat} is not a number. As another
16953 example, @samp{pdksh} 5.2.14 does not treat the following code
16954 as a traditional shell would:
16957 if ((true) || false); then
16963 To work around this problem, insert a space between the two opening
16964 parentheses. There is a similar problem and workaround with
16965 @samp{$((}; see @ref{Shell Substitutions}.
16967 @node Special Shell Variables
16968 @section Special Shell Variables
16969 @cindex Shell variables
16970 @cindex Special shell variables
16972 Some shell variables should not be used, since they can have a deep
16973 influence on the behavior of the shell. In order to recover a sane
16974 behavior from the shell, some variables should be unset; M4sh takes
16975 care of this and provides fallback values, whenever needed, to cater
16976 for a very old @file{/bin/sh} that does not support @command{unset}.
16977 (@pxref{Portable Shell, , Portable Shell Programming}).
16979 As a general rule, shell variable names containing a lower-case letter
16980 are safe; you can define and use these variables without worrying about
16981 their effect on the underlying system, and without worrying about
16982 whether the shell changes them unexpectedly. (The exception is the
16983 shell variable @code{status}, as described below.)
16985 Here is a list of names that are known to cause trouble. This list is
16986 not exhaustive, but you should be safe if you avoid the name
16987 @code{status} and names containing only upper-case letters and
16990 @c Alphabetical order, case insensitive, 'A' before 'a'.
16993 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16994 , Limitations of Shell Builtins}). Not all shells manage @samp{$?}
16995 correctly in shell functions (@pxref{Shell Functions}) or in traps
16996 (@pxref{trap, , Limitations of Shell Builtins}). Not all shells reset
16997 @samp{$?} to zero after an empty command.
17000 $ @kbd{bash -c 'false; $empty; echo $?'}
17002 $ @kbd{zsh -c 'false; $empty; echo $?'}
17008 Many shells reserve @samp{$_} for various purposes, e.g., the name of
17009 the last command executed.
17013 When this variable is set it specifies a list of directories to search
17014 when invoking @code{cd} with a relative file name that did not start
17015 with @samp{./} or @samp{../}. POSIX
17016 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
17017 is used successfully, @code{cd} prints the resulting absolute
17018 file name. Unfortunately this output can break idioms like
17019 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
17020 Also, many shells do not conform to this part of POSIX; for
17021 example, @command{zsh} prints the result only if a directory name
17022 other than @file{.} was chosen from @env{CDPATH}.
17024 In practice the shells that have this problem also support
17025 @command{unset}, so you can work around the problem as follows:
17028 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
17031 You can also avoid output by ensuring that your directory name is
17032 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
17034 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
17035 possible, so you need not worry about this problem in those scripts.
17037 @item CLICOLOR_FORCE
17038 @evindex CLICOLOR_FORCE
17039 When this variable is set, some implementations of tools like
17040 @command{ls} attempt to add color to their output via terminal escape
17041 sequences, even when the output is not directed to a terminal, and can
17042 thus cause spurious failures in scripts. Configure scripts use M4sh,
17043 which automatically unsets this variable.
17047 In the MKS shell, case statements and file name generation are
17048 case-insensitive unless @env{DUALCASE} is nonzero.
17049 Autoconf-generated scripts export this variable when they start up.
17063 These variables should not matter for shell scripts, since they are
17064 supposed to affect only interactive shells. However, at least one
17065 shell (the pre-3.0 UWIN Korn shell) gets confused about
17066 whether it is interactive, which means that (for example) a @env{PS1}
17067 with a side effect can unexpectedly modify @samp{$?}. To work around
17068 this bug, M4sh scripts (including @file{configure} scripts) do something
17072 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
17079 (actually, there is some complication due to bugs in @command{unset};
17080 @pxref{unset, , Limitations of Shell Builtins}).
17084 The Korn shell uses @env{FPATH} to find shell functions, so avoid
17085 @env{FPATH} in portable scripts. @env{FPATH} is consulted after
17086 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
17087 to find whether a command exists, since they might report the wrong
17088 result if @env{FPATH} is also set.
17091 @evindex GREP_OPTIONS
17092 When this variable is set, some implementations of @command{grep} honor
17093 these options, even if the options include direction to enable colored
17094 output via terminal escape sequences, and the result can cause spurious
17095 failures when the output is not directed to a terminal. Configure
17096 scripts use M4sh, which automatically unsets this variable.
17100 Long ago, shell scripts inherited @env{IFS} from the environment,
17101 but this caused many problems so modern shells ignore any environment
17102 settings for @env{IFS}.
17104 Don't set the first character of @env{IFS} to backslash. Indeed,
17105 Bourne shells use the first character (backslash) when joining the
17106 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
17107 backslash escapes, so you can end up with backspace and other strange
17110 The proper value for @env{IFS} (in regular code, not when performing
17111 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}. The first character is
17112 especially important, as it is used to join the arguments in @samp{$*};
17113 however, note that traditional shells, but also bash-2.04, fail to adhere
17114 to this and join with a space anyway.
17116 M4sh guarantees that @env{IFS} will have the default value at the
17117 beginning of a script, and many macros within autoconf rely on this
17118 setting. It is okay to use blocks of shell code that temporarily change
17119 the value of @env{IFS} in order to split on another character, but
17120 remember to restore it before expanding further macros.
17122 Unsetting @code{IFS} instead of resetting it to the default sequence
17123 is not suggested, since code that tries to save and restore the
17124 variable's value will incorrectly reset it to an empty value, thus
17125 disabling field splitting:
17129 # default separators used for field splitting
17135 # no field splitting performed
17148 @evindex LC_COLLATE
17150 @evindex LC_MESSAGES
17151 @evindex LC_MONETARY
17152 @evindex LC_NUMERIC
17155 You should set all these variables to @samp{C} because so much
17156 configuration code assumes the C locale and POSIX requires that locale
17157 environment variables be set to @samp{C} if the C locale is desired;
17158 @file{configure} scripts and M4sh do that for you.
17159 Export these variables after setting them.
17164 @env{LANGUAGE} is not specified by POSIX, but it is a GNU
17165 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
17169 @itemx LC_IDENTIFICATION
17170 @itemx LC_MEASUREMENT
17173 @itemx LC_TELEPHONE
17174 @evindex LC_ADDRESS
17175 @evindex LC_IDENTIFICATION
17176 @evindex LC_MEASUREMENT
17179 @evindex LC_TELEPHONE
17181 These locale environment variables are GNU extensions. They
17182 are treated like their POSIX brethren (@env{LC_COLLATE},
17183 etc.)@: as described above.
17187 Most modern shells provide the current line number in @code{LINENO}.
17188 Its value is the line number of the beginning of the current command.
17189 M4sh, and hence Autoconf, attempts to execute @command{configure} with
17190 a shell that supports @code{LINENO}. If no such shell is available, it
17191 attempts to implement @code{LINENO} with a Sed prepass that replaces each
17192 instance of the string @code{$LINENO} (not followed by an alphanumeric
17193 character) with the line's number. In M4sh scripts you should execute
17194 @code{AS_LINENO_PREPARE} so that these workarounds are included in
17195 your script; configure scripts do this automatically in @code{AC_INIT}.
17197 You should not rely on @code{LINENO} within @command{eval} or shell
17198 functions, as the behavior differs in practice. The presence of a
17199 quoted newline within simple commands can alter which line number is
17200 used as the starting point for @code{$LINENO} substitutions within that
17201 command. Also, the possibility of the Sed prepass means that you should
17202 not rely on @code{$LINENO} when quoted, when in here-documents, or when
17203 line continuations are used. Subshells should be OK, though. In the
17204 following example, lines 1, 9, and 14 are portable, but the other
17205 instances of @code{$LINENO} do not have deterministic values:
17218 ( echo 9. $LINENO )
17219 eval 'echo 10. $LINENO'
17220 eval 'echo 11. $LINENO
17225 f () @{ echo $1 $LINENO;
17232 $ @kbd{bash-3.2 ./lineno}
17251 $ @kbd{zsh-4.3.4 ./lineno}
17270 $ @kbd{pdksh-5.2.14 ./lineno}
17289 $ @kbd{sed '=' <lineno |}
17295 > @kbd{ s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17298 > @kbd{ s,^[0-9]*\n,,}
17320 In particular, note that @file{config.status} (and any other subsidiary
17321 script created by @code{AS_INIT_GENERATED}) might report line numbers
17322 relative to the parent script as a result of the potential Sed pass.
17326 When executing the command @samp{>foo}, @command{zsh} executes
17327 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17328 compatibility mode and the @command{zsh} version is newer
17329 than 3.1.6-dev-18. If you are using an older @command{zsh}
17330 and forget to set @env{NULLCMD},
17331 your script might be suspended waiting for data on its standard input.
17335 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17336 array even after @code{emulate sh}, so it should not be used.
17338 @item PATH_SEPARATOR
17339 @evindex PATH_SEPARATOR
17340 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17341 variable can be set to either @samp{:} or @samp{;} to control the path
17342 separator Bash uses to set up certain environment variables (such as
17343 @env{PATH}). You can set this variable to @samp{;} if you want
17344 @command{configure} to use @samp{;} as a separator; this might be useful
17345 if you plan to use non-POSIX shells to execute files. @xref{File System
17346 Conventions}, for more information about @code{PATH_SEPARATOR}.
17348 @item POSIXLY_CORRECT
17349 @evindex POSIXLY_CORRECT
17350 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17351 (even empty) causes programs to try harder to conform to POSIX.
17352 Autoconf does not directly manipulate this variable, but @command{bash}
17353 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17354 running in POSIX mode. Therefore, take care when exporting or unsetting
17355 this variable, so as not to change whether @command{bash} is in POSIX
17359 $ @kbd{bash --posix -c 'set -o | grep posix}
17360 > @kbd{unset POSIXLY_CORRECT}
17361 > @kbd{set -o | grep posix'}
17368 POSIX 1003.1-2001 requires that @command{cd} and
17369 @command{pwd} must update the @env{PWD} environment variable to point
17370 to the logical name of the current directory, but traditional shells
17371 do not support this. This can cause confusion if one shell instance
17372 maintains @env{PWD} but a subsidiary and different shell does not know
17373 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17374 points to the wrong directory. Use @samp{`pwd`} rather than
17379 Many shells provide @code{RANDOM}, a variable that returns a different
17380 integer each time it is used. It is common
17381 practice to use @code{$RANDOM} as part of a file name, but code
17382 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17386 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17387 hence read-only. Do not use it.
17390 @node Shell Functions
17391 @section Shell Functions
17392 @cindex Shell Functions
17394 Nowadays, it is difficult to find a shell that does not support
17395 shell functions at all. However, some differences should be expected.
17397 When declaring a shell function, you must include whitespace between the
17398 @samp{)} after the function name and the start of the compound
17399 expression, to avoid upsetting @command{ksh}. While it is possible to
17400 use any compound command, most scripts use @samp{@{@dots{}@}}.
17403 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17405 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17406 ksh: syntax error at line 1: `@}' unexpected
17407 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17411 Inside a shell function, you should not rely on the error status of a
17412 subshell if the last command of that subshell was @code{exit} or
17413 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17414 find a shell that does not exhibit the bug, zsh might be the only shell
17415 present on the user's machine.
17417 Likewise, the state of @samp{$?} is not reliable when entering a shell
17418 function. This has the effect that using a function as the first
17419 command in a @command{trap} handler can cause problems.
17422 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17425 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17430 DJGPP bash 2.04 has a bug in that @command{return} from a
17431 shell function which also used a command substitution causes a
17432 segmentation fault. To work around the issue, you can use
17433 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17434 in the execution flow of the function (@pxref{Common Shell Constructs}).
17436 Not all shells treat shell functions as simple commands impacted by
17437 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17440 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17441 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17445 Shell variables and functions may share the same namespace, for example
17446 with Solaris 10 @command{/bin/sh}:
17449 $ @kbd{f () @{ :; @}; f=; f}
17454 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17455 uses the prefix @samp{as_fn_} for its functions.
17457 Handling of positional parameters and shell options varies among shells.
17458 For example, Korn shells reset and restore trace output (@samp{set -x})
17459 and other options upon function entry and exit.
17461 It is not portable to pass temporary environment variables to shell
17462 functions. Solaris 10 @command{/bin/sh} does not see the variable.
17463 Meanwhile, not all shells follow the POSIX rule that the assignment must
17464 affect the current environment in the same manner as special built-ins.
17467 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17470 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17473 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17478 Some ancient Bourne shell variants with function support did not reset
17479 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17480 arguments of the script were lost after the first function invocation.
17481 It is probably not worth worrying about these shells any more.
17483 With AIX sh, a @command{trap} on 0 installed in a shell function
17484 triggers at function exit rather than at script exit. @xref{trap, ,
17485 Limitations of Shell Builtins}.
17487 @node Limitations of Builtins
17488 @section Limitations of Shell Builtins
17489 @cindex Shell builtins
17490 @cindex Limitations of shell builtins
17492 No, no, we are serious: some shells do have limitations! :)
17494 You should always keep in mind that any builtin or command may support
17495 options, and therefore differ in behavior with arguments
17496 starting with a dash. For instance, even the innocent @samp{echo "$word"}
17497 can give unexpected results when @code{word} starts with a dash. To avoid
17498 this problem, use @samp{printf '%s\n' "$word"}. Many of these limitations
17499 can be worked around using M4sh (@pxref{Programming in M4sh}).
17501 @c This table includes things like '@command{test} (files)', so we can't
17502 @c use @table @command.
17506 @prindex @command{.}
17507 Use @command{.} only with regular files (use @samp{test -f}). Bash
17508 2.03, for instance, chokes on @samp{. /dev/null}. Remember that
17509 @command{.} uses @env{PATH} if its argument contains no slashes. Also,
17510 some shells, including bash 3.2, implicitly append the current directory
17511 to this @env{PATH} search, even though POSIX forbids it. So if you want
17512 to use @command{.} on a file @file{foo} in the current directory, you
17513 must use @samp{. ./foo}.
17515 Not all shells gracefully handle syntax errors within a sourced file.
17516 On one extreme, some non-interactive shells abort the entire script. On
17517 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17521 $ @kbd{echo 'fi' > syntax}
17522 $ @kbd{bash -c '. ./syntax; echo $?'}
17523 ./syntax: line 1: syntax error near unexpected token `fi'
17524 ./syntax: line 1: `fi'
17526 $ @kbd{ash -c '. ./syntax; echo $?'}
17527 ./syntax: 1: Syntax error: "fi" unexpected
17528 $ @kbd{zsh -c '. ./syntax; echo $?'}
17529 ./syntax:1: parse error near `fi'
17536 @prindex @command{!}
17537 The Unix version 7 shell did not support
17538 negating the exit status of commands with @command{!}, and this feature
17539 is still absent from some shells (e.g., Solaris 10 @command{/bin/sh}).
17540 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17541 bugs when using @command{!}:
17544 $ @kbd{sh -c '! : | :'; echo $?}
17546 $ @kbd{ash -c '! : | :'; echo $?}
17548 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17550 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17552 Syntax error: "@}" unexpected
17556 Shell code like this:
17559 if ! cmp file1 file2 >/dev/null 2>&1; then
17560 echo files differ or trouble
17564 is therefore not portable in practice. Typically it is easy to rewrite
17568 cmp file1 file2 >/dev/null 2>&1 ||
17569 echo files differ or trouble
17572 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17576 AS_IF([cmp -s file file.new], [],
17577 [echo files differ or trouble])
17580 This kind of rewriting is needed in code outside macro definitions that
17581 calls other macros. @xref{Common Shell Constructs}. It is also useful
17582 inside macro definitions, where the @dfn{then} and @dfn{else} branches
17583 might contain macro arguments.
17585 More generally, one can always rewrite @samp{! @var{command}} as:
17588 AS_IF([@var{command}], [(exit 1)])
17591 @item @command{&&} and @command{||}
17592 @c --------------------------------
17593 @prindex @command{&&}
17594 @prindex @command{||}
17595 If an AND-OR list is not inside @code{AC_DEFUN}, and it contains
17596 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
17597 @xref{Common Shell Constructs}. The operators @code{&&} and @code{||}
17598 have equal precedence and are left associative, so instead of:
17601 # This is dangerous outside AC_DEFUN.
17602 cmp a b >/dev/null 2>&1 &&
17603 AS_ECHO([files are same]) >$tmpfile ||
17604 AC_MSG_NOTICE([files differ, or echo failed])
17610 # This is OK outside AC_DEFUN.
17611 AS_IF([AS_IF([cmp a b >/dev/null 2>&1],
17612 [AS_ECHO([files are same]) >$tmpfile],
17614 [AC_MSG_NOTICE([files differ, or echo failed])])
17617 @item @command{@{...@}}
17618 @c --------------------
17619 @prindex @command{@{...@}}
17620 Bash 3.2 (and earlier versions) sometimes does not properly set
17621 @samp{$?} when failing to write redirected output of a compound command.
17622 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17623 not occur with @samp{(@dots{})}. For example:
17626 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17627 bash: line 1: /bad: Permission denied
17629 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17630 bash: line 1: /bad: Permission denied
17634 To work around the bug, prepend @samp{:;}:
17637 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17638 bash: line 1: /bad: Permission denied
17642 POSIX requires a syntax error if a brace list has no contents. However,
17643 not all shells obey this rule; and on shells where empty lists are
17644 permitted, the effect on @samp{$?} is inconsistent. To avoid problems,
17645 ensure that a brace list is never empty.
17648 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17649 bash: line 1: syntax error near unexpected token `@}'
17650 bash: line 1: `false; @{ @}; echo $?'
17652 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17654 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17659 @item @command{break}
17660 @c ------------------
17661 @prindex @command{break}
17662 The use of @samp{break 2} etc.@: is safe.
17666 @item @command{case}
17667 @c -----------------
17668 @prindex @command{case}
17669 If a @code{case} command is not inside @code{AC_DEFUN}, and it contains
17670 calls to Autoconf macros, it should be rewritten using @code{AS_CASE}.
17671 @xref{Common Shell Constructs}. Instead of:
17674 # This is dangerous outside AC_DEFUN.
17676 *.[ch]) AC_MSG_NOTICE([C source file]);;
17684 # This is OK outside AC_DEFUN.
17685 AS_CASE([$filename],
17686 [[*.[ch]]], [AC_MSG_NOTICE([C source file])])
17689 You don't need to quote the argument; no splitting is performed.
17691 You don't need the final @samp{;;}, but you should use it.
17693 POSIX requires support for @code{case} patterns with opening
17694 parentheses like this:
17698 (*.c) echo "C source code";;
17703 but the @code{(} in this example is not portable to a few obsolescent Bourne
17704 shell implementations, which is a pity for those of us using tools that
17705 rely on balanced parentheses. For instance, with Solaris 10
17709 $ @kbd{case foo in (foo) echo foo;; esac}
17710 @error{}syntax error: `(' unexpected
17714 The leading @samp{(} can be omitted safely. Unfortunately, there are
17715 contexts where unbalanced parentheses cause other problems, such as when
17716 using a syntax-highlighting editor that searches for the balancing
17717 counterpart, or more importantly, when using a case statement as an
17718 underquoted argument to an Autoconf macro. @xref{Balancing
17719 Parentheses}, for trade-offs involved in various styles of dealing with
17720 unbalanced @samp{)}.
17722 Zsh handles pattern fragments derived from parameter expansions or
17723 command substitutions as though quoted:
17726 $ pat=\?; case aa in ?$pat) echo match;; esac
17727 $ pat=\?; case a? in ?$pat) echo match;; esac
17732 Because of a bug in its @code{fnmatch}, Bash fails to properly
17733 handle backslashes in character classes:
17736 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17741 This is extremely unfortunate, since you are likely to use this code to
17742 handle POSIX or MS-DOS absolute file names. To work around this
17743 bug, always put the backslash first:
17746 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17748 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17752 Many Bourne shells cannot handle closing brackets in character classes
17755 Some shells also have problems with backslash escaping in case you do not want
17756 to match the backslash: both a backslash and the escaped character match this
17757 pattern. To work around this, specify the character class in a variable, so
17758 that quote removal does not apply afterwards, and the special characters don't
17759 have to be backslash-escaped:
17762 $ @kbd{case '\' in [\<]) echo OK;; esac}
17764 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17768 Even with this, Solaris @command{ksh} matches a backslash if the set
17770 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17772 Some shells, such as Ash 0.3.8, are confused by an empty
17773 @code{case}/@code{esac}:
17776 ash-0.3.8 $ @kbd{case foo in esac;}
17777 @error{}Syntax error: ";" unexpected (expecting ")")
17780 POSIX requires @command{case} to give an exit status of 0 if no cases
17781 match. However, @command{/bin/sh} in Solaris 10 does not obey this
17782 rule. Meanwhile, it is unclear whether a case that matches, but
17783 contains no statements, must also change the exit status to 0. The M4sh
17784 macro @code{AS_CASE} works around these inconsistencies.
17787 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17789 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17796 @prindex @command{cd}
17797 POSIX 1003.1-2001 requires that @command{cd} must support
17798 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17799 with @option{-L} being the default. However, traditional shells do
17800 not support these options, and their @command{cd} command has the
17801 @option{-P} behavior.
17803 Portable scripts should assume neither option is supported, and should
17804 assume neither behavior is the default. This can be a bit tricky,
17805 since the POSIX default behavior means that, for example,
17806 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17807 the current logical directory is a symbolic link. It is safe to use
17808 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17809 Also, Autoconf-generated scripts check for this problem when computing
17810 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17811 so it is safe to @command{cd} to these variables.
17813 POSIX states that behavior is undefined if @command{cd} is given an
17814 explicit empty argument. Some shells do nothing, some change to the
17815 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17816 the shell rather than returning an error. Unfortunately, this means
17817 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17818 than @samp{cd $var} (at least the latter is well-behaved in all shells
17819 at changing to @env{HOME}, although this is probably not what you wanted
17820 in a script). You should check that a directory name was supplied
17821 before trying to change locations.
17823 @xref{Special Shell Variables}, for portability problems involving
17824 @command{cd} and the @env{CDPATH} environment variable.
17825 Also please see the discussion of the @command{pwd} command.
17829 @item @command{echo}
17830 @c -----------------
17831 @prindex @command{echo}
17832 The simple @command{echo} is probably the most surprising source of
17833 portability troubles. It is not possible to use @samp{echo} portably
17834 unless both options and escape sequences are omitted.
17836 Do not use options, as some shells support them and others do not.
17837 For example, POSIX says that the behavior of @samp{echo -n foo} is
17838 implementation-defined. On some platforms the output is @samp{foo}
17839 without a trailing newline, on others it is @samp{-n foo} with a
17840 trailing newline, and POSIX allows even other behavior.
17842 Do not use backslashes in the arguments, as there is no consensus on
17843 their handling. For @samp{echo '\n' | wc -l}, the @command{sh} of
17844 Solaris 10 outputs 2,
17845 but Bash and Zsh (in @command{sh} emulation mode) output 1.
17846 The problem is truly @command{echo}: all the shells
17847 understand @samp{'\n'} as the string composed of a backslash and an
17850 Because of these problems, do not pass a string containing arbitrary
17851 characters to @command{echo}. For example, @samp{echo "$foo"} is safe
17852 only if you know that @var{foo}'s value cannot contain backslashes and
17853 cannot start with @samp{-}.
17855 Normally, @command{printf} is safer and easier to use than @command{echo}
17856 and @command{echo -n}. Thus, you should use @command{printf '%s\n'}
17857 instead of @command{echo}, and similarly use @command{printf %s} instead
17858 of @command{echo -n}.
17860 Older scripts, written before @command{printf} was portable,
17861 sometimes used a here-document as a safer alternative to @command{echo},
17871 However, this usage is problematic, as even some modern shells have
17872 hard-to-reproduce bugs when dealing with here-documents.
17875 @item @command{eval}
17876 @c -----------------
17877 @prindex @command{eval}
17878 The @command{eval} command is useful in limited circumstances, e.g.,
17879 using commands like @samp{eval table_$key=\$value} and @samp{eval
17880 value=table_$key} to simulate a hash table when the key is known to be
17883 You should also be wary of common bugs in @command{eval} implementations.
17884 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17885 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17886 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17887 @samp{$?} is 0, so they exhibit behavior like this:
17890 $ @kbd{false; eval 'echo $?'}
17894 The correct behavior here is to output a nonzero value,
17895 but portable scripts should not rely on this.
17897 You should not rely on @code{LINENO} within @command{eval}.
17898 @xref{Special Shell Variables}.
17900 Note that, even though these bugs are easily avoided,
17901 @command{eval} is tricky to use on arbitrary arguments.
17902 It is obviously unwise to use @samp{eval $cmd} if the string value of
17903 @samp{cmd} was derived from an untrustworthy source. But even if the
17904 string value is valid, @samp{eval $cmd} might not work as intended,
17905 since it causes field splitting and file name expansion to occur twice,
17906 once for the @command{eval} and once for the command itself. It is
17907 therefore safer to use @samp{eval "$cmd"}. For example, if @var{cmd}
17908 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17909 equivalent of @samp{cat test;.c} if there happens to be a file named
17910 @file{test;.c} in the current directory; and this in turn
17911 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17912 then execute the command @command{.c}. To avoid this problem, use
17913 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17915 However, suppose that you want to output the text of the evaluated
17916 command just before executing it. Assuming the previous example,
17917 @samp{printf '%s\n' "Executing: $cmd"} outputs @samp{Executing: cat test?.c},
17918 but this output doesn't show the user that @samp{test;.c} is the actual
17919 name of the copied file.
17920 Conversely, @samp{printf 'Executing:'; eval "printf ' %s' $cmd"; printf '\n'}
17921 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17922 since it mistakenly replaces the contents of @file{bar} by the
17923 string @samp{ cat foo}. No simple, general, and portable solution to
17924 this problem is known.
17926 @item @command{exec}
17927 @c -----------------
17928 @prindex @command{exec}
17929 POSIX describes several categories of shell built-ins. Special
17930 built-ins (such as @command{exit}) must impact the environment of the
17931 current shell, and need not be available through @command{exec}. All
17932 other built-ins are regular, and must not propagate variable assignments
17933 to the environment of the current shell. However, the group of regular
17934 built-ins is further distinguished by commands that do not require a
17935 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17936 are offered as a more efficient version of something that must still be
17937 found in a @env{PATH} search (such as @command{echo}). POSIX is not
17938 clear on whether @command{exec} must work with the list of 17 utilities
17939 that are invoked without a @env{PATH} search, and many platforms lack an
17940 executable for some of those built-ins:
17943 $ @kbd{sh -c 'exec cd /tmp'}
17944 sh: line 0: exec: cd: not found
17947 All other built-ins that provide utilities specified by POSIX must have
17948 a counterpart executable that exists on @env{PATH}, although POSIX
17949 allows @command{exec} to use the built-in instead of the executable.
17950 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17953 $ @kbd{bash -c 'pwd --version' | head -n1}
17954 bash: line 0: pwd: --: invalid option
17955 pwd: usage: pwd [-LP]
17956 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17957 pwd (GNU coreutils) 6.10
17958 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17959 pdksh: pwd: --: unknown option
17962 When it is desired to avoid a regular shell built-in, the workaround is
17963 to use some other forwarding command, such as @command{env} or
17964 @command{nice}, that will ensure a path search:
17967 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17968 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17969 true (GNU coreutils) 6.10
17970 $ @kbd{pdksh -c 'env true --version' | head -n1}
17971 true (GNU coreutils) 6.10
17974 @item @command{exit}
17975 @c -----------------
17976 @prindex @command{exit}
17977 The default value of @command{exit} is supposed to be @code{$?};
17978 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17979 perform @samp{exit 0}.
17982 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17984 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17986 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17990 Using @samp{exit $?} restores the expected behavior.
17992 Some shell scripts, such as those generated by @command{autoconf}, use a
17993 trap to clean up before exiting. If the last shell command exited with
17994 nonzero status, the trap also exits with nonzero status so that the
17995 invoker can tell that an error occurred.
17997 Unfortunately, in some shells, such as Solaris 10 @command{/bin/sh}, an exit
17998 trap ignores the @code{exit} command's argument. In these shells, a trap
17999 cannot determine whether it was invoked by plain @code{exit} or by
18000 @code{exit 1}. Instead of calling @code{exit} directly, use the
18001 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
18005 @item @command{export}
18006 @c -------------------
18007 @prindex @command{export}
18008 The builtin @command{export} dubs a shell variable @dfn{environment
18009 variable}. Each update of exported variables corresponds to an update
18010 of the environment variables. Conversely, each environment variable
18011 received by the shell when it is launched should be imported as a shell
18012 variable marked as exported.
18014 Alas, some older shells, such as Solaris 10 @command{/bin/sh}, forget to
18015 @command{export} the environment variables they receive. As a result,
18016 two variables coexist: the environment variable and the shell
18017 variable. The following code demonstrates this failure:
18028 when run with @samp{FOO=foo} in the environment, these shells print
18029 alternately @samp{foo} and @samp{bar}, although they should print only
18030 @samp{foo} and then a sequence of @samp{bar}s.
18032 Therefore you should @command{export} again each environment variable
18033 that you update; the export can occur before or after the assignment.
18035 POSIX is not clear on whether the @command{export} of an undefined
18036 variable causes the variable to be defined with the value of an empty
18037 string, or merely marks any future definition of a variable by that name
18038 for export. Various shells behave differently in this regard:
18041 $ @kbd{sh -c 'export foo; env | grep foo'}
18042 $ @kbd{ash -c 'export foo; env | grep foo'}
18046 POSIX requires @command{export} to honor assignments made as arguments,
18047 but older shells do not support this, including @command{/bin/sh} in
18048 Solaris 10. Portable scripts should separate assignments and exports
18049 into different statements.
18052 $ @kbd{bash -c 'export foo=bar; echo $foo'}
18054 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
18055 /bin/sh: foo=bar: is not an identifier
18056 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
18060 POSIX requires @command{export} to work with any arbitrary value for the
18061 contents of the variable being exported, as long as the total size of
18062 the environment combined with arguments doesn't exceed @code{ARG_MAX}
18063 when executing a child process. However, some shells have extensions
18064 that involve interpreting some environment values specially, regardless
18065 of the variable name. We currently know of one case: all versions of
18066 Bash released prior to 27 September 2014 interpret an environment
18067 variable with an initial content substring of @code{() @{} as an
18068 exported function definition (this is the ``Shellshock'' remote
18069 execution bug, CVE-2014-6271 and friends, where it was possible to
18070 exploit the function parser to cause remote code execution on child bash
18071 startup; newer versions of Bash use special environment variable
18072 @emph{names} instead of values to implement the same feature).
18074 There may be entries inherited into the environment that are not valid
18075 as shell variable names; POSIX states that processes should be tolerant
18076 of these names. Some shells such as @command{dash} do this by removing
18077 those names from the environment at startup, while others such as
18078 @command{bash} hide the entry from shell access but still pass it on to
18079 child processes. While you can set such names using @command{env} for a
18080 direct child process, you cannot rely on them being preserved through an
18081 intermediate pass through the shell.
18083 @item @command{false}
18084 @c ------------------
18085 @prindex @command{false}
18086 Don't expect @command{false} to exit with status 1: in native
18087 Solaris @file{/bin/false} exits with status 255.
18090 @item @command{for}
18091 @c ----------------
18092 @prindex @command{for}
18093 To loop over positional arguments, use:
18098 printf '%s\n' "$arg"
18103 You may @emph{not} leave the @code{do} on the same line as @code{for},
18104 since some shells improperly grok:
18108 printf '%s\n' "$arg"
18112 If you want to explicitly refer to the positional arguments, use:
18115 for arg in "$@@"; do
18116 printf '%s\n' "$arg"
18120 POSIX requires support for a @command{for} loop with no list after
18121 @code{in}. However, Solaris 10 @command{/bin/sh} treats that as a syntax
18122 error. It is possible to work around this by providing any shell word
18123 that expands to nothing, or by ignoring an obvious sentinel.
18126 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
18127 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
18128 /bin/sh: syntax error at line 1: `;' unexpected
18131 This syntax problem is most frequently encountered in code that goes
18132 through several layers of expansion, such as an m4 macro or makefile
18133 variable used as a list body, where the first layer of expansion (m4 or
18134 make) can end up expanding to nothing in the version handed to the
18135 shell. In the makefile context, one common workaround is to use a shell
18136 variable rather than a make variable as the source of the list.
18139 $ @kbd{cat Makefile}
18142 @@for arg in $(list); do \
18143 printf '%s\n' $$arg; \
18146 @@list='$(list)'; \
18147 for arg in $$list; do \
18148 printf '%s\n' $$arg; \
18150 $ @kbd{make bad 2&>1 | head -n1}
18151 sh: syntax error at line 1: `;' unexpected
18152 $ @kbd{make bad list='a b'}
18156 $ @kbd{make good list='a b'}
18161 In Solaris 10 @command{/bin/sh}, when the list of arguments of a
18162 @command{for} loop starts with @emph{unquoted} tokens looking like
18163 variable assignments, the loop is not executed on those tokens:
18166 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
18172 Thankfully, quoting the assignment-like tokens, or starting the list
18173 with other tokens (including unquoted variable expansion that results in
18174 an assignment-like result), avoids the problem, so it is easy to work
18178 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
18180 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
18188 @prindex @command{if}
18189 If an @code{if} command is not inside @code{AC_DEFUN}, and it contains
18190 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
18191 @xref{Common Shell Constructs}.
18193 Using @code{if ! @dots{}} is not portable. @xref{!,,@command{!} notes}.
18195 Some very old shells did not reset the exit status from an @command{if}
18196 with no @command{else}:
18199 $ @kbd{if (exit 42); then true; fi; echo $?}
18204 whereas a proper shell should have printed @samp{0}. Although this is no
18205 longer a portability problem, as any shell that supports functions gets it
18206 correct, it explains why some makefiles have lengthy
18210 if test -f "$file"; then
18211 install "$file" "$dest"
18218 @item @command{printf}
18219 @c ------------------
18220 @prindex @command{printf}
18221 A format string starting with a @samp{-} can cause problems.
18222 Bash interprets it as an option and
18223 gives an error. And @samp{--} to mark the end of options is not good
18224 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
18225 literally as the format string. Putting the @samp{-} in a @samp{%c}
18226 or @samp{%s} is probably easiest:
18232 AIX 7.2 @command{sh} mishandles octal escapes in multi-byte locales by
18233 treating them as characters instead of bytes. For example, in a locale
18234 using the UTF-8 encoding, @samp{printf '\351'} outputs the two bytes C3,
18235 A9 (the UTF-8 encoding for U+00E9) instead of the desired single byte E9.
18236 To work around the bug, use the C locale.
18238 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
18241 $ @kbd{printf '\045'}
18242 bash: printf: `%': missing format character
18245 Large outputs may cause trouble. On Solaris 10, for
18246 example, @file{/usr/bin/printf} is buggy, so when using
18247 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18250 Since @command{printf} is not always a shell builtin, there is a
18251 potential speed penalty for using @code{printf '%s\n'} as a replacement
18252 for an @command{echo} that does not interpret @samp{\} or leading
18253 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18254 -r --} for this role instead.
18256 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18257 portable alternatives to both @command{printf} and @command{echo}.
18260 @item @command{pwd}
18261 @c ----------------
18262 @prindex @command{pwd}
18263 With modern shells, plain @command{pwd} outputs a ``logical''
18264 directory name, some of whose components may be symbolic links. These
18265 directory names are in contrast to ``physical'' directory names, whose
18266 components are all directories.
18268 POSIX 1003.1-2001 requires that @command{pwd} must support
18269 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18270 with @option{-L} being the default. However, traditional shells do
18271 not support these options, and their @command{pwd} command has the
18272 @option{-P} behavior.
18274 Portable scripts should assume neither option is supported, and should
18275 assume neither behavior is the default. Also, on many hosts
18276 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but POSIX
18277 does not require this behavior and portable scripts should not rely on
18280 Typically it's best to use plain @command{pwd}. On modern hosts this
18281 outputs logical directory names, which have the following advantages:
18285 Logical names are what the user specified.
18287 Physical names may not be portable from one installation
18288 host to another due to network file system gymnastics.
18290 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18291 some parent directory, but plain @command{pwd} cannot fail for this
18295 Also please see the discussion of the @command{cd} command.
18298 @item @command{read}
18299 @c -----------------
18300 @prindex @command{read}
18301 No options are portable, not even support @option{-r} (Solaris 10
18302 @command{/bin/sh} for example).
18306 @item @command{set}
18307 @c ----------------
18308 @prindex @command{set}
18309 With the FreeBSD 6.0 shell, the @command{set} command (without
18310 any options) does not sort its output.
18312 The @command{set} builtin faces the usual problem with arguments
18314 dash. Modern shells such as Bash or Zsh understand @option{--} to specify
18315 the end of the options (any argument after @option{--} is a parameter,
18316 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18317 10 @command{/bin/sh}) simply stop option
18318 processing as soon as a non-option argument is found. Therefore, use
18319 @samp{dummy} or simply @samp{x} to end the option processing, and use
18320 @command{shift} to pop it out:
18323 set x $my_list; shift
18326 Avoid @samp{set -}, e.g., @samp{set - $my_list}. POSIX no
18327 longer requires support for this command, and in traditional shells
18328 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18329 makes scripts harder to debug.
18331 Some nonstandard shells do not recognize more than one option
18332 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line). It is
18333 better to combine them:
18339 @cindex @command{set -e}
18340 The @option{-e} option has historically been under-specified, with enough
18341 ambiguities to cause numerous differences across various shell
18342 implementations; see for example
18343 @uref{https://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18344 or @uref{https://www.austingroupbugs.net/@/view.php?id=52, this link},
18345 documenting a change to POSIX 2008 to match @command{ksh88} behavior.
18346 Note that mixing @code{set -e} and shell functions is asking for surprises:
18359 According to the recommendation, @samp{one} should always be output
18360 regardless of whether the @command{rm} failed, because it occurs within
18361 the body of the shell function @samp{doit} invoked on the left side of
18362 @samp{||}, where the effects of @samp{set -e} are not enforced.
18363 Likewise, @samp{two} should never be printed, since the failure of
18364 @command{rm} does not abort the function, such that the status of
18367 The BSD shell has had several problems with the @option{-e}
18368 option. Older versions of the BSD
18369 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18370 @samp{case} when @option{-e} was in effect, causing the shell to exit
18371 unexpectedly in some cases. This was particularly a problem with
18372 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18373 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18374 wrapper works around the bug (@pxref{Failure in Make Rules}).
18376 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18377 wrongly exit with @option{-e} if the last command within a compound
18378 statement fails and is guarded by an @samp{&&} only. For example:
18384 test -n "$foo" && exit 1
18387 test -n "$foo" && exit 1
18389 test -n "$foo" && exit 1
18395 does not print @samp{three}. One workaround is to change the last
18396 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18397 "$foo"; then exit 1; fi} instead. Another possibility is to warn BSD
18398 users not to use @samp{sh -e}.
18400 When @samp{set -e} is in effect, a failed command substitution in
18401 Solaris 10 @command{/bin/sh} cannot be ignored, even with @samp{||}.
18404 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18405 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18411 Moreover, a command substitution, successful or not, causes this shell to
18412 exit from a failing outer command even in presence of an @samp{&&} list:
18415 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18417 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18421 @cindex @command{set -b}
18422 @cindex @command{set -m}
18423 Job control is not provided by all shells, so the use of @samp{set -m}
18424 or @samp{set -b} must be done with care. When using @command{zsh} in
18425 native mode, asynchronous notification (@samp{set -b}) is enabled by
18426 default, and using @samp{emulate sh} to switch to POSIX mode does not
18427 clear this setting (although asynchronous notification has no impact
18428 unless job monitoring is also enabled). Also, @command{zsh} 4.3.10 and
18429 earlier have a bug where job control can be manipulated in interactive
18430 shells, but not in subshells or scripts. Furthermore, some shells, like
18431 @command{pdksh}, fail to treat subshells as interactive, even though the
18435 $ @kbd{echo $ZSH_VERSION}
18437 $ @kbd{set -m; echo $?}
18439 $ @kbd{zsh -c 'set -m; echo $?'}
18440 set: can't change option: -m
18441 $ @kbd{(set -m); echo $?}
18442 set: can't change option: -m
18444 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18449 @cindex @command{set -n}
18450 Use of @command{set -n} (typically via @command{sh -n script}) to
18451 validate a script is not foolproof. Modern @command{ksh93} tries to be
18452 helpful by informing you about better syntax, but switching the script
18453 to use the suggested syntax in order to silence the warnings would
18454 render the script no longer portable to older shells:
18457 $ @kbd{ksh -nc '``'}
18458 ksh: warning: line 1: `...` obsolete, use $(...)
18463 itself uses @command{sh -n} within its testsuite to check that correct
18464 scripts were generated, but only after first probing for other shell
18465 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18466 a reasonably fast and working implementation.
18468 @item @command{shift}
18469 @c ------------------
18470 @prindex @command{shift}
18471 Not only is @command{shift}ing a bad idea when there is nothing left to
18472 shift, but in addition it is not portable: the shell of MIPS
18473 RISC/OS 4.52 refuses to do it.
18475 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18476 it is also absent in many pre-POSIX shells.
18479 @item @command{source}
18480 @c -------------------
18481 @prindex @command{source}
18482 This command is not portable, as POSIX does not require it; use
18483 @command{.} instead.
18486 @item @command{test}
18487 @c -----------------
18488 @prindex @command{test}
18489 The @code{test} program is the way to perform many file and string
18490 tests. It is often invoked by the alternate name @samp{[}, but using
18491 that name in Autoconf code is asking for trouble since it is an M4 quote
18494 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18495 present in all implementations, and have been marked obsolete by POSIX
18496 2008. This is because there are inherent ambiguities in using them.
18497 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18498 check whether two strings are both non-empty, but if @samp{$1} is the
18499 literal @samp{!}, then some implementations of @command{test} treat it
18500 as a negation of the unary operator @option{-a}.
18502 Thus, portable uses of @command{test} should never have more than four
18503 arguments, and scripts should use shell constructs like @samp{&&} and
18504 @samp{||} instead. If you combine @samp{&&} and @samp{||} in the same
18505 statement, keep in mind that they have equal precedence, so it is often
18506 better to parenthesize even when this is redundant. For example:
18510 test "X$a" = "X$b" -a \
18511 '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18514 test "X$a" = "X$b" &&
18515 @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18518 @command{test} does not process options like most other commands do; for
18519 example, it does not recognize the @option{--} argument as marking the
18522 It is safe to use @samp{!} as a @command{test} operator. For example,
18523 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18524 -d foo; @dots{}} is not.
18527 @item @command{test} (files)
18528 @c -------------------------
18529 To enable @command{configure} scripts to support cross-compilation, they
18530 shouldn't do anything that tests features of the build system instead of
18531 the host system. But occasionally you may find it necessary to check
18532 whether some arbitrary file exists. To do so, use @samp{test -f},
18533 @samp{test -r}, or @samp{test -x}. Do not use @samp{test -e}, because
18534 Solaris 10 @command{/bin/sh}
18535 lacks it. To test for symbolic links on systems that have them, use
18536 @samp{test -h} rather than @samp{test -L}; either form conforms to
18537 POSIX 1003.1-2001, but @option{-h} has been around longer.
18539 For historical reasons, POSIX reluctantly allows implementations of
18540 @samp{test -x} that will succeed for the root user, even if no execute
18541 permissions are present. Furthermore, shells do not all agree on
18542 whether Access Control Lists should affect @samp{test -r}, @samp{test
18543 -w}, and @samp{test -x}; some shells base test results strictly on the
18544 current user id compared to file owner and mode, as if by
18545 @code{stat(2)}; while other shells base test results on whether the
18546 current user has the given right, even if that right is only granted by
18547 an ACL, as if by @code{faccessat(2)}. Furthermore, there is a classic
18548 time of check to time of use race between any use of @command{test}
18549 followed by operating on the just-checked file. Therefore, it is a good
18550 idea to write scripts that actually attempt an operation, and are
18551 prepared for the resulting failure if permission is denied, rather than
18552 trying to avoid an operation based solely on whether @command{test}
18553 guessed that it might not be permitted.
18555 @item @command{test} (strings)
18556 @c ---------------------------
18557 POSIX says that @samp{test "@var{string}"} succeeds if @var{string} is
18558 not null, but this usage is not portable to traditional platforms like
18559 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18560 @samp{-n}. However, it @emph{is} portable to test if a variable is set
18561 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18562 implementations properly distinguish between no arguments and a
18563 known-safe string of @samp{y}.
18565 POSIX also says that @samp{test ! "@var{string}"},
18566 @samp{test -n "@var{string}"} and
18567 @samp{test -z "@var{string}"} work with any string, but many
18568 shells (such as Solaris 10, AIX 3.2, UNICOS 10.0.0.6,
18569 Digital Unix 4, etc.)@: get confused if
18570 @var{string} looks like an operator:
18574 test: argument expected
18576 test: argument expected
18577 $ @kbd{test -z ")"; echo $?}
18581 Similarly, POSIX says that both @samp{test "@var{string1}" = "@var{string2"}}
18582 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18583 strings, but in practice this is not true for troublesome strings that
18584 look like operators or parentheses, or that begin with @samp{-}.
18586 It is best to protect such strings with a leading @samp{X}, e.g.,
18587 @samp{test "X@var{string}" != X} rather than @samp{test -n
18588 "@var{string}"} or @samp{test ! "@var{string}"}.
18590 It is common to find variations of the following idiom:
18593 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18598 to take an action when a token matches a given pattern. Such constructs
18599 should be avoided by using:
18602 AS_CASE([$ac_feature],
18603 [[*[!-a-zA-Z0-9_]*]], [@var{action}])
18606 If the pattern is a complicated regular expression that cannot be
18607 expressed as a shell pattern, use something like this instead:
18610 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18614 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18615 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18616 @samp{@var{foo}} contains backslashes.
18620 @item @command{trap}
18621 @c -----------------
18622 @prindex @command{trap}
18623 It is safe to trap at least the signals 1, 2, 13, and 15. You can also
18624 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18625 explicit @command{exit}, or the end of the script). The trap for 0 should be
18626 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18627 will invoke the trap at the end of this function.
18629 POSIX says that @samp{trap - 1 2 13 15} resets the traps for the
18630 specified signals to their default values, but many common shells (e.g.,
18631 Solaris 10 @command{/bin/sh}) misinterpret this and attempt to execute a
18632 ``command'' named @command{-} when the specified conditions arise.
18633 POSIX 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18634 reset traps, as this is supported by a larger set of shells, but there
18635 are still shells like @command{dash} that mistakenly try to execute
18636 @command{1} instead of resetting the traps. Therefore, there is no
18637 portable workaround, except for @samp{trap - 0}, for which
18638 @samp{trap '' 0} is a portable substitute.
18640 Although POSIX is not absolutely clear on this point, it is widely
18641 admitted that when entering the trap @samp{$?} should be set to the exit
18642 status of the last command run before the trap. The ambiguity can be
18643 summarized as: ``when the trap is launched by an @command{exit}, what is
18644 the @emph{last} command run: that before @command{exit}, or
18645 @command{exit} itself?''
18647 Bash considers @command{exit} to be the last command, while Zsh and
18648 Solaris 10 @command{/bin/sh} consider that when the trap is run it is
18649 @emph{still} in the @command{exit}, hence it is the previous exit status
18650 that the trap receives:
18653 $ @kbd{cat trap.sh}
18656 $ @kbd{zsh trap.sh}
18658 $ @kbd{bash trap.sh}
18662 The portable solution is then simple: when you want to @samp{exit 42},
18663 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18664 set the exit status to 42 for Zsh, and the second to trigger the trap
18665 and pass 42 as exit status for Bash. In M4sh, this is covered by using
18668 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18669 reset to 0 by empty lines if the code is inside @command{trap}.
18672 $ @kbd{trap 'false}
18680 Fortunately, this bug only affects @command{trap}.
18682 Several shells fail to execute an exit trap that is defined inside a
18683 subshell, when the last command of that subshell is not a builtin. A
18684 workaround is to use @samp{exit $?} as the shell builtin.
18687 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18689 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18690 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18695 Likewise, older implementations of @command{bash} failed to preserve
18696 @samp{$?} across an exit trap consisting of a single cleanup command.
18699 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18701 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18703 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18707 Be aware that a trap can be called from any number of places in your
18708 script, and therefore the trap handler should not make assumptions about
18709 shell state. For some examples, if your script temporarily modifies
18710 @env{IFS}, then the trap should include an initialization back to its
18711 typical value of space-tab-newline (autoconf does this for generated
18712 @file{configure} files). Likewise, if your script changes the current
18713 working directory at some point after the trap is installed, then your
18714 trap cannot assume which directory it is in, and should begin by
18715 changing directories to an absolute path if that is important to the
18716 cleanup efforts (autotest does this for generated @file{testsuite}
18719 @item @command{true}
18720 @c -----------------
18721 @prindex @command{true}
18722 @c Info cannot handle ':' in index entries.
18723 @c @prindex @command{:}
18724 Don't worry: as far as we know @command{true} is portable.
18725 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18726 portable shell community tends to prefer using @command{:}. This has a
18727 funny side effect: when asked whether @command{false} is more portable
18728 than @command{true} Alexandre Oliva answered:
18731 In a sense, yes, because if it doesn't exist, the shell will produce an
18732 exit status of failure, which is correct for @command{false}, but not
18733 for @command{true}.
18736 Remember that even though @samp{:} ignores its arguments, it still takes
18737 time to compute those arguments. It is a good idea to use double quotes
18738 around any arguments to @samp{:} to avoid time spent in field splitting
18739 and file name expansion.
18743 @item @command{unset}
18744 @c ------------------
18745 @prindex @command{unset}
18746 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18747 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18748 @code{unset FOO} fails when @code{FOO} is not set. This can interfere
18749 with @code{set -e} operation. You can use
18756 if you are not sure that @code{FOO} is set.
18758 A few ancient shells lack @command{unset} entirely. For some variables
18759 such as @code{PS1}, you can use a neutralizing value instead:
18765 Usually, shells that do not support @command{unset} need less effort to
18766 make the environment sane, so for example is not a problem if you cannot
18767 unset @command{CDPATH} on those shells. However, Bash 2.01 mishandles
18768 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18769 So, you should do something like
18772 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18776 @xref{Special Shell Variables}, for some neutralizing values. Also, see
18777 @ref{export, , Limitations of Builtins}, for
18778 the case of environment variables.
18780 @item @command{wait}
18781 @c -----------------
18782 @prindex @command{wait}
18783 The exit status of @command{wait} is not always reliable.
18786 @node Limitations of Usual Tools
18787 @section Limitations of Usual Tools
18788 @cindex Limitations of usual tools
18790 The small set of tools you can expect to find on any machine can still
18791 include some limitations you should be aware of.
18793 @comment Between this list and the list of builtins above, we should
18794 @comment mention all the tools in GNU Coding Standards ``Utilities in
18795 @comment Makefiles''.
18797 @c This table includes things like '@command{expr} (|)', so we can't
18798 @c use @table @command.
18801 @item @command{awk}
18802 @c ----------------
18803 @prindex @command{awk}
18804 Don't leave white space before the opening parenthesis in a user function call.
18805 POSIX does not allow this and GNU Awk rejects it:
18808 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
18809 BEGIN @{ die () @}'}
18810 gawk: cmd. line:2: BEGIN @{ die () @}
18811 gawk: cmd. line:2: ^ parse error
18812 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
18813 BEGIN @{ die() @}'}
18817 POSIX says that if a program contains only @samp{BEGIN} actions, and
18818 contains no instances of @code{getline}, then the program merely
18819 executes the actions without reading input. However, traditional Awk
18820 implementations (such as Solaris 10 @command{awk}) read and discard
18821 input in this case. Portable scripts can redirect input from
18822 @file{/dev/null} to work around the problem. For example:
18825 awk 'BEGIN @{print "hello world"@}' </dev/null
18828 POSIX says that in an @samp{END} action, @samp{$NF} (and presumably,
18829 @samp{$1}) retain their value from the last record read, if no
18830 intervening @samp{getline} occurred. However, some implementations
18831 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18832 @samp{awk}) reset these variables. A workaround is to use an
18833 intermediate variable prior to the @samp{END} block. For example:
18836 $ @kbd{cat end.awk}
18838 END @{ print "a", $1, $NF, "b", tmp @}
18839 $ @kbd{echo 1 | awk -f end.awk}
18841 $ @kbd{echo 1 | gawk -f end.awk}
18845 If you want your program to be deterministic, don't depend on @code{for}
18849 $ @kbd{cat for.awk}
18856 $ @kbd{gawk -f for.awk </dev/null}
18859 $ @kbd{nawk -f for.awk </dev/null}
18864 Some Awk implementations, such as HP-UX 11.0's native one,
18868 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18869 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18871 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18873 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18878 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18879 or use a simple test to reject such implementations.
18881 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18885 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18889 AIX version 5.2 has an arbitrary limit of 399 on the
18890 length of regular expressions and literal strings in an Awk program.
18892 Traditional Awk implementations derived from Unix version 7, such as
18893 Solaris @command{/bin/awk}, have many limitations and do not
18894 conform to POSIX. Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18895 Programs}) finds you an Awk that doesn't have these problems, but if
18896 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18897 address them. For more detailed descriptions, see @ref{Language
18898 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18900 Traditional Awk does not support multidimensional arrays or user-defined
18903 Traditional Awk does not support the @option{-v} option. You can use
18904 assignments after the program instead, e.g., @code{$AWK '@{print v
18905 $1@}' v=x}; however, don't forget that such assignments are not
18906 evaluated until they are encountered (e.g., after any @code{BEGIN}
18909 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18911 Traditional Awk does not support the expressions
18912 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18913 or @code{@var{a}^=@var{b}}.
18915 Traditional Awk does not support the predefined @code{CONVFMT} or
18916 @code{ENVIRON} variables.
18918 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18919 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18920 @code{sqrt}, and @code{substr}.
18922 Traditional Awk @code{getline} is not at all compatible with POSIX;
18925 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18926 @code{in} keyword. For example, it lacks @code{if (i in a) @dots{}}.
18928 In code portable to both traditional and modern Awk, @code{FS} must be a
18929 string containing just one ordinary character, and similarly for the
18930 field-separator argument to @code{split}.
18932 Traditional Awk has a limit of 99 fields in a record
18933 and splits the input even if you don't refer to any field in the script.
18934 To circumvent this problem, set @samp{FS}
18935 to an unusual character and use @code{split}.
18937 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18938 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18941 The original version of Awk had a limit of at most 99 bytes per
18942 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18943 per run of non-special characters in a @code{printf} format, but these
18944 bugs have been fixed on all practical hosts that we know of.
18946 HP-UX 11.00 Awk requires that input files have a line length
18947 of at most 3070 bytes.
18949 @item @command{basename}
18950 @c ---------------------
18951 @prindex @command{basename}
18952 Long ago some hosts lacked a working @command{basename},
18953 and portable scripts needed to use @command{expr} instead.
18954 Nowadays it is safe to use @command{basename}. For example:
18957 base=`basename -- "$file"`
18960 @c AS_BASENAME is to be replaced by a better API.
18962 Not all hosts have a working @command{basename}, and you should instead
18963 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18964 @command{expr} if you need to strip a suffix. For example:
18967 a=`basename "$aname"` # This is not portable.
18968 a=`AS_BASENAME(["$aname"])` # This is more portable.
18970 # This is not portable.
18971 c=`basename "$cname" .c`
18973 # This is more portable.
18974 c=`AS_BASENAME(["$cname"])`
18976 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18982 @item @command{cat}
18983 @c ----------------
18984 @prindex @command{cat}
18985 Don't rely on any option.
18990 @prindex @command{cc}
18991 The command @samp{cc -c foo.c} traditionally produces an object file
18992 named @file{foo.o}. Most compilers allow @option{-c} to be combined
18993 with @option{-o} to specify a different object file name, but
18994 POSIX does not require this combination and a few compilers
18995 lack support for it. @xref{C Compiler}, for how GNU Make
18996 tests for this feature with @code{AC_PROG_CC_C_O}.
18998 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18999 (such as CDS on Reliant Unix) leave a @file{foo.o}.
19001 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
19002 assemble. @samp{cc -c foo.S} appears to succeed, but in fact does
19005 The default executable, produced by @samp{cc foo.c}, can be
19008 @item @file{a.out} -- usual POSIX convention.
19009 @item @file{b.out} -- i960 compilers (including @command{gcc}).
19010 @item @file{a.exe} -- DJGPP port of @command{gcc}.
19011 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
19012 @item @file{foo.exe} -- various MS-DOS compilers.
19015 The C compiler's traditional name is @command{cc}, but other names like
19016 @command{gcc} are common. POSIX 1003.1-2001 through 1003.1-2017 specify the
19017 name @command{c99}, but older POSIX editions specified
19018 @command{c89}, future POSIX standards will likely specify
19019 other commands, and anyway these standard names are rarely used in
19020 practice. Typically the C compiler is invoked from makefiles that use
19021 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
19024 @item @command{chgrp}
19025 @itemx @command{chown}
19026 @c -------------------
19027 @prindex @command{chgrp}
19028 @prindex @command{chown}
19029 It is not portable to change a file's group to a group that the owner
19030 does not belong to.
19032 @item @command{chmod}
19033 @c ------------------
19034 @prindex @command{chmod}
19035 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
19036 instead, for two reasons. First, plain @option{-w} does not necessarily
19037 make the file unwritable, since it does not affect mode bits that
19038 correspond to bits in the file mode creation mask. Second,
19039 POSIX says that the @option{-w} might be interpreted as an
19040 implementation-specific option, not as a mode; POSIX suggests
19041 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
19042 @samp{--} does not work on some older hosts.
19045 @item @command{cmp}
19046 @c ----------------
19047 @prindex @command{cmp}
19048 @command{cmp} performs a raw data comparison of two files, while
19049 @command{diff} compares two text files. Therefore, if you might compare
19050 DOS files, even if only checking whether two files are different, use
19051 @command{diff} to avoid spurious differences due to differences of
19057 @prindex @command{cp}
19058 The @option{-i}, @option{-f}, @option{-p} and @option{-R} options are
19059 widely used. POSIX also specifies @option{-H}, @option{-L}, and
19060 @option{-P}. Avoid other options in portable scripts.
19062 @cindex timestamp resolution
19063 Traditionally, file timestamps had 1-second resolution, and @samp{cp
19064 -p} copied the timestamps exactly. However, many modern file systems
19065 have timestamps with 1-nanosecond resolution. Unfortunately, some older
19066 @samp{cp -p} implementations truncate timestamps when copying files,
19067 which can cause the destination file to appear to be older than the
19068 source. The exact amount of truncation depends on the resolution of
19069 the system calls that @command{cp} uses. Traditionally this was
19070 @code{utime}, which has 1-second resolution. Less-ancient @command{cp}
19071 implementations such as GNU Core Utilities 5.0.91 (2003) use
19072 @code{utimes}, which has 1-microsecond resolution. Modern
19073 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
19074 the full nanosecond resolution, using the modern system calls
19075 @code{futimens} and @code{utimensat} when they are available. As of
19076 2011, though, many platforms do not yet fully support these new system
19079 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
19080 ownerships. But whether it actually does copy ownerships or not is a
19081 system dependent policy decision implemented by the kernel. If the
19082 kernel allows it then it happens. If the kernel does not allow it then
19083 it does not happen. It is not something @command{cp} itself has control
19086 In Unix System V any user can chown files to any other user, and System
19087 V also has a non-sticky @file{/tmp}. That probably derives from the
19088 heritage of System V in a business environment without hostile users.
19090 to be a more secure model where only root can @command{chown} files and
19091 a sticky @file{/tmp} is used. That undoubtedly derives from the heritage
19092 of BSD in a campus environment.
19094 GNU/Linux and Solaris by default follow BSD, but
19095 can be configured to allow a System V style @command{chown}. On the
19096 other hand, HP-UX follows System V, but can
19097 be configured to use the modern security model and disallow
19098 @command{chown}. Since it is an administrator-configurable parameter
19099 you can't use the name of the kernel as an indicator of the behavior.
19103 @item @command{date}
19104 @c -----------------
19105 @prindex @command{date}
19106 When most versions of @command{date} do not recognize a @samp{%}
19107 conversion specification, they quietly pass it through,
19108 and exit with success:
19111 $ @kbd{date --version | head -n 1}
19112 date (GNU coreutils) 9.5
19113 $ @kbd{date +'%H:%M %Q'}
19118 However, this behavior is not required by POSIX.
19121 @item @command{dirname}
19122 @c --------------------
19123 @prindex @command{dirname}
19124 Long ago some hosts lacked a working @command{dirname} and portable
19125 scripts needed to use use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).
19126 Nowadays @command{dirname} suffices and the following are equivalent:
19129 dir=`dirname -- "$file"`
19130 dir=`AS_DIRNAME(["$file"])`
19134 @item @command{egrep}
19135 @c ------------------
19136 @prindex @command{egrep}
19137 Although POSIX stopped requiring @command{egrep} in 2001,
19138 a few traditional hosts (notably Solaris 10) do not support the POSIX
19139 replacement @code{grep -E}. Also, some traditional implementations do
19140 not work on long input lines. To work around these problems, invoke
19141 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
19143 Portable extended regular expressions should use @samp{\} only to escape
19144 characters in the string @samp{$()*+.?[\^@{|}. For example, @samp{\@}}
19145 is not portable, even though it typically matches @samp{@}}.
19147 The empty alternative is not portable. Use @samp{?} instead. For
19148 instance with Digital Unix v5.0:
19151 > printf 'foo\n|foo\n' | $EGREP '^(|foo|bar)$'
19153 > printf 'bar\nbar|\n' | $EGREP '^(foo|bar|)$'
19155 > printf 'foo\nfoo|\n|bar\nbar\n' | $EGREP '^(foo||bar)$'
19160 For more information about what can appear in portable extended regular
19161 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
19163 @command{$EGREP} also suffers the limitations of @command{grep}
19164 (@pxref{grep, , Limitations of Usual Tools}).
19166 @item @command{expr}
19167 @c -----------------
19168 @prindex @command{expr}
19169 Not all implementations obey the POSIX rule that @samp{--} separates
19170 options from arguments; likewise, not all implementations provide the
19171 extension to POSIX that the first argument can be treated as part of a
19172 valid expression rather than an invalid option if it begins with
19173 @samp{-}. When performing arithmetic, use @samp{expr 0 + $var} if
19174 @samp{$var} might be a negative number, to keep @command{expr} from
19175 interpreting it as an option.
19177 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
19178 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
19179 misinterpreting @var{word}.
19181 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
19183 @item @command{expr} (@samp{|})
19184 @prindex @command{expr} (@samp{|})
19185 You can use @samp{|}. Although POSIX does require that @samp{expr
19186 ''} return the empty string, it does not specify the result when you
19187 @samp{|} together the empty string (or zero) with the empty string. For
19194 POSIX 1003.2-1992 returns the empty string
19195 for this case, but traditional Unix returns @samp{0} (Solaris is
19196 one such example). In POSIX 1003.1-2001, the specification was
19197 changed to match traditional Unix's behavior (which is
19198 bizarre, but it's too late to fix this). Please note that the same
19199 problem does arise when the empty string results from a computation,
19203 expr bar : foo \| foo : bar
19207 Avoid this portability problem by avoiding the empty string.
19210 @item @command{expr} (@samp{:})
19211 @c ----------------------------
19212 @prindex @command{expr}
19213 Portable @command{expr} regular expressions should use @samp{\} to
19214 escape only characters in the string @samp{$()*.123456789[\^@{@}}.
19215 For example, alternation, @samp{\|}, is common but POSIX does not
19216 require its support, so it should be avoided in portable scripts.
19217 Similarly, @samp{\+} and @samp{\?} should be avoided.
19219 Portable @command{expr} regular expressions should not begin with
19220 @samp{^}. Patterns are automatically anchored so leading @samp{^} is
19223 On the other hand, the behavior of the @samp{$} anchor is not portable
19224 on multi-line strings. POSIX is ambiguous whether the anchor applies to
19225 each line, as was done in older versions of the GNU Core Utilities, or
19226 whether it applies only to the end of the overall string, as in
19227 Coreutils 6.0 and most other implementations.
19232 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19234 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19238 The POSIX standard is ambiguous as to whether
19239 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19240 In practice, it outputs the empty string on most platforms, but portable
19241 scripts should not assume this. For instance, the QNX 4.25 native
19242 @command{expr} returns @samp{0}.
19244 One might think that a way to get a uniform behavior would be to use
19245 the empty string as a default value:
19248 expr a : '\(b\)' \| ''
19252 Unfortunately this behaves exactly as the original expression; see the
19253 @command{expr} (@samp{|}) entry for more information.
19255 Some ancient @command{expr} implementations (e.g.,
19256 Solaris 10 @command{/usr/ucb/expr}) have a silly length limit that causes
19257 @command{expr} to fail if the matched substring is longer than 120
19258 bytes. In this case, you might want to fall back on @samp{printf|sed} if
19259 @command{expr} fails. Nowadays this is of practical importance only for
19260 the rare installer who mistakenly puts @file{/usr/ucb} before
19261 @file{/usr/bin} in @env{PATH} on Solaris 10.
19263 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19264 some cases. For example, the command
19266 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19270 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19271 This particular case can be worked around by substituting @samp{[^--]}
19274 Don't leave, there is some more!
19276 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19277 the empty string, has a funny behavior in its exit status: it's always 1
19278 when parentheses are used!
19281 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19283 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19286 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19288 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19293 In practice this can be a big problem if you are ready to catch failures
19294 of @command{expr} programs with some other method (such as using
19295 @command{sed}), since you may get twice the result. For instance
19298 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19302 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25. A
19303 simple workaround consists of testing @command{expr} and using a variable
19304 set to @command{expr} or to @command{false} according to the result.
19306 On HP-UX 11, @command{expr} supports only a single
19310 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19311 expr: More than one '\(' was used.
19315 @item @command{fgrep}
19316 @c ------------------
19317 @prindex @command{fgrep}
19318 Although POSIX stopped requiring @command{fgrep} in 2001,
19319 a few traditional hosts (notably Solaris 10) do not support the POSIX
19320 replacement @code{grep -F}. Also, some traditional implementations do
19321 not work on long input lines. To work around these problems, invoke
19322 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19325 @item @command{find}
19326 @c -----------------
19327 @prindex @command{find}
19328 Many operands of GNU @command{find} are not standardized by POSIX and
19329 are missing on many platforms. These nonportable operands include
19330 @option{-follow}, @option{-maxdepth}, @option{-mindepth},
19331 @option{-printf}, and @option{,}. See the
19332 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/find.html,
19333 POSIX spec for @command{find}} for @command{find} operands that
19334 should be portable nowadays.
19336 The replacement of @samp{@{@}} is guaranteed only if the argument is
19337 exactly @emph{@{@}}, not if it's only a part of an argument. For
19338 instance, on HP-UX 11:
19342 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19347 while GNU @command{find} reports @samp{./foo-./foo}.
19348 POSIX allows either behavior.
19352 @item @command{grep}
19353 @c -----------------
19354 @prindex @command{grep}
19355 Portable scripts can rely on the @command{grep} options @option{-c},
19356 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19357 options. For example, don't use @option{-w}, as POSIX does not require it.
19358 Also, portable scripts should not combine @option{-c} with @option{-l},
19359 as POSIX does not allow this.
19361 Some of the options required by POSIX are not portable in practice.
19362 Don't use @samp{grep -q} to suppress output, because traditional @command{grep}
19363 implementations (e.g., Solaris 10) do not support @option{-q}.
19364 Don't use @samp{grep -s} to suppress output either, because POSIX
19365 says @option{-s} does not suppress output, only some error messages;
19366 also, the @option{-s} option of traditional @command{grep} behaved
19367 like @option{-q} does in most modern implementations. Instead,
19368 redirect the standard output and standard error (in case the file
19369 doesn't exist) of @code{grep} to @file{/dev/null}. Check the exit
19370 status of @code{grep} to determine whether it found a match.
19372 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19373 but works with @code{grep -c '^'}. Other alternatives for counting
19374 lines are to use @code{sed -n '$='} or @code{wc -l}.
19376 Some traditional @command{grep} implementations do not work on long
19377 input lines. On AIX the default @code{grep} silently truncates long
19378 lines on the input before matching.
19380 Also, Solaris 10 @command{grep} does not support @option{-e}.
19381 To work around this, invoke @code{AC_PROG_GREP} and then use @code{$GREP}.
19383 Another possible workaround for the multiple @option{-e} problem is to
19384 separate the patterns by newlines, for example:
19392 except that this fails with traditional @command{grep}
19393 implementations and with OpenBSD 3.8 @command{grep}.
19395 Traditional @command{grep} implementations (e.g., Solaris 10) do not
19396 support the @option{-E} or @option{-F} options. To work around these
19397 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19398 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}. Even if you are
19399 willing to require support for POSIX @command{grep}, your script should
19400 not use both @option{-E} and @option{-F}, since POSIX does not allow
19403 Portable @command{grep} regular expressions should use @samp{\} only to
19404 escape characters in the string @samp{$()*.123456789[\^@{@}}. For example,
19405 alternation, @samp{\|}, is common but POSIX does not require its
19406 support in basic regular expressions, so it should be avoided in
19407 portable scripts. Solaris and HP-UX @command{grep} do not support it.
19408 Similarly, the following escape sequences should also be avoided:
19409 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19410 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19411 For more information about what can appear in portable regular expressions,
19412 @pxref{Problematic Expressions,,, grep, GNU Grep}.
19414 POSIX does not specify the behavior of @command{grep} on binary files.
19415 An example where this matters is using BSD @command{grep} to
19416 search text that includes embedded ANSI escape sequences for
19417 colored output to terminals (@samp{\033[m} is the sequence to restore
19418 normal output); the behavior depends on whether input is seekable:
19421 $ @kbd{printf 'esc\033[mape\n' > sample}
19422 $ @kbd{grep . sample}
19423 Binary file sample matches
19424 $ @kbd{cat sample | grep .}
19429 @item @command{join}
19430 @c -----------------
19431 @prindex @command{join}
19432 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19433 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19434 the workaround is to use @command{join -a1 file1 file2} instead.
19436 On some circa-2020 BSD-based systems @command{join} mishandles inputs
19437 with missing fields. For example, an empty line is not treated as
19438 containing an empty join field. As a workaround, input lines should
19439 always have a join field.
19441 On platforms with the BusyBox tools, the @command{join} command is
19442 entirely missing. As a workaround, you can simulate special cases of the
19443 @command{join} command using an @command{awk} script. For an example,
19444 see @url{https://lists.gnu.org/r/bug-gnulib/2021-04/msg00054.html}.
19449 @prindex @command{ln}
19450 The @option{-f} option is portable nowadays.
19452 @cindex Symbolic links
19453 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19454 a portable substitute.
19456 For versions of the DJGPP before 2.04,
19457 @command{ln} emulates symbolic links
19458 to executables by generating a stub that in turn calls the real
19459 program. This feature also works with nonexistent files like in the
19460 POSIX spec. So @samp{ln -s file link} generates @file{link.exe},
19461 which attempts to call @file{file.exe} if run. But this feature only
19462 works for executables, so @samp{cp -p} is used instead for these
19463 systems. DJGPP versions 2.04 and later have full support
19464 for symbolic links.
19469 @prindex @command{ls}
19470 @cindex Listing directories
19471 The portable options are @option{-acdilrtu}. Current practice is for
19472 @option{-l} to output both owner and group, even though ancient versions
19473 of @command{ls} omitted the group.
19475 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19476 to standard output if @file{foo} did not exist. Hence a shell command
19477 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19478 was equivalent to @samp{sources='*.c not found'} in the absence of
19479 @samp{.c} files. This is no longer a practical problem, since current
19480 @command{ls} implementations send diagnostics to standard error.
19482 The behavior of @command{ls} on a directory that is being concurrently
19483 modified is not always predictable, because of a data race where cached
19484 information returned by @code{readdir} does not match the current
19485 directory state. In fact, Mac OS X 10.5 had an intermittent bug where
19486 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19487 once if other files were added or removed from the directory immediately
19488 prior to the @command{ls} call. Since @command{ls} already sorts its
19489 output, the duplicate entries can be avoided by piping the results
19490 through @code{uniq}.
19493 @item @command{mkdir}
19494 @c ------------------
19495 @prindex @command{mkdir}
19496 @cindex Making directories
19497 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19498 go-w -p @var{dir}}, often leads to trouble. FreeBSD
19499 @command{mkdir} incorrectly attempts to change the permissions of
19500 @var{dir} even if it already exists. HP-UX 11.23
19501 @command{mkdir} often assigns the wrong permissions to
19502 any newly-created parents of @var{dir}.
19504 POSIX does not clearly specify whether @samp{mkdir -p foo}
19505 should succeed when @file{foo} is a symbolic link to an already-existing
19506 directory. The GNU @command{mkdir}
19507 succeeds, but Solaris 10 @command{mkdir} fails.
19509 Traditional @code{mkdir -p} implementations suffer from race conditions.
19510 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19511 at the same time, both processes might detect that @file{a} is missing,
19512 one might create @file{a}, then the other might try to create @file{a}
19513 and fail with a @code{File exists} diagnostic. Solaris 10 @command{mkdir}
19514 is vulnerable, and other traditional Unix systems are
19515 probably vulnerable too. This possible race is harmful in parallel
19516 builds when several Make rules call @code{mkdir -p} to
19517 construct directories. You may use
19518 @code{install-sh -d} as a safe replacement, for example by setting
19519 @samp{MKDIR_P='/path/to/install-sh -d'} in the environment of
19520 @command{configure}, assuming the package distributes @file{install-sh}.
19522 @item @command{mkfifo}
19523 @itemx @command{mknod}
19524 @c -------------------
19525 @prindex @command{mkfifo}
19526 @prindex @command{mknod}
19527 The GNU Coding Standards state that @command{mknod} is safe to use on
19528 platforms where it has been tested to exist; but it is generally portable
19529 only for creating named FIFOs, since device numbers are
19530 platform-specific. Autotest uses @command{mkfifo} to implement parallel
19531 testsuites. POSIX states that behavior is unspecified when opening a
19532 named FIFO for both reading and writing; on at least Cygwin, this
19533 results in failure on any attempt to read or write to that file
19536 @item @command{mktemp}
19537 @c -------------------
19538 @prindex @command{mktemp}
19539 @cindex Creating temporary files
19540 Shell scripts can use temporary files safely with @command{mktemp}, but
19541 it does not exist on all systems. A portable way to create a safe
19542 temporary file name is to create a temporary directory with mode 700 and
19543 use a file inside this directory. Both methods prevent attackers from
19544 gaining control, though @command{mktemp} is far less likely to fail
19545 gratuitously under attack.
19547 Here is sample code to create a new temporary directory @samp{$dir} safely:
19550 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19551 # Use mktemp if possible; otherwise fall back on mkdir,
19552 # with $RANDOM to make collisions less likely.
19553 : "$@{TMPDIR:=/tmp@}"
19556 (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19560 dir=$TMPDIR/foo$$-$RANDOM
19561 @c $$ restore font-lock
19562 (umask 077 && mkdir "$dir")
19569 @prindex @command{mv}
19570 @cindex Moving open files
19571 The only portable options are @option{-f} and @option{-i}.
19573 Moving individual files between file systems is portable (it was in Unix
19575 but it is not always atomic: when doing @samp{mv new existing}, there's
19576 a critical section where neither the old nor the new version of
19577 @file{existing} actually exists.
19579 On some systems moving files from @file{/tmp} can sometimes cause
19580 undesirable (but perfectly valid) warnings, even if you created these
19581 files. This is because @file{/tmp} belongs to a group that ordinary
19582 users are not members of, and files created in @file{/tmp} inherit
19583 the group of @file{/tmp}. When the file is copied, @command{mv} issues
19584 a diagnostic without failing:
19587 $ @kbd{touch /tmp/foo}
19588 $ @kbd{mv /tmp/foo .}
19589 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19597 This annoying behavior conforms to POSIX, unfortunately.
19599 Moving directories across mount points is not portable, use @command{cp}
19602 DOS variants cannot rename or remove open files, and do not
19603 support commands like @samp{mv foo bar >foo}, even though this is
19604 perfectly portable among POSIX hosts.
19609 @prindex @command{od}
19611 In Mac OS X versions prior to 10.4.3, @command{od} does not support the
19612 standard POSIX options @option{-A}, @option{-j}, @option{-N}, or
19613 @option{-t}, or the XSI option, @option{-s}. The only
19614 supported POSIX option is @option{-v}, and the only supported
19615 XSI options are those in @option{-bcdox}. The BSD
19616 @command{hexdump} program can be used instead.
19618 In some versions of some operating systems derived from Solaris 11,
19619 @command{od} prints decimal byte values padded with zeros rather than
19623 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19631 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19635 We have observed this on both OpenIndiana and OmniOS;
19636 Illumos may also be affected.
19637 As a workaround, you can use octal output (option @code{-t o1}).
19642 @prindex @command{rm}
19643 The @option{-f} and @option{-r} options are portable.
19645 It is not portable to invoke @command{rm} without options or operands.
19646 On the other hand, POSIX now requires @command{rm -f} to silently
19647 succeed when there are no operands (useful for constructs like
19648 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19649 was empty). But this was not always portable; at least NetBSD
19650 @command{rm} built before 2008 would fail with a diagnostic.
19652 A file might not be removed even if its parent directory is writable
19653 and searchable. Many POSIX hosts cannot remove a mount point, a named
19654 stream, a working directory, or a last link to a file that is being
19657 DOS variants cannot rename or remove open files, and do not
19658 support commands like @samp{rm foo >foo}, even though this is
19659 perfectly portable among POSIX hosts.
19661 @item @command{rmdir}
19662 @c ------------------
19663 @prindex @command{rmdir}
19664 Just as with @command{rm}, some platforms refuse to remove a working
19668 @item @command{sed}
19669 @c ----------------
19670 @prindex @command{sed}
19671 Patterns should not include the separator (unless escaped), even as part
19672 of a character class. In conformance with POSIX, the Cray
19673 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19674 Even when escaped, patterns should not include separators that are also
19675 used as @command{sed} metacharacters. For example, GNU sed 4.0.9 rejects
19676 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19677 before evaluating the basic regular expression.
19679 Avoid empty patterns within parentheses (i.e., @samp{\(\)}). POSIX does
19680 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19683 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19685 Sed scripts should not use branch labels longer than 7 characters and
19686 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19687 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19688 48 labels, which cannot be circumvented by using more than one script
19689 file. It can execute up to 19 reads with the @samp{r} command per cycle.
19690 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19691 about 6000 bytes for the internal representation of commands.
19693 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19694 NetBSD 1.4.2's, incorrectly try to interpret the second
19695 @samp{;} as a command:
19698 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19699 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19702 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19703 and this limits the size of input lines, output lines, and internal
19704 buffers that can be processed portably. Likewise,
19705 not all @command{sed} implementations can handle embedded @code{NUL} or
19706 a missing trailing newline.
19708 Remember that ranges within a bracket expression of a regular expression
19709 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19710 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19711 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19712 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19713 than to rely on @samp{[A-Z]}.
19715 Additionally, POSIX states that regular expressions are only
19716 well-defined on characters. Unfortunately, there exist platforms such
19717 as Mac OS X 10.5 where not all 8-bit byte values are valid characters,
19718 even though that platform has a single-byte @samp{C} locale. And POSIX
19719 allows the existence of a multi-byte @samp{C} locale, although that does
19720 not yet appear to be a common implementation. At any rate, it means
19721 that not all bytes will be matched by the regular expression @samp{.}:
19724 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19726 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19730 Portable @command{sed} regular expressions should use @samp{\} only to escape
19731 characters in the string @samp{$()*.123456789[\^n@{@}}. For example,
19732 alternation, @samp{\|}, is common but POSIX does not require its
19733 support, so it should be avoided in portable scripts. Solaris
19734 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19735 deletes only lines that contain the literal string @samp{a|b}.
19736 Similarly, @samp{\+} and @samp{\?} should be avoided.
19738 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19740 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19741 quite portable to current hosts, but was not supported by some ancient
19742 @command{sed} implementations like SVR3.
19744 Some @command{sed} implementations, e.g., Solaris, restrict the special
19745 role of the asterisk @samp{*} to one-character regular expressions and
19746 back-references, and the special role of interval expressions
19747 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19748 to one-character regular expressions. This may lead to unexpected behavior:
19751 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19753 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19757 The @option{-e} option is mostly portable.
19758 However, its argument cannot be empty, as this fails on AIX 7.3.
19759 Some people prefer to use @samp{-e}:
19762 sed -e '@var{command-1}' \
19763 -e '@var{command-2}'
19767 as opposed to the equivalent:
19777 The following usage is sometimes equivalent:
19780 sed '@var{command-1};@var{command-2}'
19783 but POSIX says that this use of a semicolon has undefined effect if
19784 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19785 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19786 should use semicolon only with simple scripts that do not use these
19789 POSIX up to the 2008 revision requires the argument of the @option{-e}
19790 option to be a syntactically complete script. GNU @command{sed} allows
19791 to pass multiple script fragments, each as argument of a separate
19792 @option{-e} option, that are then combined, with newlines between the
19793 fragments, and a future POSIX revision may allow this as well. This
19794 approach is not portable with script fragments ending in backslash; for
19795 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19796 don't allow splitting in this case:
19799 $ @kbd{echo a | sed -n -e 'i\}
19802 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19803 Unrecognized command: 0
19807 In practice, however, this technique of joining fragments
19808 through @option{-e} works for multiple @command{sed} functions within
19809 @samp{@{} and @samp{@}}, even if that is not specified by POSIX:
19812 @c The quote around the closing brace silences interactive zsh.
19813 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19817 Commands inside @{ @} brackets are further restricted. POSIX 2008 says that
19818 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19819 each command must be followed immediately by a newline, without any
19820 intervening blanks or semicolons. The closing bracket must be alone on
19821 a line, other than white space preceding or following it. However, a
19822 future version of POSIX may standardize the use of addresses within brackets.
19824 Contrary to yet another urban legend, you may portably use @samp{&} in
19825 the replacement part of the @code{s} command to mean ``what was
19826 matched''. All descendants of Unix version 7 @command{sed}
19828 don't have first hand experience with older @command{sed} implementations) have
19831 POSIX requires that you must not have any white space between
19832 @samp{!} and the following command. It is OK to have blanks between
19833 the address and the @samp{!}. For instance, on Solaris:
19836 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19837 @error{}Unrecognized command: /bar/ ! p
19838 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19839 @error{}Unrecognized command: /bar/! p
19840 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19844 POSIX also says that you should not combine @samp{!} and @samp{;}. If
19845 you use @samp{!}, it is best to put it on a command that is delimited by
19846 newlines rather than @samp{;}.
19848 Also note that POSIX requires that the @samp{b}, @samp{t}, @samp{r}, and
19849 @samp{w} commands be followed by exactly one space before their argument.
19850 On the other hand, no white space is allowed between @samp{:} and the
19851 subsequent label name.
19853 If a sed script is specified on the command line and ends in an
19854 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19855 should be followed by a newline. Otherwise some @command{sed}
19856 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19859 Many @command{sed} implementations (e.g., Mac OS X 10.4,
19860 OpenBSD 3.9, Solaris 10
19861 @command{/usr/ucb/sed}) strip leading white space from the text of
19862 @samp{a}, @samp{c}, and @samp{i} commands. Prepend a backslash to
19863 work around this incompatibility with POSIX:
19866 $ @kbd{echo flushleft | sed 'a\}
19871 $ @kbd{echo foo | sed 'a\}
19878 POSIX requires that with an empty regular expression, the last non-empty
19879 regular expression from either an address specification or substitution
19880 command is applied. However, busybox 1.6.1 complains when using a
19881 substitution command with a replacement containing a back-reference to
19882 an empty regular expression; the workaround is repeating the regular
19886 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19887 sed: No previous regexp.
19888 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19892 Portable scripts should be aware of the inconsistencies and options for
19893 handling word boundaries, as these are not specified by POSIX.
19897 Solaris 10 yes no no
19898 Solaris XPG4 yes no error
19899 NetBSD 5.1 no no yes
19900 FreeBSD 9.1 no no yes
19902 busybox yes yes error
19905 @item @command{sed} (@samp{t})
19906 @c ---------------------------
19907 @prindex @command{sed} (@samp{t})
19908 There are two things one should remember about @samp{t} in @command{sed}.
19909 First, @samp{t} jumps if @emph{some} substitution
19910 succeeded, not only the immediately preceding substitution. Therefore,
19911 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19912 line, to reset the @samp{t} flag where needed.
19914 Second, do not rely on @command{sed} to clear the flag at each new cycle.
19916 For example, the following script replaces all instances of ``keep me''
19917 with ``kept'', and replaces the contents of all lines that did not
19918 contain ``keep me'' with ``deleted''.
19929 @item @command{sed} (@samp{w})
19930 @c ---------------------------
19931 @prindex @command{sed} (@samp{w})
19933 When a script contains multiple commands to write lines to the same
19934 output file, BusyBox @command{sed} mistakenly opens a separate output
19935 stream for each command. This can cause one of the commands to ``win''
19936 and the others to ``lose'', in the sense that their output is discarded.
19949 This might output only @samp{a} to @file{xxx}; the @samp{b} is lost.
19950 To avoid the problem, a portable script should contain at most one
19951 @samp{w} or @samp{s/.../.../w} command per output file.
19953 @item @command{sleep}
19954 @c ------------------
19955 @prindex @command{sleep}
19956 Using @command{sleep} is generally portable. However, remember that
19957 adding a @command{sleep} to work around timestamp issues, with a minimum
19958 granularity of one second, doesn't scale well for parallel builds on
19959 modern machines with sub-second process completion.
19961 @item @command{sort}
19962 @c -----------------
19963 @prindex @command{sort}
19964 Remember that sort order is influenced by the current locale. Inside
19965 @file{configure}, the C locale is in effect, but in Makefile snippets,
19966 you may need to specify @code{LC_ALL=C sort}.
19968 @item @command{tar}
19969 @c ----------------
19970 @prindex @command{tar}
19971 There are multiple file formats for @command{tar}; if you use Automake,
19972 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19973 level of portability to use.
19976 @item @command{touch}
19977 @c ------------------
19978 @prindex @command{touch}
19979 @cindex timestamp resolution
19980 If you specify the desired timestamp (e.g., with the @option{-r}
19981 option), older @command{touch} implementations use the @code{utime} or
19982 @code{utimes} system call, which can result in the same kind of
19983 timestamp truncation problems that @samp{cp -p} has.
19987 @prindex @command{tr}
19988 @cindex carriage return, deleting
19989 @cindex newline, deleting
19990 @cindex deleting carriage return
19991 Not all versions of @command{tr} handle all backslash character escapes.
19992 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19993 Solaris contains more modern @command{tr} in other locations.
19994 Using octal escapes is more portable for carriage returns, since
19995 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19996 literal carriage returns in scripts causes a number of other problems.
19997 But for other characters, like newline, using octal escapes ties the
19998 operation to ASCII, so it is better to use literal characters.
20001 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
20004 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
20006 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
20009 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
20013 Not all versions of @command{tr} recognize direct ranges of characters: at
20014 least Solaris @command{/usr/bin/tr} still fails to do so. But you can
20015 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in POSIX
20016 transliterate to themselves).
20019 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
20021 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
20023 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
20027 When providing two arguments, be sure the second string is at least as
20031 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
20033 $ @kbd{echo abc | coreutils/tr bc d}
20037 On platforms with the BusyBox tools, @command{tr} does not support the
20038 @code{[@var{x}*@var{n}]} option syntax.
20041 $ @kbd{echo abc | tr 'abcd' '[A*4]'}
20043 $ @kbd{echo abc | coreutils/tr 'abcd' '[A*4]'}
20045 $ @kbd{echo xyz | tr 'a-z' '[A*]'}
20047 $ @kbd{echo xyz | coreutils/tr 'a-z' '[A*]'}
20051 POSIX requires @command{tr} to operate on binary files. But at least
20052 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
20053 @code{NUL} in the input prior to doing any translation. When using
20054 @command{tr} to process a binary file that may contain @code{NUL} bytes,
20055 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
20056 @command{/usr/xpg6/bin/tr} if that is available.
20059 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
20061 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
20063 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
20067 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
20068 octal escape for @code{NUL}.
20071 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
20073 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
20075 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
20082 @node Portable Make
20083 @chapter Portable Make Programming
20084 @prindex @command{make}
20085 @cindex Limitations of @command{make}
20087 Writing portable makefiles is an art. Since a makefile's commands are
20088 executed by the shell, you must consider the shell portability issues
20089 already mentioned. However, other issues are specific to @command{make}
20093 * $< in Ordinary Make Rules:: $< in ordinary rules
20094 * Failure in Make Rules:: Failing portably in rules
20095 * Command Line Prefixes:: What's at the start of makefile command lines
20096 * Special Chars in Names:: Special characters in macro names
20097 * Backslash-Newline-Empty:: Empty lines after backslash-newline
20098 * Backslash-Newline Comments:: Spanning comments across line boundaries
20099 * Macros and Submakes:: @code{make macro=value} and submakes
20100 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
20101 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
20102 * Parallel Make:: Parallel @command{make} quirks
20103 * Comments in Make Rules:: Other problems with Make comments
20104 * Newlines in Make Rules:: Using literal newlines in rules
20105 * Comments in Make Macros:: Other problems with Make comments in macros
20106 * Trailing whitespace in Make Macros:: Macro substitution problems
20107 * Command-line Macros and whitespace:: Whitespace trimming of values
20108 * obj/ and Make:: Don't name a subdirectory @file{obj}
20109 * make -k Status:: Exit status of @samp{make -k}
20110 * VPATH and Make:: @code{VPATH} woes
20111 * Single Suffix Rules:: Single suffix rules and separated dependencies
20112 * Timestamps and Make:: Sub-second timestamp resolution
20115 @node $< in Ordinary Make Rules
20116 @section @code{$<} in Ordinary Make Rules
20118 POSIX says that the @samp{$<} construct in makefiles can be
20119 used only in inference rules and in the @samp{.DEFAULT} rule; its
20120 meaning in ordinary rules is unspecified. Solaris @command{make}
20121 for instance replaces it with the empty string. OpenBSD (3.0 and
20122 later) @command{make} diagnoses these uses and errors out.
20124 @node Failure in Make Rules
20125 @section Failure in Make Rules
20127 Unless errors are being ignored
20128 (e.g., because a makefile command line is preceded by a @samp{-} prefix),
20129 POSIX 2008 requires that @command{make} must invoke each command with
20130 the equivalent of a @samp{sh -e -c} subshell, which causes the
20131 subshell to exit immediately if a subsidiary simple-command fails,
20132 with some complicated exceptions.
20133 Historically not all @command{make} implementations
20134 followed this rule. For
20135 example, the command @samp{touch T; rm -f U} may attempt to
20136 remove @file{U} even if the @command{touch} fails, although this is not
20137 permitted with POSIX make. One way to work around failures in simple
20138 commands is to reword them so that they always succeed, e.g., @samp{touch
20140 However, even this approach can run into common bugs in BSD
20141 implementations of the @option{-e} option of @command{sh} and
20142 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
20144 about porting to buggy BSD shells it may be simpler to migrate
20145 complicated @command{make} actions into separate scripts.
20147 @node Command Line Prefixes
20148 @section Makefile Command Line Prefixes
20150 Makefile command lines can be preceded by zero or more of
20151 the command line prefixes @samp{-}, @samp{@@}, and @samp{+},
20152 which modify how @command{make} processes the command.
20153 Although POSIX says these are the only command line prefixes,
20154 some @command{make} implementations, such as Solaris @command{make},
20155 support the additional prefixes @samp{!} and @samp{?}.
20156 Portable makefiles should therefore avoid using these two characters at
20157 the start of a makefile command line.
20161 mishandled-by-Solaris-make:; ! grep FIXME foo.c
20162 portable-to-Solaris-make:; :;! grep FIXME foo.c
20165 @node Special Chars in Names
20166 @section Special Characters in Make Macro Names
20168 POSIX limits macro names to nonempty strings containing only
20169 ASCII letters and digits, @samp{.}, and @samp{_}. Many
20170 @command{make} implementations allow a wider variety of characters, but
20171 portable makefiles should avoid them. It is portable to start a name
20172 with a special character, e.g., @samp{$(.FOO)}.
20174 Some ancient @command{make} implementations don't support leading
20175 underscores in macro names. An example is NEWS-OS 4.2R.
20178 $ @kbd{cat Makefile}
20181 all:; @@echo this is test
20183 Make: Must be a separator on rules line 2. Stop.
20184 $ @kbd{cat Makefile2}
20187 all:; @@echo this is test
20188 $ @kbd{make -f Makefile2}
20193 However, this problem is no longer of practical concern.
20195 @node Backslash-Newline-Empty
20196 @section Backslash-Newline Before Empty Lines
20198 @c This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20199 @c but another hppa hpux 10.20 didn't have it. Bob Proulx
20200 @c <bob@proulx.com> thinks it was in hpux 8.0 too.
20201 On some versions of HP-UX, @command{make} reads multiple newlines
20202 following a backslash, continuing to the next non-empty line. For
20216 shows @code{FOO} equal to @code{one BAR = two}. Other implementations
20217 sensibly let a backslash continue only to the immediately following
20220 @node Backslash-Newline Comments
20221 @section Backslash-Newline in Make Comments
20223 According to POSIX, Make comments start with @code{#}
20224 and continue until an unescaped newline is reached.
20227 $ @kbd{cat Makefile}
20234 $ @kbd{make} # GNU make
20239 However this is not always the case. Some implementations
20240 discard everything from @code{#} through the end of the line, ignoring any
20241 trailing backslash.
20244 $ @kbd{pmake} # BSD make
20245 "Makefile", line 3: Need an operator
20246 Fatal errors encountered -- cannot continue
20250 Therefore, if you want to comment out a multi-line definition, prefix each
20251 line with @code{#}, not only the first.
20259 @node Macros and Submakes
20260 @section @code{make macro=value} and Submakes
20262 A command-line variable definition such as @code{foo=bar} overrides any
20263 definition of @code{foo} in a makefile. Some @command{make}
20264 implementations (such as GNU @command{make}) propagate this
20265 override to subsidiary invocations of @command{make}. Some other
20266 implementations do not pass the substitution along to submakes.
20269 $ @kbd{cat Makefile}
20272 @@printf '%s\n' $(foo)
20275 @@printf '%s\n' $(foo)
20276 $ @kbd{make foo=bar} # GNU make 3.79.1
20279 make[1]: Entering directory `/home/adl'
20281 make[1]: Leaving directory `/home/adl'
20282 $ @kbd{pmake foo=bar} # BSD make
20288 You have a few possibilities if you do want the @code{foo=bar} override
20289 to propagate to submakes. One is to use the @option{-e}
20290 option, which causes all environment variables to have precedence over
20291 the makefile macro definitions, and declare foo as an environment
20295 $ @kbd{env foo=bar make -e}
20298 The @option{-e} option is propagated to submakes automatically,
20299 and since the environment is inherited between @command{make}
20300 invocations, the @code{foo} macro is overridden in
20301 submakes as expected.
20303 This syntax (@code{foo=bar make -e}) is portable only when used
20304 outside of a makefile, for instance from a script or from the
20305 command line. When run inside a @command{make} rule, GNU
20306 @command{make} 3.80 and prior versions forget to propagate the
20307 @option{-e} option to submakes.
20309 Moreover, using @option{-e} could have unexpected side effects if your
20310 environment contains some other macros usually defined by the
20311 makefile. (See also the note about @code{make -e} and @code{SHELL}
20314 If you can foresee all macros that a user might want to override, then
20315 you can propagate them to submakes manually, from your makefile:
20320 @@printf '%s\n' $(foo)
20321 $(MAKE) foo=$(foo) two
20323 @@printf '%s\n' $(foo)
20326 Another way to propagate a variable to submakes in a portable way is to
20327 expand an extra variable in every invocation of @samp{$(MAKE)} within
20333 @@printf '%s\n' $(foo)
20334 $(MAKE) $(SUBMAKEFLAGS) two
20336 @@printf '%s\n' $(foo)
20339 Users must be aware that this technique is in use to take advantage of
20340 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20341 allows any macro to be overridden. Makefiles generated by
20342 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20343 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20344 automake, GNU Automake}).
20346 @node The Make Macro MAKEFLAGS
20347 @section The Make Macro MAKEFLAGS
20348 @cindex @code{MAKEFLAGS} and @command{make}
20349 @cindex @command{make} and @code{MAKEFLAGS}
20351 POSIX requires @command{make} to use @code{MAKEFLAGS} to affect the
20352 current and recursive invocations of make, but allows implementations
20353 several formats for the variable. It is tricky to parse
20354 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20355 or @option{-k} for continued execution are in effect. For example, you
20356 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20357 contains single-letter options, since in the Cygwin version of
20358 GNU @command{make} it is either @option{--unix} or
20359 @option{--win32} with the second word containing single-letter options.
20362 $ @kbd{cat Makefile}
20364 @@printf 'MAKEFLAGS = %s\n' '$(MAKEFLAGS)'
20368 MAKEFLAGS = --unix -k
20371 @node The Make Macro SHELL
20372 @section The Make Macro @code{SHELL}
20373 @cindex @code{SHELL} and @command{make}
20374 @cindex @command{make} and @code{SHELL}
20376 Many @command{make} implementations use the the @code{$(SHELL)}
20377 macro to spawn shell processes and execute Make rules. This
20378 is a builtin macro with a default value upplied by @command{make};
20379 the default can be overridden by a makefile or by a command-line argument,
20380 though not by the environment.
20382 Other @command{make} implementations use other ways to spawn shell
20383 processes, and the POSIX standard for @command{make} says that portable
20384 makefiles should neither define nor use the @code{$(SHELL)} macro.
20386 Despite this prohibition, in practice it does not hurt to define and
20387 then possibly use @code{SHELL} in your makefiles and in some cases it
20388 can help your builds use a better shell to spawn shell processes.
20389 So it's a good idea to define @code{SHELL} in
20390 your makefiles. If you use Autoconf, you can use
20391 its standard output variable @code{SHELL} as follows:
20398 If you use Automake, this is done for you.
20400 Do not force @code{SHELL = /bin/sh} because that is not correct
20401 everywhere. Remember, @file{/bin/sh} is not POSIX compliant on some
20402 systems, such as Solaris 10.
20403 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20404 GNU @command{make} port sees such a setting it enters a
20405 special emulation mode where features like pipes and redirections are
20406 emulated on top of DOS's @command{command.com}. Unfortunately this
20407 emulation is incomplete; for instance it does not handle command
20408 substitutions. Using @code{@@SHELL@@} means that your makefile will
20409 benefit from the same improved shell, such as @command{bash} or
20410 @command{ksh}, that was discovered during @command{configure}, so that
20411 you aren't fighting two different sets of shell bugs between the two
20414 Do not rely on whether @command{make}'s @code{SHELL} settings are
20415 exported to subprocesses, as implementations differ:
20418 $ @kbd{cat Makefile}
20420 @@printf '%s\n' '$(SHELL)'
20422 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # BSD make, AIX make
20425 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # GNU make
20430 @node Parallel Make
20431 @section Parallel Make
20432 @cindex Parallel @command{make}
20434 Support for parallel execution in @command{make} implementation varies.
20435 Generally, using GNU make is your best bet.
20437 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20438 reuse the same shell for multiple commands within one recipe. This can
20439 have various unexpected consequences. For example, changes of directories
20440 or variables persist between recipes, so that:
20444 @@var=value; cd /; pwd; echo $$var; echo $$$$
20445 @@pwd; echo $$var; echo $$$$
20449 may output the following with @code{make -j1}, at least on NetBSD up to
20450 5.1 and FreeBSD up to 8.2:
20462 while without @option{-j1}, or with @option{-B}, the output looks less
20475 Another consequence is that, if one command in a recipe uses @code{exit 0}
20476 to indicate a successful exit, the shell will be gone and the remaining
20477 commands of this recipe will not be executed.
20479 The BSD @command{make} implementations, when run in parallel mode,
20480 will also pass the @command{Makefile} recipes to the shell through
20481 its standard input, thus making it unusable from the recipes:
20484 $ @kbd{cat Makefile}
20486 @@read line; echo LINE: $$line
20487 @c $$ @c restore font-lock
20488 $ @kbd{echo foo | make read}
20490 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20495 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20496 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20497 modifiers'' by dynamically modifying the active shell flags. This
20498 behavior has the effects of potentially clobbering the exit status
20499 of recipes silenced with the @code{@@} modifier if they also unset
20500 the @option{errexit} shell flag, and of mangling the output in
20504 $ @kbd{cat Makefile}
20506 @@echo $$-; set +e; false
20508 -echo $$-; false; echo set -
20509 $ @kbd{make a; echo status: $?}
20513 $ @kbd{make -j1 a; echo status: $?}
20517 echo $-; echo set -
20525 You can avoid all these issues by using the @option{-B} option to enable
20526 compatibility semantics. However, that will effectively also disable
20527 all parallelism as that will cause prerequisites to be updated in the
20528 order they are listed in a rule.
20530 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20531 @command{make}, and Solaris @command{dmake}), when invoked with a
20532 @option{-j@var{N}} option, connect the standard output and standard
20533 error of all their child processes to pipes or temporary regular
20534 files. This can lead to subtly different semantics in the behavior
20535 of the spawned processes. For example, even if the @command{make}
20536 standard output is connected to a tty, the recipe command will not be:
20539 $ @kbd{cat Makefile}
20541 @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20542 $ @kbd{make -j 2} # FreeBSD 8.2 make
20544 $ @kbd{make -j 2} # NetBSD 5.1 make
20547 $ @kbd{dmake -j 2} # Solaris 10 dmake
20548 @var{hostname} --> 1 job
20549 @var{hostname} --> Job output
20557 $ @kbd{make -j 2} # GNU make, Heirloom make
20562 The above examples also show additional status output produced in parallel
20563 mode for targets being updated by Solaris @command{dmake} and NetBSD
20564 @command{make} (but @emph{not} by FreeBSD @command{make}).
20566 Furthermore, parallel runs of those @command{make} implementations will
20567 route standard error from commands that they spawn into their own
20568 standard output, and may remove leading whitespace from output lines.
20571 @node Comments in Make Rules
20572 @section Comments in Make Rules
20573 @cindex Comments in @file{Makefile} rules
20574 @cindex @file{Makefile} rules and comments
20576 Do not try to put comments (lines beginning with @samp{#}) in a rule, as
20577 they end the rule. It is OK for a rule line to start with a tab
20578 followed by @samp{#}, as a comment passed to a shell that does nothing.
20580 To use the @samp{#} character in a command, put it in a rule not a
20581 macro, as the character cannot portably appear in macros
20582 (@pxref{Comments in Make Macros}). So for example, assuming the output
20583 variable @code{COMMENT_CHAR} stands for @samp{#}, the following replaces
20584 @samp{@@COMMENT_CHAR@@} by @samp{#} in a generated header:
20588 sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20589 '$(srcdir)/foo.h.in' > $@@
20592 The funny shell quoting avoids a substitution at @command{config.status}
20593 run time of the left-hand side of the @command{sed} @samp{s} command.
20595 @node Newlines in Make Rules
20596 @section Newlines in Make Rules
20597 @cindex Newlines in @file{Makefile} rules
20598 @cindex @file{Makefile} rules and newlines
20600 In shell scripts, newlines can be used inside string literals. But in
20601 the shell statements of @file{Makefile} rules, this is not possible:
20602 a newline not preceded by a backslash separates commands, whereas a
20603 newline preceded by a backslash becomes part of the shell statement.
20604 So, how can a newline be used in a string literal?
20606 The trick is to set up a shell variable @code{nl} that contains a newline.
20607 For example, the following uses a multi-line @samp{sed} expression that
20608 appends an empty line after every line of a file:
20612 eval "$$(printf 'nl="\n"\n')"; \
20613 sed "a\\$$nl" input >$@@
20616 @node Comments in Make Macros
20617 @section Comments in Make Macros
20618 @cindex Comments in @file{Makefile} macros
20619 @cindex @file{Makefile} macros and comments
20621 In macro definitions, text from @samp{#} until line end is ignored,
20622 which has the unfortunate effect of disallowing @samp{#} even in quotes.
20623 Thus, the following does not work:
20626 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20630 as @samp{CPPFLAGS} is expanded to @samp{"-DCOMMENT_CHAR='}.
20632 GNU @command{make}, when not in POSIX mode, lets you put
20633 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20634 @samp{\#}. However, this usage is not portable.
20635 @xref{Comments in Make Rules}, for a portable alternative.
20637 Even without quoting involved, comments can have surprising effects,
20638 because the whitespace before them is part of the variable value:
20641 foo = bar # trailing comment
20642 print: ; @@echo "$(foo)."
20646 prints @samp{bar .}, which is usually not intended, and can expose
20647 @command{make} bugs as described below.
20649 @node Trailing whitespace in Make Macros
20650 @section Trailing whitespace in Make Macros
20651 @cindex whitespace in @file{Makefile} macros
20652 @cindex @file{Makefile} macros and whitespace
20654 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20655 substitutions and appends another spurious suffix:
20660 print: ; @@echo $(foo:=.test)
20664 prints @samp{bar.test .test}.
20666 BSD and Solaris @command{make} implementations do not honor trailing
20667 whitespace in macro definitions as POSIX requires:
20670 foo = bar # Note the space after "bar".
20671 print: ; @@echo $(foo)t
20675 prints @samp{bart} instead of @samp{bar t}. To work around this, you
20676 can use a helper macro as in the previous example.
20679 @node Command-line Macros and whitespace
20680 @section Command-line Macros and whitespace
20681 @cindex whitespace in command-line macros
20682 @cindex command-line, macros set on
20683 @cindex environment, macros set from
20685 Some @command{make} implementations may strip trailing whitespace off
20686 of macros set on the command line in addition to leading whitespace.
20687 Further, some may strip leading whitespace off of macros set from
20688 environment variables:
20691 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20692 foo=' f f ' make -f - bar=' b b '}
20693 x f f xb b x # AIX, BSD, GNU make
20694 xf f xb b x # HP-UX
20695 x f f xb bx # Solaris make
20699 @node obj/ and Make
20700 @section The @file{obj/} Subdirectory and Make
20701 @cindex @file{obj/}, subdirectory
20702 @cindex BSD @command{make} and @file{obj/}
20704 Never name one of your subdirectories @file{obj/} if you don't like
20707 If an @file{obj/} directory exists, BSD @command{make} enters it
20708 before reading the makefile. Hence the makefile in the
20709 current directory is not read.
20712 $ @kbd{cat Makefile}
20715 $ @kbd{cat obj/Makefile}
20718 $ @kbd{make} # GNU make
20721 $ @kbd{pmake} # BSD make
20726 @node make -k Status
20727 @section Exit Status of @code{make -k}
20728 @cindex @code{make -k}
20730 Do not rely on the exit status of @code{make -k}. Some implementations
20731 reflect whether they encountered an error in their exit status; other
20732 implementations always succeed.
20735 $ @kbd{cat Makefile}
20738 $ @kbd{make -k; echo exit status: $?} # GNU make
20740 make: *** [all] Error 1
20742 $ @kbd{pmake -k; echo exit status: $?} # BSD make
20744 *** Error code 1 (continuing)
20748 @node VPATH and Make
20749 @section @code{VPATH} and Make
20750 @cindex @code{VPATH}
20752 POSIX does not specify the semantics of @code{VPATH}. Typically,
20753 @command{make} supports @code{VPATH}, but its implementation is not
20756 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20757 portable to recent-enough popular implementations of @command{make}, but
20758 to keep the resulting makefiles portable, a package's makefile
20759 prototypes must take the following issues into account. These issues
20760 are complicated and are often poorly understood, and installers who use
20761 @code{VPATH} should expect to find many bugs in this area. If you use
20762 @code{VPATH}, the simplest way to avoid these portability bugs is to
20763 stick with GNU @command{make}, since it is the most
20764 commonly-used @command{make} among Autoconf users.
20766 Here are some known issues with some @code{VPATH}
20770 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
20771 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
20772 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
20773 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
20774 * Make Target Lookup:: More details about @code{VPATH} lookup
20777 @node Variables listed in VPATH
20778 @subsection Variables listed in @code{VPATH}
20779 @cindex @code{VPATH} and variables
20780 @cindex variables and @code{VPATH}
20782 Do not set @code{VPATH} to the value of another variable, for example
20783 @samp{VPATH = $(srcdir)}, because some ancient versions of
20784 @command{make} do not do variable substitutions on the value of
20785 @code{VPATH}. For example, use this
20788 srcdir = @@srcdir@@
20793 rather than @samp{VPATH = $(srcdir)}. Note that with GNU
20794 Automake, there is no need to set this yourself.
20796 @node VPATH and Double-colon
20797 @subsection @code{VPATH} and Double-colon Rules
20798 @cindex @code{VPATH} and double-colon rules
20799 @cindex double-colon rules and @code{VPATH}
20801 With ancient versions of Sun @command{make},
20802 any assignment to @code{VPATH} causes @command{make} to execute only
20803 the first set of double-colon rules.
20804 However, this problem is no longer of practical concern.
20806 @node $< in Explicit Rules
20807 @subsection @code{$<} Not Supported in Explicit Rules
20808 @cindex explicit rules, @code{$<}, and @code{VPATH}
20809 @cindex @code{$<}, explicit rules, and @code{VPATH}
20810 @cindex @code{VPATH}, explicit rules, and @code{$<}
20812 Using @code{$<} in explicit rules is not portable.
20813 The prerequisite file must be named explicitly in the rule. If you want
20814 to find the prerequisite via a @code{VPATH} search, you have to code the
20815 whole thing manually. @xref{Build Directories}.
20817 @node Automatic Rule Rewriting
20818 @subsection Automatic Rule Rewriting
20819 @cindex @code{VPATH} and automatic rule rewriting
20820 @cindex automatic rule rewriting and @code{VPATH}
20822 Some @command{make} implementations, such as Solaris,
20823 search for prerequisites in @code{VPATH} and
20824 then rewrite each occurrence as a plain word in the rule.
20828 # This isn't portable to GNU make.
20835 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20836 found in @file{../pkg/src}.
20838 However, this rule leads to real problems in practice. For example, if
20839 the source directory contains an ordinary file named @file{test} that is
20840 used in a dependency, Solaris @command{make} rewrites commands like
20841 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20842 @dots{}}, which is typically undesirable. In fact, @command{make} is
20843 completely unaware of shell syntax used in the rules, so the VPATH
20844 rewrite can potentially apply to @emph{any} whitespace-separated word
20845 in a rule, including shell variables, functions, and keywords.
20848 $ @kbd{mkdir build}
20850 $ @kbd{cat > Makefile <<'END'}
20852 all: arg func for echo
20853 func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20856 $ @kbd{touch ../arg ../func ../for ../echo}
20858 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20859 ../func "hello world"
20860 sh: syntax error at line 1: `do' unexpected
20865 To avoid this problem, portable makefiles should never mention a source
20866 file or dependency whose name is that of a shell keyword like @file{for}
20867 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20868 @command{test}, or a shell function or variable used in the corresponding
20869 @command{Makefile} recipe.
20871 Because of these problems GNU @command{make} and many other @command{make}
20872 implementations do not rewrite commands, so portable makefiles should
20873 search @code{VPATH} manually. It is tempting to write this:
20876 # This isn't portable to Solaris make.
20879 cp `test -f if.c || echo $(VPATH)/`if.c f.c
20883 However, the ``prerequisite rewriting'' still applies here. So if
20884 @file{if.c} is in @file{../pkg/src}, Solaris @command{make}
20888 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20899 and thus fails. Oops.
20901 A simple workaround, and good practice anyway, is to use @samp{$?} and
20902 @samp{$@@} when possible:
20911 but this does not generalize well to commands with multiple
20912 prerequisites. A more general workaround is to rewrite the rule so that
20913 the prerequisite @file{if.c} never appears as a plain word. For
20914 example, these three rules would be safe, assuming @file{if.c} is in
20915 @file{../pkg/src} and the other files are in the working directory:
20920 cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20922 cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20924 cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20927 Things get worse when your prerequisites are in a macro.
20931 HEADERS = f.h g.h h.h
20932 install-HEADERS: $(HEADERS)
20933 for i in $(HEADERS); do \
20934 $(INSTALL) -m 644 \
20935 `test -f $$i || echo $(VPATH)/`$$i \
20936 $(DESTDIR)$(includedir)/$$i; \
20937 @c $$ restore font-lock
20941 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20942 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20943 where @code{f.h} and @code{g.h} are plain words and are hence
20944 subject to @code{VPATH} adjustments.
20946 If the three files are in @file{../pkg/src}, the rule is run as:
20949 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20951 `test -f $i || echo ../pkg/src/`$i \
20952 /usr/local/include/$i; \
20956 where the two first @command{install} calls fail. For instance,
20957 consider the @code{f.h} installation:
20961 `test -f ../pkg/src/f.h || \
20964 /usr/local/include/../pkg/src/f.h;
20973 /usr/local/include/../pkg/src/f.h;
20976 Note that the manual @code{VPATH} search did not cause any problems here;
20977 however this command installs @file{f.h} in an incorrect directory.
20979 Trying to quote @code{$(HEADERS)} in some way, as we did for
20980 @code{foo.c} a few makefiles ago, does not help:
20983 install-HEADERS: $(HEADERS)
20984 headers='$(HEADERS)'; \
20985 for i in $$headers; do \
20986 $(INSTALL) -m 644 \
20987 `test -f $$i || echo $(VPATH)/`$$i \
20988 $(DESTDIR)$(includedir)/$$i; \
20992 Now, @code{headers='$(HEADERS)'} macro-expands to:
20995 headers='f.h g.h h.h'
20999 but @code{g.h} is still a plain word. (As an aside, the idiom
21000 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
21001 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
21002 syntax error on @code{for i in;}.)
21004 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
21008 HEADERS = f.h g.h h.h
21009 install-HEADERS: $(HEADERS)
21010 headers='$(HEADERS)'; \
21011 for i in $$headers; do \
21012 i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
21013 $(INSTALL) -m 644 \
21014 `test -f $$i || echo $(VPATH)/`$$i \
21015 $(DESTDIR)$(includedir)/$$i; \
21016 @c $$ restore font-lock
21021 Automake does something similar.
21023 @node Make Target Lookup
21024 @subsection Make Target Lookup
21025 @cindex @code{VPATH}, resolving target pathnames
21027 GNU @command{make} uses a complex algorithm to decide when it
21028 should use files found via a @code{VPATH} search. @xref{Search
21029 Algorithm, , How Directory Searches are Performed, make, The GNU Make
21032 If a target needs to be rebuilt, GNU @command{make} discards the
21033 file name found during the @code{VPATH} search for this target, and
21034 builds the file locally using the file name given in the makefile.
21035 If a target does not need to be rebuilt, GNU @command{make} uses the
21036 file name found during the @code{VPATH} search.
21038 Other @command{make} implementations, like NetBSD @command{make}, are
21039 easier to describe: the file name found during the @code{VPATH} search
21040 is used whether the target needs to be rebuilt or not. Therefore
21041 new files are created locally, but existing files are updated at their
21042 @code{VPATH} location.
21044 OpenBSD and FreeBSD @command{make}, however,
21046 @code{VPATH} search for a dependency that has an explicit rule.
21047 This is extremely annoying.
21049 When attempting a @code{VPATH} build for an autoconfiscated package
21050 (e.g., @code{mkdir build && cd build && ../configure}), this means
21052 @command{make} builds everything locally in the @file{build}
21053 directory, while BSD @command{make} builds new files locally and
21054 updates existing files in the source directory.
21057 $ @kbd{cat Makefile}
21060 foo.x bar.x: newer.x
21061 @@echo Building $@@
21062 $ @kbd{touch ../bar.x}
21063 $ @kbd{touch ../newer.x}
21064 $ @kbd{make} # GNU make
21067 $ @kbd{pmake} # NetBSD make
21070 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21073 $ @kbd{make} # GNU make
21075 $ @kbd{pmake} # NetBSD make
21077 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21082 Note how NetBSD @command{make} updates @file{../bar.x} in its
21083 VPATH location, and how FreeBSD and OpenBSD
21084 @command{make} always
21085 update @file{bar.x}, even when @file{../bar.x} is up to date.
21087 Another point worth mentioning is that once GNU @command{make} has
21088 decided to ignore a @code{VPATH} file name (e.g., it ignored
21089 @file{../bar.x} in the above example) it continues to ignore it when
21090 the target occurs as a prerequisite of another rule.
21092 The following example shows that GNU @command{make} does not look up
21093 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21094 because it ignored the @code{VPATH} result of @file{bar.x} while running
21095 the @code{bar.x: newer.x} rule.
21098 $ @kbd{cat Makefile}
21102 @@echo Building $@@
21106 $ @kbd{touch ../bar.x}
21107 $ @kbd{touch ../newer.x}
21108 $ @kbd{make} # GNU make
21111 cp: cannot stat 'bar.x': No such file or directory
21112 make: *** [bar.y] Error 1
21113 $ @kbd{pmake} # NetBSD make
21117 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21118 echo Building bar.x
21120 cp: cannot stat 'bar.x': No such file or directory
21124 Note that if you drop away the command from the @code{bar.x: newer.x}
21125 rule, GNU @command{make} magically starts to work: it
21126 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21127 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21128 uses. FreeBSD and OpenBSD still don't work, though.
21131 $ @kbd{cat Makefile}
21138 $ @kbd{touch ../bar.x}
21139 $ @kbd{touch ../newer.x}
21140 $ @kbd{make} # GNU make
21143 $ @kbd{pmake} # NetBSD make
21146 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21148 cp: cannot stat 'bar.x': No such file or directory
21152 It seems the sole solution that would please every @command{make}
21153 implementation is to never rely on @code{VPATH} searches for targets.
21154 In other words, @code{VPATH} should be reserved to sources that are not built.
21157 @node Single Suffix Rules
21158 @section Single Suffix Rules and Separated Dependencies
21159 @cindex Single Suffix Inference Rule
21160 @cindex Rule, Single Suffix Inference
21161 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21162 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21165 @cindex Separated Dependencies
21166 @dfn{Separated dependencies} simply refers to listing the prerequisite
21167 of a target, without defining a rule. Usually one can list on the one
21168 hand side, the rules, and on the other hand side, the dependencies.
21170 Solaris @command{make} does not support separated dependencies for
21171 targets defined by single suffix rules:
21174 $ @kbd{cat Makefile}
21179 $ @kbd{touch foo.in}
21186 while GNU Make does:
21192 Makefile foo foo.in
21195 Note it works without the @samp{foo: foo.in} dependency.
21198 $ @kbd{cat Makefile}
21207 and it works with double suffix inference rules:
21210 $ @kbd{cat Makefile}
21212 .SUFFIXES: .in .out
21219 As a result, in such a case, you have to write target rules.
21221 @node Timestamps and Make
21222 @section Timestamp Resolution and Make
21223 @cindex timestamp resolution
21224 Traditionally, file timestamps had 1-second resolution, and
21225 @command{make} used those timestamps to determine whether one file was
21226 newer than the other. However, many modern file systems have
21227 timestamps with 1-nanosecond resolution. Some @command{make}
21228 implementations look at the entire timestamp; others ignore the
21229 fractional part, which can lead to incorrect results. Normally this
21230 is not a problem, but in some extreme cases you may need to use tricks
21231 like @samp{sleep 1} to work around timestamp truncation bugs.
21233 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21234 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21235 Tools}). Hence you should be wary of rules like this:
21242 as @file{dest} often appears to be older than @file{src} after the
21243 timestamp is truncated, and this can cause @command{make} to do
21244 needless rework the next time it is invoked. To work around this
21245 problem, you can use a timestamp file, e.g.:
21253 Apart from timestamp resolution, there are also differences in handling
21254 equal timestamps. HP-UX @command{make} updates targets if it has the
21255 same timestamp as one of its prerequisites, in violation of POSIX rules.
21257 This can cause spurious rebuilds for repeated runs of @command{make}.
21258 This in turn can cause @command{make} to fail if it tries to rebuild
21259 generated files in a possibly read-only source tree with tools not
21260 present on the end-user machine. Use GNU @command{make} instead.
21264 @c ======================================== Portable C and C++ Programming
21266 @node Portable C and C++
21267 @chapter Portable C and C++ Programming
21268 @cindex Portable C and C++ programming
21270 C and C++ programs often use low-level features of the underlying
21271 system, and therefore are often more difficult to make portable to other
21274 Several standards have been developed to help make your programs more
21275 portable. If you write programs with these standards in mind, you can
21276 have greater confidence that your programs work on a wide variety
21279 @uref{https://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21280 Standards Supported by GCC}
21283 @xref{Standards, , Language Standards Supported by
21284 GCC, gcc, Using the GNU Compiler Collection
21287 for a list of C-related standards. Many programs also assume the
21288 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX standard}.
21291 @cindex C89, C99, C11, C17, and C23
21292 The first widely used C variant was K&R C, which predates any C
21293 standard. K&R C compilers are no longer of practical interest, though,
21294 and Autoconf assumes at least C89, the first C standard,
21295 which is sometimes called ``C90'' due to a delay in standardization.
21296 C has since gone through the standards C99, C11, C17, and C23, and
21297 Autoconf is compatible with all these standards.
21299 Program portability is a huge topic, and this section can only briefly
21300 introduce common pitfalls. @xref{System Portability, , Portability
21301 between System Types, standards, The GNU Coding Standards}, for
21305 * Varieties of Unportability:: How to make your programs unportable
21306 * Integer Overflow:: When integers get too large
21307 * Preprocessor Arithmetic:: @code{#if} expression problems
21308 * Null Pointers:: Properties of null pointers
21309 * Buffer Overruns:: Subscript errors and the like
21310 * Volatile Objects:: @code{volatile} and signals
21311 * Floating Point Portability:: Portable floating-point arithmetic
21312 * Exiting Portably:: Exiting and the exit status
21315 @node Varieties of Unportability
21316 @section Varieties of Unportability
21317 @cindex portability
21319 Autoconf tests and ordinary programs often need to test what is allowed
21320 on a system, and therefore they may need to deliberately exceed the
21321 boundaries of what the standards allow, if only to see whether an
21322 optional feature is present. When you write such a program, you should
21323 keep in mind the difference between constraints, unspecified behavior,
21324 and undefined behavior.
21326 In C, a @dfn{constraint} is a rule that the compiler must enforce. An
21327 example constraint is that C programs must not declare a bit-field with
21328 negative width. Tests can therefore reliably assume that programs with
21329 negative-width bit-fields are rejected by a compiler that conforms
21332 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21333 multiple possibilities. For example, the order of evaluation of
21334 function arguments is unspecified. Some unspecified behavior is
21335 @dfn{implementation-defined}, i.e., documented by the implementation,
21336 but since Autoconf tests cannot read the documentation they cannot
21337 distinguish between implementation-defined and other unspecified
21338 behavior. It is common for Autoconf tests to probe implementations to
21339 determine otherwise-unspecified behavior.
21341 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21342 the implementation to do anything it pleases. For example,
21343 dereferencing a null pointer leads to undefined behavior. If possible,
21344 test programs should avoid undefined behavior, since a program with
21345 undefined behavior might succeed on a test that should fail.
21347 The above rules apply to programs that are intended to conform to the
21348 standard. However, strictly-conforming programs are quite rare, since
21349 the standards are so limiting. A major goal of Autoconf is to support
21350 programs that use implementation features not described by the standard,
21351 and it is fairly common for test programs to violate the above rules, if
21352 the programs work well enough in practice.
21354 @node Integer Overflow
21355 @section Integer Overflow
21356 @cindex integer overflow
21357 @cindex overflow, signed integer
21358 @cindex signed integer overflow
21359 @cindex wraparound arithmetic
21361 Although some traditional C programs assume that signed integer overflow
21362 wraps around reliably using two's complement arithmetic, the C standard
21363 says that program behavior is undefined on overflow, and these C
21364 programs may not work on many modern implementations.
21367 * Integer Overflow Basics:: Why integer overflow is a problem
21368 * Signed Overflow Examples:: Examples of code assuming wraparound
21369 * Optimization and Wraparound:: Optimizations that break uses of wraparound
21370 * Signed Overflow Advice:: Practical advice for signed overflow issues
21371 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
21374 @node Integer Overflow Basics
21375 @subsection Basics of Integer Overflow
21376 @cindex integer overflow
21377 @cindex overflow, signed integer
21378 @cindex signed integer overflow
21379 @cindex wraparound arithmetic
21381 In languages like C, integer overflow wraps around for unsigned
21382 integer types that are at least as wide as @code{unsigned int};
21383 e.g., @code{UINT_MAX + 1} yields zero.
21384 This is guaranteed by the C standard and is
21385 portable in practice, unless you specify aggressive,
21386 nonstandard optimization options
21387 suitable only for special applications.
21389 In contrast, the C standard says that signed integer overflow leads to
21390 undefined behavior where a program can do anything, including dumping
21391 core or overrunning a buffer. The misbehavior can even precede the
21392 overflow. Such an overflow can occur during addition, subtraction,
21393 multiplication, division, and left shift. It can even occur for
21394 unsigned types like @code{unsigned short int} that are narrower
21395 than @code{int}, as values of these types are widened to @code{int}
21396 before computation.
21398 Despite this requirement of the standard, some C programs assume that
21399 signed integer overflow silently wraps around modulo a power of two,
21400 using two's complement arithmetic, so long as you convert the resulting
21401 value to a signed integer type. These programs can have problems,
21402 especially when optimization is enabled. If you assume a GCC-like
21403 compiler, you can work around the problems by compiling with GCC's
21404 @code{-fwrapv} option; however, this is not portable.
21406 For historical reasons C17 and earlier also allowed implementations with
21407 ones' complement or signed magnitude arithmetic, but C23 requires
21408 two's complement and it is safe to assume two's complement nowadays.
21410 Also, overflow can occur when converting an out-of-range value to a
21411 signed integer type. Here a standard implementation must define what
21412 happens, and this can include raising an exception. Although practical
21413 implementations typically wrap around silently in this case, a few
21414 debugging implementations trap instead.
21416 @node Signed Overflow Examples
21417 @subsection Examples of Code Assuming Wraparound Overflow
21418 @cindex integer overflow
21419 @cindex overflow, signed integer
21420 @cindex signed integer overflow
21421 @cindex wraparound arithmetic
21423 There was long a tension between what the C standard requires for signed
21424 integer overflow, and what traditional C programs commonly assumed. The
21425 standard allows aggressive optimizations based on assumptions that
21426 overflow never occurs, but traditionally many C programs relied on overflow
21427 wrapping around. Although these programs did not conform to the standard,
21428 they formerly worked in practice because traditionally compilers did not
21429 optimize in such a way that would break the programs. Nowadays, though,
21430 compilers do perform these optimizations, so portable programs can no
21431 longer assume reliable wraparound on signed integer overflow.
21433 The C Standard says that if a program has signed integer overflow its
21434 behavior is undefined, and the undefined behavior can even precede the
21435 overflow. To take an extreme example:
21437 @c Inspired by Robert Dewar's example in
21438 @c <https://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21440 if (password == expected_password)
21441 allow_superuser_privileges ();
21442 else if (counter++ == INT_MAX)
21445 printf ("%d password mismatches\n", counter);
21449 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21450 @code{counter++} must overflow and the behavior is undefined, so the C
21451 standard allows the compiler to optimize away the test against
21452 @code{INT_MAX} and the @code{abort} call.
21453 Worse, if an earlier bug in the program lets the compiler deduce that
21454 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21455 the C standard allows the compiler to optimize away the password test
21456 and generate code that allows superuser privileges unconditionally.
21458 Here is an example derived from the 7th Edition Unix implementation of
21459 @code{atoi} (1979-01-10):
21465 while (*p >= '0' && *p <= '9')
21466 n = n * 10 + *p++ - '0';
21467 return (f ? -n : n);
21471 Even if the input string is in range, on most modern machines this has
21472 signed overflow when computing the most negative integer (the @code{-n}
21473 overflows) or a value near an extreme integer (the @code{+}
21476 Here is another example, derived from the 7th Edition implementation of
21477 @code{rand} (1979-01-10). Here the programmer expects both
21478 multiplication and addition to wrap on overflow:
21481 static long int randx = 1;
21483 randx = randx * 1103515245 + 12345;
21484 return (randx >> 16) & 077777;
21487 In the following example, derived from the GNU C Library 2.15
21488 implementation of @code{mktime} (2012-03-21), the code assumes
21489 wraparound arithmetic in @code{+} to detect signed overflow:
21493 int sec_requested, sec_adjustment;
21495 t1 = t + sec_requested;
21496 t2 = t1 + sec_adjustment;
21497 if (((t1 < t) != (sec_requested < 0))
21498 | ((t2 < t1) != (sec_adjustment < 0)))
21502 Although some of these examples will likely behave as if signed integer
21503 overflow wraps around reliably, other examples are likely to misbehave
21504 when optimization is enabled. All these examples should be avoided in
21505 portable code because signed integer overflow is not reliable on modern
21506 systems, and it's not worth worrying about which of these examples
21507 happen to work on most platforms and which do not.
21509 @node Optimization and Wraparound
21510 @subsection Optimizations That Break Wraparound Arithmetic
21511 @cindex loop induction
21513 Compilers sometimes generate code that is incompatible with wraparound
21514 integer arithmetic. A simple example is an algebraic simplification: a
21515 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21516 because it assumes that @code{i * 2000} does not overflow. The
21517 translation is not equivalent to the original when overflow occurs:
21518 e.g., in the typical case of 32-bit signed two's complement wraparound
21519 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21520 the original expression returns @minus{}2147483 but the optimized
21521 version returns the mathematically correct value 2147484.
21523 More subtly, loop induction optimizations often exploit the undefined
21524 behavior of signed overflow. Consider the following contrived function
21529 sumc (int lo, int hi)
21532 for (int i = lo; i <= hi; i++)
21539 To avoid multiplying by 53 each time through the loop, an optimizing
21540 compiler might internally transform @code{sumc} to the equivalent of the
21545 transformed_sumc (int lo, int hi)
21549 for (int ic = lo * 53; ic <= hic; ic += 53)
21556 This transformation is allowed by the C standard, but it is invalid for
21557 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21558 overflow in computing expressions like @code{hi * 53} can cause the
21559 expression @code{i <= hi} to yield a different value from the
21560 transformed expression @code{ic <= hic}.
21562 For this reason, compilers that use loop induction and similar
21563 techniques often do not support reliable wraparound arithmetic when a
21564 loop induction variable like @code{ic} is involved. Since loop
21565 induction variables are generated by the compiler, and are not visible
21566 in the source code, it is not always trivial to say whether the problem
21569 Hardly any code actually depends on wraparound arithmetic in cases like
21570 these, so in practice these loop induction optimizations are almost
21571 always useful. However, edge cases in this area can cause problems.
21575 for (int j = 1; 0 < j; j *= 2)
21580 Here, the loop attempts to iterate through all powers of 2 that
21581 @code{int} can represent, but the C standard allows a compiler to
21582 optimize away the comparison and generate an infinite loop,
21583 under the argument that behavior is undefined on overflow. As of this
21584 writing this optimization is done on some platforms by
21585 GCC with @option{-O2}, so this code is not portable in practice.
21587 @node Signed Overflow Advice
21588 @subsection Practical Advice for Signed Overflow Issues
21589 @cindex integer overflow
21590 @cindex overflow, signed integer
21591 @cindex signed integer overflow
21592 @cindex wraparound arithmetic
21594 Ideally the safest approach is to avoid signed integer overflow
21595 entirely. For example, instead of multiplying two signed integers, you
21596 can convert them to double-width integers, multiply the wider values,
21597 then test whether the result is in the narrower range. Or you can use
21598 more-complicated code employing unsigned integers of the same width.
21600 Rewriting code in this way will be inconvenient, though, especially if
21601 the signed values might be negative and no wider type is available.
21602 Using unsigned arithmetic to check for overflow is
21603 particularly painful to do portably and efficiently when dealing with an
21604 integer type like @code{uid_t} whose width and signedness vary from
21605 platform to platform. Also, this approach may hurt performance.
21607 Hence it is often useful to maintain code that needs
21608 wraparound on overflow, instead of rewriting the code. The rest of this
21609 section attempts to give practical advice for this situation.
21611 To detect integer overflow portably when attempting operations like
21612 @code{sum = a + b}, you can use the C23 @code{<stdckdint.h>} macros
21613 @code{ckd_add}, @code{ckd_sub}, and @code{ckd_mul}.
21614 The following code adds two integers with overflow wrapping around
21615 reliably in the sum:
21618 #include <stdckdint.h>
21620 /* Set sum = a + b, with wraparound. */
21621 if (ckd_add (&sum, a, b))
21622 /* 'sum' has just the low order bits. */;
21624 /* 'sum' is the correct answer. */;
21627 To be portable to pre-C23 platforms you can use Gnulib's
21628 @code{stdckdint} module, which emulates this part of C23 (@pxref{Gnulib}).
21629 Invoking the @code{stdckdint} macros typically costs just one machine
21630 instruction for the arithmetic and another instruction for the rare
21631 branch on overflow.
21633 If your code uses a signed loop index, make sure that the index cannot
21634 overflow, along with all signed expressions derived from the index.
21635 Here is a contrived example of problematic code with two instances of
21639 for (int i = INT_MAX - 10; i <= INT_MAX; i++)
21642 report_overflow ();
21648 Because of the two overflows, a compiler might optimize away or
21649 transform the two comparisons in a way that is incompatible with the
21650 wraparound assumption.
21652 If your code is intended to be compiled only by GCC and
21653 assumes wraparound behavior, and you want to insulate it
21654 against any GCC optimizations that would fail to support that
21655 behavior, you should use GCC's @option{-fwrapv} option, which
21656 causes signed overflow to wrap around reliably (except for division and
21657 remainder, as discussed in the next section).
21659 If you need to write portable code and therefore cannot assume that
21660 signed integer overflow wraps around reliably, you should consider
21661 debugging with a GCC option that causes signed overflow to raise an
21662 exception. These options include @option{-fsanitize=undefined} and
21665 @node Signed Integer Division
21666 @subsection Signed Integer Division and Integer Overflow
21667 @cindex division, integer
21670 integer division is not always harmless: for example, on CPUs of the
21671 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21672 which by default terminates the program. Worse, taking the remainder
21673 of these two values typically yields the same signal on these CPUs,
21674 behavior that the C standard allows.
21676 @node Preprocessor Arithmetic
21677 @section Preprocessor Arithmetic
21678 @cindex preprocessor arithmetic
21680 In C99 and later, preprocessor arithmetic, used for @code{#if}
21682 be evaluated as if all signed values are of type @code{intmax_t} and all
21683 unsigned values of type @code{uintmax_t}. Many compilers are buggy in
21684 this area, though. For example, as of 2007, Sun C mishandles @code{#if
21685 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21686 @code{long long int}. Also, some older preprocessors mishandle
21687 constants ending in @code{LL}. To work around these problems, you can
21688 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21689 @code{configure}-time rather than at @code{#if}-time.
21691 @node Null Pointers
21692 @section Properties of Null Pointers
21693 @cindex null pointers
21695 Most modern hosts reliably fail when you attempt to dereference a null
21698 On almost all modern hosts, null pointers use an all-bits-zero internal
21699 representation, so you can reliably use @code{memset} with 0 to set all
21700 the pointers in an array to null values.
21702 If @code{p} is a null pointer to an object type, the C expression
21703 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21704 the standard says that it has undefined behavior.
21706 @node Buffer Overruns
21707 @section Buffer Overruns and Subscript Errors
21708 @cindex buffer overruns
21710 Buffer overruns and subscript errors are the most common dangerous
21711 errors in C programs. They result in undefined behavior because storing
21712 outside an array typically modifies storage that is used by some other
21713 object, and most modern systems lack runtime checks to catch these
21714 errors. Programs should not rely on buffer overruns being caught.
21716 There is one exception to the usual rule that a portable program cannot
21717 address outside an array. In C, it is valid to compute the address just
21718 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21719 so long as you do not dereference the resulting pointer. But it is not
21720 valid to compute the address just before an object, e.g., @code{&a[-1]};
21721 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}. On
21722 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21723 reliable in general, and it is usually easy enough to avoid the
21724 potential portability problem, e.g., by allocating an extra unused array
21725 element at the start or end.
21727 @uref{https://@/www.valgrind.org/, Valgrind} can catch many overruns.
21728 GCC users might also consider using the @option{-fsanitize=} options
21730 @xref{Instrumentation Options, , Program Instrumentation Options,
21731 gcc, Using the GNU Compiler Collection (GCC)}.
21733 Buffer overruns are usually caused by off-by-one errors, but there are
21734 more subtle ways to get them.
21736 Using @code{int} values to index into an array or compute array sizes
21737 causes problems on typical 64-bit hosts where an array index might
21738 be @math{2^{31}} or larger. Index values of type @code{size_t} avoid this
21739 problem, but cannot be negative. Index values of type @code{ptrdiff_t}
21740 are signed, and are wide enough in practice.
21742 If you add or multiply two numbers to calculate an array size, e.g.,
21743 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21744 multiplication overflows.
21746 Many implementations of the @code{alloca} function silently misbehave
21747 and can generate buffer overflows if given sizes that are too large.
21748 The size limits are implementation dependent, but are at least 4000
21749 bytes on all platforms that we know about.
21751 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21752 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21753 portable code should not use them unless the inputs are known to be
21754 within certain limits. The time-related functions can overflow their
21755 buffers if given timestamps out of range (e.g., a year less than -999
21756 or greater than 9999). Time-related buffer overflows cannot happen with
21757 recent-enough versions of the GNU C library, but are possible
21759 implementations. The @code{gets} function is the worst, since it almost
21760 invariably overflows its buffer when presented with an input line larger
21763 @node Volatile Objects
21764 @section Volatile Objects
21765 @cindex volatile objects
21767 The keyword @code{volatile} is often misunderstood in portable code.
21768 Its use inhibits some memory-access optimizations, but programmers often
21769 wish that it had a different meaning than it actually does.
21771 @code{volatile} was designed for code that accesses special objects like
21772 memory-mapped device registers whose contents spontaneously change.
21773 Such code is inherently low-level, and it is difficult to specify
21774 portably what @code{volatile} means in these cases. The C standard
21775 says, ``What constitutes an access to an object that has
21776 volatile-qualified type is implementation-defined,'' so in theory each
21777 implementation is supposed to fill in the gap by documenting what
21778 @code{volatile} means for that implementation. In practice, though,
21779 this documentation is usually absent or incomplete.
21781 One area of confusion is the distinction between objects defined with
21782 volatile types, and volatile lvalues. From the C standard's point of
21783 view, an object defined with a volatile type has externally visible
21784 behavior. You can think of such objects as having little oscilloscope
21785 probes attached to them, so that the user can observe some properties of
21786 accesses to them, just as the user can observe data written to output
21787 files. However, accesses via volatile lvalues to ordinary objects
21788 are merely side effects (i.e., changes to the state of the execution
21789 environment), and the implementation is not required to document
21790 their visibility any further. For example:
21793 /* Declare and access a volatile object.
21794 Accesses to X are "visible" to users. */
21795 static int volatile x;
21798 /* Access two ordinary objects via a volatile lvalue.
21799 Although each read and write is a side effect,
21800 the accesses are not directly "visible" to users. */
21802 int *z = malloc (sizeof *z);
21811 Programmers often wish that @code{volatile} meant ``Perform the memory
21812 access here and now, without merging several memory accesses, without
21813 changing the memory word size, and without reordering.'' But the C
21814 standard does not require this. For objects defined with a volatile
21815 type, accesses must be done before the next sequence point; but
21816 otherwise merging, reordering, and word-size change is allowed.
21818 Even when accessing objects defined with a volatile type,
21819 the C standard allows only
21820 extremely limited signal handlers: in C23 the behavior is undefined if a
21821 signal handler refers to any non-local object that is not a lock-free
21822 atomic object and that is not @code{constexpr} (other than by writing to
21823 a @code{sig_atomic_t volatile} object), or calls any standard library
21824 function other than from a small set that includes @code{abort},
21825 @code{_Exit}, @code{quick_exit}, some @code{<stdatomic.h>} functions,
21826 and @code{signal}. Hence C compilers need not worry about a signal
21827 handler disturbing ordinary computation. POSIX allows some additional
21828 behavior in a portable signal handler, but is still quite restrictive.
21829 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21830 GNU Compiler Collection (GCC)}, for some
21831 restrictions imposed by GCC. @xref{Defining Handlers, ,
21832 Defining Signal Handlers, libc, The GNU C Library}, for some
21833 restrictions imposed by the GNU C library. Restrictions
21834 differ on other platforms.
21836 If possible, it is best to use a signal handler that fits within the
21837 limits imposed by the C and POSIX standards.
21839 If this is not practical, you can try the following rules of thumb. A
21840 signal handler should access only volatile lvalues, preferably lvalues
21841 that refer to objects defined with a volatile type, and should not
21842 assume that the accessed objects have an internally consistent state
21843 if they are larger than a machine word. Furthermore, installers
21844 should employ compilers and compiler options that are commonly used
21845 for building operating system kernels, because kernels often need more
21846 from @code{volatile} than the C Standard requires, and installers who
21847 compile an application in a similar environment can sometimes benefit
21848 from the extra constraints imposed by kernels on compilers.
21849 Admittedly we are hand-waving somewhat here, as there are few
21850 guarantees in this area; the rules of thumb may help to fix some bugs
21851 but there is a good chance that they will not fix them all.
21853 For @code{volatile}, C++ has the same problems that C does.
21854 Multithreaded applications have even more problems with @code{volatile},
21855 but they are beyond the scope of this section.
21857 The bottom line is that using @code{volatile} typically hurts
21858 performance but should not hurt correctness. In some cases its use
21859 does help correctness, but these cases are often so poorly understood
21860 that all too often adding @code{volatile} to a data structure merely
21861 alleviates some symptoms of a bug while not fixing the bug in general.
21863 @node Floating Point Portability
21864 @section Floating Point Portability
21865 @cindex floating point
21867 Almost all modern systems use IEEE-754 floating point, and it is safe to
21868 assume IEEE-754 in most portable code these days. For more information,
21869 please see David Goldberg's classic paper
21870 @uref{https://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21871 Scientist Should Know About Floating-Point Arithmetic}.
21873 @node Exiting Portably
21874 @section Exiting Portably
21875 @cindex exiting portably
21877 A C or C++ program can exit with status @var{N} by returning
21878 @var{N} from the @code{main} function. Portable programs are supposed
21879 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21880 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21881 fail by exiting with status 1, and test programs that assume POSIX can
21882 fail by exiting with status values from 1 through 255.
21884 A program can also exit with status @var{N} by passing @var{N} to the
21885 @code{exit} function, and a program can fail by calling the @code{abort}
21886 function. If a program is specialized to just some platforms, it can fail
21887 by calling functions specific to those platforms, e.g., @code{_exit}
21888 (POSIX). However, like other functions, an exit
21889 function should be declared, typically by including a header. For
21890 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21891 either directly or via the default includes (@pxref{Default Includes}).
21893 A program can fail due to undefined behavior such as dereferencing a null
21894 pointer, but this is not recommended as undefined behavior allows an
21895 implementation to do whatever it pleases and this includes exiting
21899 @c ================================================== Manual Configuration
21901 @node Manual Configuration
21902 @chapter Manual Configuration
21904 A few kinds of features can't be guessed automatically by running test
21905 programs. For example, the details of the object-file format, or
21906 special options that need to be passed to the compiler or linker.
21907 Autoconf provides a uniform method for handling unguessable features,
21908 by giving each operating system a @dfn{canonical system type}, also
21909 known as a @dfn{canonical name} or @dfn{target triplet}.
21911 @prindex @command{config.guess}
21912 @prindex @command{config.sub}
21914 If you use any of the macros described in this chapter, you must
21915 distribute the helper scripts @command{config.guess} and
21916 @command{config.sub} along with your source code. Some Autoconf macros
21917 use these macros internally, so you may need to distribute these scripts
21918 even if you do not use any of these macros yourself. @xref{Input}, for
21919 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21920 to control in which directory @command{configure} looks for helper
21921 scripts, and where to get the scripts from.
21924 * Specifying Target Triplets:: Specifying target triplets
21925 * Canonicalizing:: Getting the canonical system type
21926 * Using System Type:: What to do with the system type
21929 @node Specifying Target Triplets
21930 @section Specifying target triplets
21931 @cindex System type
21932 @cindex Target triplet
21933 @c This node used to be named Specifying Names. The @anchor allows old
21934 @c links to still work.
21935 @anchor{Specifying Names}
21938 @command{configure} scripts can make decisions based on a canonical name
21939 for the system type, or @dfn{target triplet}, which has the form:
21940 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21941 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21943 @command{configure} can usually guess the canonical name for the type of
21944 system it's running on. To do so it runs a script called
21945 @command{config.guess}, which infers the name using the @code{uname}
21946 command or symbols predefined by the C preprocessor.
21948 Alternately, the user can specify the system type with command line
21949 arguments to @command{configure} (@pxref{System Types}. Doing so is
21951 cross-compiling. In the most complex case of cross-compiling, three
21952 system types are involved. The options to specify them are:
21955 @item --build=@var{build-type}
21956 the type of system on which the package is being configured and
21957 compiled. It defaults to the result of running @command{config.guess}.
21958 Specifying a @var{build-type} that differs from @var{host-type} enables
21959 cross-compilation mode.
21961 @item --host=@var{host-type}
21962 the type of system on which the package runs. By default it is the
21963 same as the build machine. The tools that get used to build and
21964 manipulate binaries will, by default, all be prefixed with
21965 @code{@var{host-type}-}, such as @code{@var{host-type}-gcc},
21966 @code{@var{host-type}-g++}, @code{@var{host-type}-ar}, and
21967 @code{@var{host-type}-nm}. If the binaries produced by these tools can
21968 be executed by the build system, the configure script will make use of
21969 it in @code{AC_RUN_IFELSE} invocations; otherwise, cross-compilation
21970 mode is enabled. Specifying a @var{host-type} that differs
21971 from @var{build-type}, when @var{build-type} was also explicitly
21972 specified, equally enables cross-compilation mode.
21974 @item --target=@var{target-type}
21975 the type of system for which any compiler tools in the package
21976 produce code (rarely needed). By default, it is the same as host.
21979 If you mean to override the result of @command{config.guess} but
21980 still produce binaries for the build machine, use @option{--build},
21981 not @option{--host}.
21983 So, for example, to produce binaries for 64-bit MinGW, use a command
21987 ./configure --host=x86_64-w64-mingw64
21990 If your system has the ability to execute MinGW binaries but you don't
21991 want to make use of this feature and instead prefer cross-compilation
21992 guesses, use a command like this:
21995 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
21999 Note that if you do not specify @option{--host}, @command{configure}
22000 fails if it can't run the code generated by the specified compiler. For
22001 example, configuring as follows fails:
22004 ./configure CC=x86_64-w64-mingw64-gcc
22007 When cross-compiling, @command{configure} will warn about any tools
22008 (compilers, linkers, assemblers) whose name is not prefixed with the
22009 host type. This is an aid to users performing cross-compilation.
22010 Continuing the example above, if a cross-compiler named @command{cc} is
22011 used with a native @command{pkg-config}, then libraries found by
22012 @command{pkg-config} will likely cause subtle build failures; but using
22013 the names @command{x86_64-w64-mingw64-gcc} and
22014 @command{x86_64-w64-mingw64-pkg-config}
22015 avoids any confusion. Avoiding the warning is as simple as creating the
22016 correct symlinks naming the cross tools.
22018 @cindex @command{config.sub}
22019 @command{configure} recognizes short aliases for some system types; for
22020 example, @samp{mingw64} can be used instead of
22021 @samp{x86_64-pc-mingw64}. @command{configure} runs a script called
22022 @command{config.sub} to canonicalize system type aliases.
22024 This section deliberately omits the description of the obsolete
22025 interface; see @ref{Hosts and Cross-Compilation}.
22028 @node Canonicalizing
22029 @section Getting the Canonical System Type
22030 @cindex System type
22031 @cindex Canonical system type
22033 The following macros make the system type available to @command{configure}
22036 @ovindex build_alias
22037 @ovindex host_alias
22038 @ovindex target_alias
22040 The variables @samp{build_alias}, @samp{host_alias}, and
22041 @samp{target_alias} are always exactly the arguments of @option{--build},
22042 @option{--host}, and @option{--target}; in particular, they are left empty
22043 if the user did not use them, even if the corresponding
22044 @code{AC_CANONICAL} macro was run. Any configure script may use these
22045 variables anywhere. These are the variables that should be used when in
22046 interaction with the user.
22048 If you need to recognize some special environments based on their system
22049 type, run the following macros to get canonical system names. These
22050 variables are not set before the macro call.
22052 @defmac AC_CANONICAL_BUILD
22053 @acindex{CANONICAL_BUILD}
22056 @ovindex build_vendor
22058 Compute the canonical build-system type variable, @code{build}, and its
22059 three individual parts @code{build_cpu}, @code{build_vendor}, and
22062 If @option{--build} was specified, then @code{build} is the
22063 canonicalization of @code{build_alias} by @command{config.sub},
22064 otherwise it is determined by the shell script @command{config.guess}.
22067 @defmac AC_CANONICAL_HOST
22068 @acindex{CANONICAL_HOST}
22071 @ovindex host_vendor
22073 Compute the canonical host-system type variable, @code{host}, and its
22074 three individual parts @code{host_cpu}, @code{host_vendor}, and
22077 If @option{--host} was specified, then @code{host} is the
22078 canonicalization of @code{host_alias} by @command{config.sub},
22079 otherwise it defaults to @code{build}.
22082 @defmac AC_CANONICAL_TARGET
22083 @acindex{CANONICAL_TARGET}
22085 @ovindex target_cpu
22086 @ovindex target_vendor
22088 Compute the canonical target-system type variable, @code{target}, and its
22089 three individual parts @code{target_cpu}, @code{target_vendor}, and
22092 If @option{--target} was specified, then @code{target} is the
22093 canonicalization of @code{target_alias} by @command{config.sub},
22094 otherwise it defaults to @code{host}.
22097 Note that there can be artifacts due to the backward compatibility
22098 code. @xref{Hosts and Cross-Compilation}, for more.
22100 @node Using System Type
22101 @section Using the System Type
22103 In @file{configure.ac} the system type is generally used by one or more
22104 @code{case} statements to select system-specifics. Shell wildcards can
22105 be used to match a group of system types.
22107 For example, an extra assembler code object file could be chosen, giving
22108 access to a CPU cycle counter register. @code{$(CYCLE_OBJ)} in the
22109 following would be used in a makefile to add the object to a
22110 program or library.
22114 [aarch64*-*-*], [CYCLE_OBJ=pmccntr.o],
22115 [i?86-*-*], [CYCLE_OBJ=rdtsc.o],
22117 AC_SUBST([CYCLE_OBJ])
22120 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22121 to select variant source files, for example optimized code for some
22122 CPUs. The configured CPU type doesn't always indicate exact CPU types,
22123 so some runtime capability checks may be necessary too.
22127 [aarch64*-*-*], [AC_CONFIG_LINKS([dither.c:aarch64/dither.c])],
22128 [powerpc*-*-*], [AC_CONFIG_LINKS([dither.c:powerpc/dither.c])],
22129 [AC_CONFIG_LINKS([dither.c:generic/dither.c])])
22132 The host system type can also be used to find cross-compilation tools
22133 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22135 The above examples all show @samp{$host}, since this is where the code
22136 is going to run. Only rarely is it necessary to test @samp{$build}
22137 (which is where the build is being done).
22139 Whenever you're tempted to use @samp{$host} it's worth considering
22140 whether some sort of probe would be better. New system types come along
22141 periodically or previously missing features are added. Well-written
22142 probes can adapt themselves to such things, but hard-coded lists of
22143 names can't. Here are some guidelines,
22147 Availability of libraries and library functions should always be checked
22150 Variant behavior of system calls is best identified with runtime tests
22151 if possible, but bug workarounds or obscure difficulties might have to
22152 be driven from @samp{$host}.
22154 Assembler code is inevitably highly CPU-specific and is best selected
22155 according to @samp{$host_cpu}.
22157 Assembler variations like underscore prefix on globals or ELF versus
22158 COFF type directives are however best determined by probing, perhaps
22159 even examining the compiler output.
22162 @samp{$target} is for use by a package creating a compiler or similar.
22163 For ordinary packages it's meaningless and should not be used. It
22164 indicates what the created compiler should generate code for, if it can
22165 cross-compile. @samp{$target} generally selects various hard-coded CPU
22166 and system conventions, since usually the compiler or tools under
22167 construction themselves determine how the target works.
22170 @c ===================================================== Site Configuration.
22172 @node Site Configuration
22173 @chapter Site Configuration
22175 @command{configure} scripts support several kinds of local configuration
22176 decisions. There are ways for users to specify where external software
22177 packages are, include or exclude optional features, install programs
22178 under modified names, and set default values for @command{configure}
22182 * Help Formatting:: Customizing @samp{configure --help}
22183 * External Software:: Working with other optional software
22184 * Package Options:: Selecting optional features
22185 * Pretty Help Strings:: Formatting help string
22186 * Option Checking:: Controlling checking of @command{configure} options
22187 * Site Details:: Configuring site details
22188 * Transforming Names:: Changing program names when installing
22189 * Site Defaults:: Giving @command{configure} local defaults
22192 @node Help Formatting
22193 @section Controlling Help Output
22195 Users consult @samp{configure --help} to learn of configuration
22196 decisions specific to your package. By default, @command{configure}
22197 breaks this output into sections for each type of option; within each
22198 section, help strings appear in the order @file{configure.ac} defines
22204 --enable-bar include bar
22211 @defmac AC_PRESERVE_HELP_ORDER
22212 @acindex{PRESERVE_HELP_ORDER}
22214 Request an alternate @option{--help} format, in which options of all
22215 types appear together, in the order defined. Call this macro before any
22216 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22219 Optional Features and Packages:
22221 --enable-bar include bar
22227 @node External Software
22228 @section Working With External Software
22229 @cindex External software
22231 Some packages require, or can optionally use, other software packages
22232 that are already installed. The user can give @command{configure}
22233 command line options to specify which such external software to use.
22234 The options have one of these forms:
22236 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22239 --with-@var{package}@r{[}=@var{arg}@r{]}
22240 --without-@var{package}
22243 For example, @option{--with-gnu-ld} means work with the GNU linker
22244 instead of some other linker. @option{--with-x} means work with The X
22247 The user can give an argument by following the package name with
22248 @samp{=} and the argument. Giving an argument of @samp{no} is for
22249 packages that are used by default; it says to @emph{not} use the
22250 package. An argument that is neither @samp{yes} nor @samp{no} could
22251 include a name or number of a version of the other package, to specify
22252 more precisely which other package this program is supposed to work
22253 with. If no argument is given, it defaults to @samp{yes}.
22254 @option{--without-@var{package}} is equivalent to
22255 @option{--with-@var{package}=no}.
22257 Normally @command{configure} scripts complain about
22258 @option{--with-@var{package}} options that they do not support.
22259 @xref{Option Checking}, for details, and for how to override the
22262 For each external software package that may be used, @file{configure.ac}
22263 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22264 user asked to use it. Whether each package is used or not by default,
22265 and which arguments are valid, is up to you.
22267 @anchor{AC_ARG_WITH}
22268 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22269 @ovar{action-if-given}, @ovar{action-if-not-given})
22271 If the user gave @command{configure} the option @option{--with-@var{package}}
22272 or @option{--without-@var{package}}, run shell commands
22273 @var{action-if-given}. If neither option was given, run shell commands
22274 @var{action-if-not-given}. The name @var{package} indicates another
22275 software package that this program should work with. It should consist
22276 only of alphanumeric characters, dashes, plus signs, and dots.
22278 The option's argument is available to the shell commands
22279 @var{action-if-given} in the shell variable @code{withval}, which is
22280 actually just the value of the shell variable named
22281 @code{with_@var{package}}, with any non-alphanumeric characters in
22282 @var{package} changed into @samp{_}. You may use that variable instead,
22285 Note that @var{action-if-not-given} is not expanded until the point that
22286 @code{AC_ARG_WITH} was expanded. If you need the value of
22287 @code{with_@var{package}} set to a default value by the time argument
22288 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22289 diversion (@pxref{m4_divert_text}) (if done as an argument to
22290 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22293 The argument @var{help-string} is a description of the option that
22296 --with-readline support fancy command line editing
22300 @var{help-string} may be more than one line long, if more detail is
22301 needed. Just make sure the columns line up in @samp{configure
22302 --help}. Avoid tabs in the help string. The easiest way to provide the
22303 proper leading whitespace is to format your @var{help-string} with the macro
22304 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22306 The following example shows how to use the @code{AC_ARG_WITH} macro in
22307 a common situation. You want to let the user decide whether to enable
22308 support for an external library (e.g., the readline library); if the user
22309 specified neither @option{--with-readline} nor @option{--without-readline},
22310 you want to enable support for readline only if the library is available
22313 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22315 AC_ARG_WITH([readline],
22316 [AS_HELP_STRING([--with-readline],
22317 [support fancy command line editing @@<:@@default=check@@:>@@])],
22319 [: m4_divert_text([DEFAULTS], [with_readline=check])])
22322 AS_IF([test "x$with_readline" != xno],
22323 [AC_CHECK_LIB([readline], [main],
22324 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22325 AC_DEFINE([HAVE_LIBREADLINE], [1],
22326 [Define if you have libreadline])
22328 [if test "x$with_readline" != xcheck; then
22330 [--with-readline was given, but test for readline failed])
22335 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22336 possibility to enable support for the readline library, in case it is still
22337 experimental and not well tested, and is therefore disabled by default.
22339 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22341 AC_ARG_WITH([readline],
22342 [AS_HELP_STRING([--with-readline],
22343 [enable experimental support for readline])],
22345 [with_readline=no])
22348 AS_IF([test "x$with_readline" != xno],
22349 [AC_CHECK_LIB([readline], [main],
22350 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22351 AC_DEFINE([HAVE_LIBREADLINE], [1],
22352 [Define if you have libreadline])
22355 [--with-readline was given, but test for readline failed])],
22359 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22360 possibility to disable support for the readline library, given that it is
22361 an important feature and that it should be enabled by default.
22363 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22365 AC_ARG_WITH([readline],
22366 [AS_HELP_STRING([--without-readline],
22367 [disable support for readline])],
22369 [with_readline=yes])
22372 AS_IF([test "x$with_readline" != xno],
22373 [AC_CHECK_LIB([readline], [main],
22374 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22375 AC_DEFINE([HAVE_LIBREADLINE], [1],
22376 [Define if you have libreadline])
22379 [readline test failed (--without-readline to disable)])],
22383 These three examples can be easily adapted to the case where
22384 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22385 @ref{Package Options}).
22388 @node Package Options
22389 @section Choosing Package Options
22390 @cindex Package options
22391 @cindex Options, package
22393 If a software package has optional compile-time features, the user can
22394 give @command{configure} command line options to specify whether to
22395 compile them. The options have one of these forms:
22397 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22400 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22401 --disable-@var{feature}
22404 These options allow users to choose which optional features to build and
22405 install. @option{--enable-@var{feature}} options should never make a
22406 feature behave differently or cause one feature to replace another.
22407 They should only cause parts of the program to be built rather than left
22410 The user can give an argument by following the feature name with
22411 @samp{=} and the argument. Giving an argument of @samp{no} requests
22412 that the feature @emph{not} be made available. A feature with an
22413 argument looks like @option{--enable-debug=stabs}. If no argument is
22414 given, it defaults to @samp{yes}. @option{--disable-@var{feature}} is
22415 equivalent to @option{--enable-@var{feature}=no}.
22417 Normally @command{configure} scripts complain about
22418 @option{--enable-@var{package}} options that they do not support.
22419 @xref{Option Checking}, for details, and for how to override the
22422 For each optional feature, @file{configure.ac} should call
22423 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22424 to include it. Whether each feature is included or not by default, and
22425 which arguments are valid, is up to you.
22427 @anchor{AC_ARG_ENABLE}
22428 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22429 @ovar{action-if-given}, @ovar{action-if-not-given})
22430 @acindex{ARG_ENABLE}
22431 If the user gave @command{configure} the option
22432 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22433 shell commands @var{action-if-given}. If neither option was given, run
22434 shell commands @var{action-if-not-given}. The name @var{feature}
22435 indicates an optional user-level facility. It should consist only of
22436 alphanumeric characters, dashes, plus signs, and dots.
22438 The option's argument is available to the shell commands
22439 @var{action-if-given} in the shell variable @code{enableval}, which is
22440 actually just the value of the shell variable named
22441 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22442 @var{feature} changed into @samp{_}. You may use that variable instead,
22443 if you wish. The @var{help-string} argument is like that of
22444 @code{AC_ARG_WITH} (@pxref{External Software}).
22446 Note that @var{action-if-not-given} is not expanded until the point that
22447 @code{AC_ARG_ENABLE} was expanded. If you need the value of
22448 @code{enable_@var{feature}} set to a default value by the time argument
22449 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22450 diversion (@pxref{m4_divert_text}) (if done as an argument to
22451 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22454 You should format your @var{help-string} with the macro
22455 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22457 See the examples suggested with the definition of @code{AC_ARG_WITH}
22458 (@pxref{External Software}) to get an idea of possible applications of
22459 @code{AC_ARG_ENABLE}.
22462 @node Pretty Help Strings
22463 @section Making Your Help Strings Look Pretty
22464 @cindex Help strings
22466 Properly formatting the @samp{help strings} which are used in
22467 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22468 (@pxref{Package Options}) can be challenging. Specifically, you want
22469 your own @samp{help strings} to line up in the appropriate columns of
22470 @samp{configure --help} just like the standard Autoconf @samp{help
22471 strings} do. This is the purpose of the @code{AS_HELP_STRING} macro.
22473 @anchor{AS_HELP_STRING}
22474 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22475 @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22476 @asindex{HELP_STRING}
22478 Expands into a help string that looks pretty when the user executes
22479 @samp{configure --help}. It is typically used in @code{AC_ARG_WITH}
22480 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22481 Options}). The following example makes this clearer.
22485 [AS_HELP_STRING([--with-foo],
22486 [use foo (default is no)])],
22487 [use_foo=$withval],
22491 Then the last few lines of @samp{configure --help} appear like
22495 --enable and --with options recognized:
22496 --with-foo use foo (default is no)
22499 Macro expansion is performed on the first argument. However, the second
22500 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22501 list of text to be reformatted, and is not subject to macro expansion.
22502 Since it is not expanded, it should not be double quoted.
22503 @xref{Autoconf Language}, for a more detailed explanation.
22505 The @code{AS_HELP_STRING} macro is particularly helpful when the
22506 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22507 arguments, as shown in the following example. Be aware that
22508 @var{left-hand-side} may not expand to unbalanced quotes,
22509 although quadrigraphs can be used.
22512 AC_DEFUN([MY_ARG_WITH],
22513 [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22514 [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22515 [use $1 (default is $2)])],
22516 [use_[]$1=$withval],
22518 MY_ARG_WITH([a_b], [no])
22521 Here, the last few lines of @samp{configure --help} will include:
22524 --enable and --with options recognized:
22525 --with-a-b use a_b (default is no)
22528 The parameters @var{indent-column} and @var{wrap-column} were introduced
22529 in Autoconf 2.62. Generally, they should not be specified; they exist
22530 for fine-tuning of the wrapping.
22532 AS_HELP_STRING([--option], [description of option])
22533 @result{} --option description of option
22534 AS_HELP_STRING([--option], [description of option], [15], [30])
22535 @result{} --option description of
22541 @node Option Checking
22542 @section Controlling Checking of @command{configure} Options
22543 @cindex Options, Package
22545 The @command{configure} script checks its command-line options against a
22546 list of known options, like @option{--help} or @option{--config-cache}.
22547 An unknown option ordinarily indicates a mistake by the user and
22548 @command{configure} halts with an error. However, by default unknown
22549 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22550 options elicit only a warning, to support configuring entire source
22553 Source trees often contain multiple packages with a top-level
22554 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22555 (@pxref{Subdirectories}). Because the packages generally support
22556 different @option{--with-@var{package}} and
22557 @option{--enable-@var{feature}} options, the GNU Coding
22558 Standards say they must accept unrecognized options without halting.
22559 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22560 automatically disables the warnings.
22562 This default behavior may be modified in two ways. First, the installer
22563 can invoke @code{configure --disable-option-checking} to disable
22564 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22565 options to turn them into fatal errors, respectively. Second, the
22566 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22568 @defmac AC_DISABLE_OPTION_CHECKING
22569 @acindex{DISABLE_OPTION_CHECKING}
22571 By default, disable warnings related to any unrecognized
22572 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22573 options. This is implied by @code{AC_CONFIG_SUBDIRS}.
22575 The installer can override this behavior by passing
22576 @option{--enable-option-checking} (enable warnings) or
22577 @option{--enable-option-checking=fatal} (enable errors) to
22578 @command{configure}.
22583 @section Configuring Site Details
22584 @cindex Site details
22586 Some software packages require complex site-specific information. Some
22587 examples are host names to use for certain services, company names, and
22588 email addresses to contact. Since some configuration scripts generated
22589 by Metaconfig ask for such information interactively, people sometimes
22590 wonder how to get that information in Autoconf-generated configuration
22591 scripts, which aren't interactive.
22593 Such site configuration information should be put in a file that is
22594 edited @emph{only by users}, not by programs. The location of the file
22595 can either be based on the @code{prefix} variable, or be a standard
22596 location such as the user's home directory. It could even be specified
22597 by an environment variable. The programs should examine that file at
22598 runtime, rather than at compile time. Runtime configuration is more
22599 convenient for users and makes the configuration process simpler than
22600 getting the information while configuring. @xref{Directory Variables, ,
22601 Variables for Installation Directories, standards, The GNU Coding
22602 Standards}, for more information on where to put data files.
22604 @node Transforming Names
22605 @section Transforming Program Names When Installing
22606 @cindex Transforming program names
22607 @cindex Program names, transforming
22609 Autoconf supports changing the names of programs when installing them.
22610 In order to use these transformations, @file{configure.ac} must call the
22611 macro @code{AC_ARG_PROGRAM}.
22613 @defmac AC_ARG_PROGRAM
22614 @acindex{ARG_PROGRAM}
22615 @ovindex program_transform_name
22616 Place in output variable @code{program_transform_name} a sequence of
22617 @code{sed} commands for changing the names of installed programs.
22619 If any of the options described below are given to @command{configure},
22620 program names are transformed accordingly. Otherwise, if
22621 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22622 is given, the target type followed by a dash is used as a prefix.
22623 Otherwise, no program name transformation is done.
22627 * Transformation Options:: @command{configure} options to transform names
22628 * Transformation Examples:: Sample uses of transforming names
22629 * Transformation Rules:: Makefile uses of transforming names
22632 @node Transformation Options
22633 @subsection Transformation Options
22635 You can specify name transformations by giving @command{configure} these
22636 command line options:
22639 @item --program-prefix=@var{prefix}
22640 prepend @var{prefix} to the names;
22642 @item --program-suffix=@var{suffix}
22643 append @var{suffix} to the names;
22645 @item --program-transform-name=@var{expression}
22646 perform @code{sed} substitution @var{expression} on the names.
22649 @node Transformation Examples
22650 @subsection Transformation Examples
22652 These transformations are useful with programs that can be part of a
22653 cross-compilation development environment. For example, a
22654 cross-assembler running on x86-64 configured with
22655 @option{--target=aarch64-linux-gnu} is normally installed as
22656 @file{aarch64-linux-gnu-as}, rather than @file{as}, which could be confused
22657 with a native x86-64 assembler.
22659 You can force a program name to begin with @file{g}, if you don't want
22660 GNU programs installed on your system to shadow other programs with
22661 the same name. For example, if you configure GNU @code{diff} with
22662 @option{--program-prefix=g}, then when you run @samp{make install} it is
22663 installed as @file{/usr/local/bin/gdiff}.
22665 As a more sophisticated example, you could use
22668 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22672 to prepend @samp{g} to most of the program names in a source tree,
22673 excepting those like @code{gdb} that already have one and those like
22674 @code{less} and @code{lesskey} that aren't GNU programs. (That is
22675 assuming that you have a source tree containing those programs that is
22676 set up to use this feature.)
22678 One way to install multiple versions of some programs simultaneously is
22679 to append a version number to the name of one or both. For example, if
22680 you want to keep Autoconf version 1 around for awhile, you can configure
22681 Autoconf version 2 using @option{--program-suffix=2} to install the
22682 programs as @file{/usr/local/bin/autoconf2},
22683 @file{/usr/local/bin/autoheader2}, etc. Nevertheless, pay attention
22684 that only the binaries are renamed, therefore you'd have problems with
22685 the library files which might overlap.
22687 @node Transformation Rules
22688 @subsection Transformation Rules
22690 Here is how to use the variable @code{program_transform_name} in a
22691 @file{Makefile.in}:
22694 PROGRAMS = cp ls rm
22695 transform = @@program_transform_name@@
22697 for p in $(PROGRAMS); do \
22698 $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22699 sed '$(transform)'`; \
22703 for p in $(PROGRAMS); do \
22704 rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22705 @c $$ restore font-lock
22709 It is guaranteed that @code{program_transform_name} is never empty, and
22710 that there are no useless separators. Therefore you may safely embed
22711 @code{program_transform_name} within a sed program using @samp{;}:
22714 transform = @@program_transform_name@@
22715 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22718 Whether to do the transformations on documentation files (Texinfo or
22719 @code{man}) is a tricky question; there seems to be no perfect answer,
22720 due to the several reasons for name transforming. Documentation is not
22721 usually particular to a specific architecture, and Texinfo files do not
22722 conflict with system documentation. But they might conflict with
22723 earlier versions of the same files, and @code{man} pages sometimes do
22724 conflict with system documentation. As a compromise, it is probably
22725 best to do name transformations on @code{man} pages but not on Texinfo
22728 @node Site Defaults
22729 @section Setting Site Defaults
22730 @cindex Site defaults
22731 @cindex config.site
22733 Autoconf-generated @command{configure} scripts allow your site to provide
22734 default values for some configuration values. You do this by creating
22735 site- and system-wide initialization files.
22737 @evindex CONFIG_SITE
22738 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22739 uses its value as a space-separated list of shell scripts to read;
22740 it is recommended that these be absolute file names. Otherwise, it
22741 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22742 then @file{@var{prefix}/etc/config.site} if it exists. Thus,
22743 settings in machine-specific files override those in machine-independent
22744 ones in case of conflict.
22746 Site files can be arbitrary shell scripts, but only certain kinds of
22747 code are really appropriate to be in them. Because @command{configure}
22748 reads any cache file after it has read any site files, a site file can
22749 define a default cache file to be shared between all Autoconf-generated
22750 @command{configure} scripts run on that system (@pxref{Cache Files}). If
22751 you set a default cache file in a site file, it is a good idea to also
22752 set the output variable @code{CC} in that site file, because the cache
22753 file is only valid for a particular compiler, but many systems have
22756 You can examine or override the value set by a command line option to
22757 @command{configure} in a site file; options set shell variables that have
22758 the same names as the options, with any dashes turned into underscores.
22759 The exceptions are that @option{--without-} and @option{--disable-} options
22760 are like giving the corresponding @option{--with-} or @option{--enable-}
22761 option and the value @samp{no}. Thus, @option{--cache-file=localcache}
22762 sets the variable @code{cache_file} to the value @samp{localcache};
22763 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22764 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22765 variable @code{prefix} to the value @samp{/usr}; etc.
22767 Site files are also good places to set default values for other output
22768 variables, such as @code{CFLAGS}, if you need to give them non-default
22769 values: anything you would normally do, repetitively, on the command
22770 line. If you use non-default values for @var{prefix} or
22771 @var{exec_prefix} (wherever you locate the site file), you can set them
22772 in the site file if you specify it with the @code{CONFIG_SITE}
22773 environment variable.
22775 You can set some cache values in the site file itself. Doing this is
22776 useful if you are cross-compiling, where it is impossible to check features
22777 that require running a test program. You could ``prime the cache'' by
22778 setting those values correctly for that system in
22779 @file{@var{prefix}/etc/config.site}. To find out the names of the cache
22780 variables you need to set, see the documentation of the respective
22781 Autoconf macro. If the variables or their semantics are undocumented,
22782 you may need to look for shell variables with @samp{_cv_} in their names
22783 in the affected @command{configure} scripts, or in the Autoconf M4
22784 source code for those macros; but in that case, their name or semantics
22785 may change in a future Autoconf version.
22787 The cache file is careful to not override any variables set in the site
22788 files. Similarly, you should not override command-line options in the
22789 site files. Your code should check that variables such as @code{prefix}
22790 and @code{cache_file} have their default values (as set near the top of
22791 @command{configure}) before changing them.
22793 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}. The
22794 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22795 file (if @code{CONFIG_SITE} is not set to a different file).
22798 # /usr/share/local/gnu/share/config.site for configure
22800 # Change some defaults.
22801 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22802 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22803 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22804 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22805 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
22807 # Give Autoconf 2.x generated configure scripts a shared default
22808 # cache file for feature test results, architecture-specific.
22809 if test "$cache_file" = /dev/null; then
22810 cache_file="$prefix/var/config.cache"
22811 # A cache file is only valid for one C compiler.
22816 @c Leave this use of "File system" rendered as one word, but
22817 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22818 @cindex File@/system Hierarchy Standard
22821 Another use of @file{config.site} is for priming the directory variables
22822 @c "File system", but slightly obfuscated, as above.
22823 in a manner consistent with the File@/system Hierarchy Standard
22824 (FHS). Once the following file is installed at
22825 @file{/usr/share/config.site}, a user can execute simply
22826 @code{./configure --prefix=/usr} to get all the directories chosen in
22827 the locations recommended by FHS.
22830 # /usr/share/config.site for FHS defaults when installing below /usr,
22831 # and the respective settings were not changed on the command line.
22832 if test "$prefix" = /usr; then
22833 test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22834 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22835 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22839 @cindex @file{lib64}
22840 @cindex 64-bit libraries
22841 Likewise, on platforms where 64-bit libraries are built by default, then
22842 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22843 it is appropriate to install @file{/usr/local/@/share/config.site}:
22846 # /usr/local/share/config.site for platforms that prefer
22847 # the directory /usr/local/lib64 over /usr/local/lib.
22848 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22852 @c ============================================== Running configure Scripts.
22854 @node Running configure Scripts
22855 @chapter Running @command{configure} Scripts
22856 @cindex @command{configure}
22858 Below are instructions on how to configure a package that uses a
22859 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22860 file in the package. A plain-text version of @file{INSTALL} which you
22861 may use comes with Autoconf.
22864 * Basic Installation:: Instructions for typical cases
22865 * Compilers and Options:: Selecting compilers and optimization
22866 * Multiple Architectures:: Compiling for multiple architectures at once
22867 * Installation Names:: Installing in different directories
22868 * Optional Features:: Selecting optional features
22869 * System Types:: Specifying a system type
22870 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
22871 * Defining Variables:: Specifying the compiler etc.
22872 * configure Invocation:: Changing how @command{configure} runs
22876 @include install.texi
22879 @c ============================================== config.status Invocation
22881 @node config.status Invocation
22882 @chapter config.status Invocation
22883 @cindex @command{config.status}
22885 The @command{configure} script creates a file named @file{config.status},
22886 which actually configures, @dfn{instantiates}, the template files. It
22887 also records the configuration options that were specified when the
22888 package was last configured in case reconfiguring is needed.
22892 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22895 It configures each @var{tag}; if none are specified, all the templates
22896 are instantiated. A @var{tag} refers to a file or other tag associated
22897 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22898 macro (@pxref{Configuration Actions}). The files must be specified
22899 without their dependencies, as in
22902 ./config.status foobar
22909 ./config.status foobar:foo.in:bar.in
22912 The supported options are:
22917 Print a summary of the command line options, the list of the template
22922 Print the version number of Autoconf and the configuration settings,
22926 Print the configuration settings in reusable way, quoted for the shell,
22927 and exit. For example, for a debugging build that otherwise reuses the
22928 configuration from a different build directory @var{build-dir} of a
22929 package in @var{src-dir}, you could use the following:
22932 args=`@var{build-dir}/config.status --config`
22933 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22937 Note that it may be necessary to override a @option{--srcdir} setting
22938 that was saved in the configuration, if the arguments are used in a
22939 different build directory.
22944 Do not print progress messages.
22948 Don't remove the temporary files.
22950 @item --file=@var{file}[:@var{template}]
22951 Require that @var{file} be instantiated as if
22952 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used. Both
22953 @var{file} and @var{template} may be @samp{-} in which case the standard
22954 output and/or standard input, respectively, is used. If a
22955 @var{template} file name is relative, it is first looked for in the build
22956 tree, and then in the source tree. @xref{Configuration Actions}, for
22959 This option and the following ones provide one way for separately
22960 distributed packages to share the values computed by @command{configure}.
22961 Doing so can be useful if some of the packages need a superset of the
22962 features that one of them, perhaps a common library, does. These
22963 options allow a @file{config.status} file to create files other than the
22964 ones that its @file{configure.ac} specifies, so it can be used for a
22965 different package, or for extracting a subset of values. For example,
22968 echo '@@CC@@' | ./config.status --file=-
22972 provides the value of @code{@@CC@@} on standard output.
22974 @item --header=@var{file}[:@var{template}]
22975 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22978 Ask @file{config.status} to update itself and exit (no instantiation).
22979 This option is useful if you change @command{configure}, so that the
22980 results of some tests might be different from the previous run. The
22981 @option{--recheck} option reruns @command{configure} with the same arguments
22982 you used before, plus the @option{--no-create} option, which prevents
22983 @command{configure} from running @file{config.status} and creating
22984 @file{Makefile} and other files, and the @option{--no-recursion} option,
22985 which prevents @command{configure} from running other @command{configure}
22986 scripts in subdirectories. (This is so other Make rules can
22987 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22991 @file{config.status} checks several optional environment variables that
22992 can alter its behavior:
22994 @anchor{CONFIG_SHELL}
22995 @defvar CONFIG_SHELL
22996 @evindex CONFIG_SHELL
22997 The shell with which to run @command{configure}. It must be
22998 Bourne-compatible, and the absolute name of the shell should be passed.
22999 The default is a shell that supports @code{LINENO} if available, and
23000 @file{/bin/sh} otherwise.
23003 @defvar CONFIG_STATUS
23004 @evindex CONFIG_STATUS
23005 The file name to use for the shell script that records the
23006 configuration. The default is @file{./config.status}. This variable is
23007 useful when one package uses parts of another and the @command{configure}
23008 scripts shouldn't be merged because they are maintained separately.
23011 You can use @file{./config.status} in your makefiles. For example, in
23012 the dependencies given above (@pxref{Automatic Remaking}),
23013 @file{config.status} is run twice when @file{configure.ac} has changed.
23014 If that bothers you, you can make each run only regenerate the files for
23019 stamp-h: config.h.in config.status
23020 ./config.status config.h
23023 Makefile: Makefile.in config.status
23024 ./config.status Makefile
23028 The calling convention of @file{config.status} has changed; see
23029 @ref{Obsolete config.status Use}, for details.
23032 @c =================================================== Obsolete Constructs
23034 @node Obsolete Constructs
23035 @chapter Obsolete Constructs
23036 @cindex Obsolete constructs
23038 Autoconf changes, and throughout the years some constructs have been
23039 obsoleted. Most of the changes involve the macros, but in some cases
23040 the tools themselves, or even some concepts, are now considered
23043 You may completely skip this chapter if you are new to Autoconf. Its
23044 intention is mainly to help maintainers updating their packages by
23045 understanding how to move to more modern constructs.
23048 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
23049 * acconfig Header:: Additional entries in @file{config.h.in}
23050 * autoupdate Invocation:: Automatic update of @file{configure.ac}
23051 * Obsolete Macros:: Backward compatibility macros
23052 * Autoconf 1:: Tips for upgrading your files
23053 * Autoconf 2.13:: Some fresher tips
23056 @node Obsolete config.status Use
23057 @section Obsolete @file{config.status} Invocation
23059 @file{config.status} now supports arguments to specify the files to
23060 instantiate; see @ref{config.status Invocation}, for more details.
23061 Before, environment variables had to be used.
23063 @defvar CONFIG_COMMANDS
23064 @evindex CONFIG_COMMANDS
23065 The tags of the commands to execute. The default is the arguments given
23066 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23067 @file{configure.ac}.
23070 @defvar CONFIG_FILES
23071 @evindex CONFIG_FILES
23072 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23073 The default is the arguments given to @code{AC_OUTPUT} and
23074 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23077 @defvar CONFIG_HEADERS
23078 @evindex CONFIG_HEADERS
23079 The files in which to substitute C @code{#define} statements. The
23080 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23081 macro was not called, @file{config.status} ignores this variable.
23084 @defvar CONFIG_LINKS
23085 @evindex CONFIG_LINKS
23086 The symbolic links to establish. The default is the arguments given to
23087 @code{AC_CONFIG_LINKS}; if that macro was not called,
23088 @file{config.status} ignores this variable.
23091 In @ref{config.status Invocation}, using this old interface, the example
23097 stamp-h: config.h.in config.status
23098 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23099 CONFIG_HEADERS=config.h ./config.status
23102 Makefile: Makefile.in config.status
23103 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23104 CONFIG_FILES=Makefile ./config.status
23109 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23110 no need to set @code{CONFIG_HEADERS} in the @command{make} rules. Equally
23111 for @code{CONFIG_COMMANDS}, etc.)
23114 @node acconfig Header
23115 @section @file{acconfig.h}
23117 @cindex @file{acconfig.h}
23118 @cindex @file{config.h.top}
23119 @cindex @file{config.h.bot}
23121 In order to produce @file{config.h.in}, @command{autoheader} needs to
23122 build or to find templates for each symbol. Modern releases of Autoconf
23123 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23124 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23125 list of needed templates. @command{autoheader} copied comments and
23126 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23127 the current directory, if present. This file used to be mandatory if
23128 you @code{AC_DEFINE} any additional symbols.
23130 Modern releases of Autoconf also provide @code{AH_TOP} and
23131 @code{AH_BOTTOM} if you need to prepend/append some information to
23132 @file{config.h.in}. Ancient versions of Autoconf had a similar feature:
23133 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23134 @command{autoheader} copies the lines before the line containing
23135 @samp{@@TOP@@} into the top of the file that it generates. Similarly,
23136 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23137 @command{autoheader} copies the lines after that line to the end of the
23138 file it generates. Either or both of those strings may be omitted. An
23139 even older alternate way to produce the same effect in ancient versions
23140 of Autoconf is to create the files @file{@var{file}.top} (typically
23141 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23142 directory. If they exist, @command{autoheader} copies them to the
23143 beginning and end, respectively, of its output.
23145 In former versions of Autoconf, the files used in preparing a software
23146 package for distribution were:
23149 configure.ac --. .------> autoconf* -----> configure
23151 [aclocal.m4] --+ `---.
23153 +--> [autoheader*] -> [config.h.in]
23154 [acconfig.h] ----. |
23161 Using only the @code{AH_} macros, @file{configure.ac} should be
23162 self-contained, and should not depend upon @file{acconfig.h} etc.
23165 @node autoupdate Invocation
23166 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23167 @cindex @command{autoupdate}
23169 The @command{autoupdate} program updates a @file{configure.ac} file that
23170 calls Autoconf macros by their old names to use the current macro names.
23171 In version 2 of Autoconf, most of the macros were renamed to use a more
23172 uniform and descriptive naming scheme. @xref{Macro Names}, for a
23173 description of the new scheme. Although the old names still work
23174 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23175 new names), you can make your @file{configure.ac} files more readable
23176 and make it easier to use the current Autoconf documentation if you
23177 update them to use the new macro names.
23179 @evindex SIMPLE_BACKUP_SUFFIX
23180 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23181 backing up the original version with the suffix @file{~} (or the value
23182 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23183 set). If you give @command{autoupdate} an argument, it reads that file
23184 instead of @file{configure.ac} and writes the updated file to the
23188 @command{autoupdate} accepts the following options:
23193 Print a summary of the command line options and exit.
23197 Print the version number of Autoconf and exit.
23201 Report processing steps.
23205 Don't remove the temporary files.
23209 Force the update even if the file has not changed. Disregard the cache.
23211 @item --include=@var{dir}
23212 @itemx -I @var{dir}
23213 Also look for input files in @var{dir}. Multiple invocations accumulate.
23214 Directories are browsed from last to first.
23216 @item --prepend-include=@var{dir}
23217 @itemx -B @var{dir}
23218 Prepend directory @var{dir} to the search path. This is used to include
23219 the language-specific files before any third-party macros.
23222 @node Obsolete Macros
23223 @section Obsolete Macros
23225 Several macros are obsoleted in Autoconf, for various reasons (typically
23226 they failed to quote properly, couldn't be extended for more recent
23227 issues, etc.). They are still supported, but deprecated: their use
23230 During the jump from Autoconf version 1 to version 2, most of the
23231 macros were renamed to use a more uniform and descriptive naming scheme,
23232 but their signature did not change. @xref{Macro Names}, for a
23233 description of the new naming scheme. Below, if there is just the mapping
23234 from old names to new names for these macros, the reader is invited to
23235 refer to the definition of the new macro for the signature and the
23240 @cvindex _ALL_SOURCE
23241 This macro is a platform-specific subset of
23242 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23247 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23250 @defmac AC_ARG_ARRAY
23251 @acindex{ARG_ARRAY}
23252 Removed because of limited usefulness.
23257 This macro is obsolete; it does nothing.
23260 @defmac AC_C_LONG_DOUBLE
23261 @acindex{C_LONG_DOUBLE}
23262 @cvindex HAVE_LONG_DOUBLE
23263 If the C compiler supports a working @code{long double} type with more
23264 range or precision than the @code{double} type, define
23265 @code{HAVE_LONG_DOUBLE}.
23267 You should use @code{AC_TYPE_LONG_DOUBLE} or
23268 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23271 @defmac AC_CANONICAL_SYSTEM
23272 @acindex{CANONICAL_SYSTEM}
23273 Determine the system type and set output variables to the names of the
23274 canonical system types. @xref{Canonicalizing}, for details about the
23275 variables this macro sets.
23277 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23278 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23279 the needs. Using @code{AC_CANONICAL_TARGET} is enough to run the two
23280 other macros (@pxref{Canonicalizing}).
23283 @defmac AC_CHAR_UNSIGNED
23284 @acindex{CHAR_UNSIGNED}
23285 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23288 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23289 @acindex{CHECK_TYPE}
23290 Autoconf, up to 2.13, used to provide this version of
23291 @code{AC_CHECK_TYPE}, deprecated because of its flaws. First, although
23292 it is a member of the @code{CHECK} clan, it does
23293 more than just checking. Secondly, missing types are defined
23294 using @code{#define}, not @code{typedef}, and this can lead to
23295 problems in the case of pointer types.
23297 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23298 @ref{Generic Types}, for the description of the current macro.
23300 If the type @var{type} is not defined, define it to be the C (or C++)
23301 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23303 This macro is equivalent to:
23306 AC_CHECK_TYPE([@var{type}], [],
23307 [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23308 [Define to '@var{default}'
23309 if <sys/types.h> does not define.])])
23312 In order to keep backward compatibility, the two versions of
23313 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23317 If there are three or four arguments, the modern version is used.
23320 If the second argument appears to be a C or C++ type, then the
23321 obsolete version is used. This happens if the argument is a C or C++
23322 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23323 followed by one of @samp{[(* } and then by a string of zero or more
23324 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23327 If the second argument is spelled with the alphabet of valid C and C++
23328 types, the user is warned and the modern version is used.
23331 Otherwise, the modern version is used.
23335 You are encouraged either to use a valid builtin type, or to use the
23336 equivalent modern code (see above), or better yet, to use
23337 @code{AC_CHECK_TYPES} together with
23340 #ifndef HAVE_LOFF_T
23341 typedef loff_t off_t;
23345 @c end of AC_CHECK_TYPE
23347 @defmac AC_CHECKING (@var{feature-description})
23352 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23356 @xref{AC_MSG_NOTICE}.
23359 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23360 @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23361 @acindex{COMPILE_CHECK}
23362 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23363 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23364 addition that it prints @samp{checking for @var{echo-text}} to the
23365 standard output first, if @var{echo-text} is non-empty. Use
23366 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23367 messages (@pxref{Printing Messages}).
23372 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23375 @defmac AC_CROSS_CHECK
23376 @acindex{CROSS_CHECK}
23377 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23384 Check for the Cygwin environment in which case the shell variable
23385 @code{CYGWIN} is set to @samp{yes}. Don't use this macro, the dignified
23386 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23387 (@pxref{Canonicalizing}). As a matter of fact this macro is defined as:
23390 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23392 *cygwin* ) CYGWIN=yes;;
23397 Beware that the variable @env{CYGWIN} has a special meaning when
23398 running Cygwin, and should not be changed. That's yet another reason
23399 not to use this macro.
23402 @defmac AC_DECL_SYS_SIGLIST
23403 @acindex{DECL_SYS_SIGLIST}
23404 @cvindex SYS_SIGLIST_DECLARED
23408 AC_CHECK_DECLS([sys_siglist], [], [],
23409 [#include <signal.h>
23410 /* NetBSD declares sys_siglist in unistd.h. */
23411 #ifdef HAVE_UNISTD_H
23412 # include <unistd.h>
23418 @xref{AC_CHECK_DECLS}.
23421 @defmac AC_DECL_YYTEXT
23422 @acindex{DECL_YYTEXT}
23423 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23426 @defmac AC_DIAGNOSE (@var{category}, @var{message})
23428 Replaced by @code{m4_warn} (@pxref{m4_warn}).
23431 @defmac AC_DIR_HEADER
23432 @acindex{DIR_HEADER}
23437 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23438 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23439 (@pxref{AC_HEADER_DIRENT}),
23440 but defines a different set of C preprocessor macros to indicate which
23441 header file is found:
23443 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23444 @item Header @tab Old Symbol @tab New Symbol
23445 @item @file{dirent.h} @tab @code{DIRENT} @tab @code{HAVE_DIRENT_H}
23446 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23447 @item @file{sys/dir.h} @tab @code{SYSDIR} @tab @code{HAVE_SYS_DIR_H}
23448 @item @file{ndir.h} @tab @code{NDIR} @tab @code{HAVE_NDIR_H}
23452 @defmac AC_DYNIX_SEQ
23453 @acindex{DYNIX_SEQ}
23454 If on DYNIX/ptx, add @option{-lseq} to output variable
23455 @code{LIBS}. This macro used to be defined as
23458 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23462 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23468 Defined the output variable @code{EXEEXT} based on the output of the
23469 compiler, which is now done automatically. Typically set to empty
23470 string if POSIX and @samp{.exe} if a DOS variant.
23475 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23476 and sets @code{EMXOS2}. Don't use this macro, the dignified means to
23477 check the nature of the host is using @code{AC_CANONICAL_HOST}
23478 (@pxref{Canonicalizing}).
23481 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23482 @ovar{action-if-not-given})
23484 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23485 support providing a help string (@pxref{AC_ARG_ENABLE}).
23490 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23493 @defmac AC_FATAL (@var{message})
23495 Replaced by @code{m4_fatal} (@pxref{m4_fatal}).
23500 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23503 @defmac AC_FIND_XTRA
23504 @acindex{FIND_XTRA}
23505 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23510 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23513 @defmac AC_FUNC_CHECK
23514 @acindex{FUNC_CHECK}
23515 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23518 @anchor{AC_FUNC_SETVBUF_REVERSED}
23519 @defmac AC_FUNC_SETVBUF_REVERSED
23520 @acindex{FUNC_SETVBUF_REVERSED}
23521 @cvindex SETVBUF_REVERSED
23522 @c @fuindex setvbuf
23523 @prindex @code{setvbuf}
23524 Do nothing. Formerly, this macro checked whether @code{setvbuf} takes
23525 the buffering type as its second argument and the buffer pointer as the
23526 third, instead of the other way around, and defined
23527 @code{SETVBUF_REVERSED}. However, the last systems to have the problem
23528 were those based on SVR2, which became obsolete in 1987, and the macro
23529 is no longer needed.
23532 @defmac AC_FUNC_WAIT3
23533 @acindex{FUNC_WAIT3}
23534 @cvindex HAVE_WAIT3
23536 @prindex @code{wait3}
23537 If @code{wait3} is found and fills in the contents of its third argument
23538 (a @samp{struct rusage *}), which HP-UX does not do, define
23541 These days portable programs should use @code{waitpid}, not
23542 @code{wait3}, as @code{wait3} has been removed from POSIX.
23545 @defmac AC_GCC_TRADITIONAL
23546 @acindex{GCC_TRADITIONAL}
23547 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}),
23548 which is itself obsolete.
23551 @defmac AC_GETGROUPS_T
23552 @acindex{GETGROUPS_T}
23553 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23556 @defmac AC_GETLOADAVG
23557 @acindex{GETLOADAVG}
23558 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23561 @defmac AC_GNU_SOURCE
23562 @acindex{GNU_SOURCE}
23563 @cvindex _GNU_SOURCE
23564 This macro is a platform-specific subset of
23565 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23568 @defmac AC_HAVE_FUNCS
23569 @acindex{HAVE_FUNCS}
23570 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23573 @defmac AC_HAVE_HEADERS
23574 @acindex{HAVE_HEADERS}
23575 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23578 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23579 @ovar{action-if-not-found}, @ovar{other-libraries})
23580 @acindex{HAVE_LIBRARY}
23581 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23582 @var{function} argument of @code{main}. In addition, @var{library} can
23583 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}. In
23584 all of those cases, the compiler is passed @option{-lfoo}. However,
23585 @var{library} cannot be a shell variable; it must be a literal name.
23586 @xref{AC_CHECK_LIB}.
23589 @defmac AC_HAVE_POUNDBANG
23590 @acindex{HAVE_POUNDBANG}
23591 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23594 @defmac AC_HEADER_CHECK
23595 @acindex{HEADER_CHECK}
23596 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23599 @defmac AC_HEADER_EGREP
23600 @acindex{HEADER_EGREP}
23601 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23604 @anchor{AC_HEADER_TIME}
23605 @defmac AC_HEADER_TIME
23606 @acindex{HEADER_TIME}
23607 @cvindex TIME_WITH_SYS_TIME
23609 @hdrindex{sys/time.h}
23610 @caindex header_time
23611 This macro used to check whether it was possible to include
23612 @file{time.h} and @file{sys/time.h} in the same source file,
23613 defining @code{TIME_WITH_SYS_TIME} if so.
23615 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23616 although it does still define @code{TIME_WITH_SYS_TIME} for
23617 compatibility's sake. @file{time.h} is universally present, and the
23618 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23622 @defmac AC_HELP_STRING
23623 @acindex{HELP_STRING}
23624 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23627 @defmac AC_INIT (@var{unique-file-in-source-dir})
23629 Formerly @code{AC_INIT} used to have a single argument, and was
23634 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23636 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23641 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23644 @defmac AC_INT_16_BITS
23645 @acindex{INT_16_BITS}
23646 @cvindex INT_16_BITS
23647 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23648 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23651 @defmac AC_IRIX_SUN
23653 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23654 @code{LIBS}. If you were using it to get @code{getmntent}, use
23655 @code{AC_FUNC_GETMNTENT} instead. If you used it for the NIS versions
23656 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23657 getpwnam)}. Up to Autoconf 2.13, it used to be
23660 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23664 now it is defined as
23668 AC_CHECK_LIB([sun], [getpwnam])
23672 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23675 @defmac AC_ISC_POSIX
23676 @acindex{ISC_POSIX}
23678 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23679 necessary for POSIX facilities. Sun dropped support for the obsolete
23680 INTERACTIVE Systems Corporation Unix on 2006-07-23. New programs
23681 need not use this macro. It is implemented as
23682 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23687 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23690 @defmac AC_LANG_CPLUSPLUS
23691 @acindex{LANG_CPLUSPLUS}
23692 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23695 @defmac AC_LANG_FORTRAN77
23696 @acindex{LANG_FORTRAN77}
23697 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23700 @defmac AC_LANG_RESTORE
23701 @acindex{LANG_RESTORE}
23702 Select the @var{language} that is saved on the top of the stack, as set
23703 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23704 @code{AC_LANG(@var{language})}. @xref{Language Choice}, for the
23705 preferred way to change languages.
23708 @defmac AC_LANG_SAVE
23709 @acindex{LANG_SAVE}
23710 Remember the current language (as set by @code{AC_LANG}) on a stack.
23711 The current language does not change. @code{AC_LANG_PUSH} is preferred
23712 (@pxref{AC_LANG_PUSH}).
23715 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23716 @acindex{LINK_FILES}
23717 This is an obsolete version of @code{AC_CONFIG_LINKS}
23718 (@pxref{AC_CONFIG_LINKS}. An updated version of:
23721 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23729 AC_CONFIG_LINKS([host.h:config/$machine.h
23730 object.h:config/$obj_format.h])
23736 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23739 @defmac AC_LONG_64_BITS
23740 @acindex{LONG_64_BITS}
23741 @cvindex LONG_64_BITS
23742 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23743 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23744 (@pxref{AC_CHECK_SIZEOF}).
23747 @defmac AC_LONG_DOUBLE
23748 @acindex{LONG_DOUBLE}
23749 If the C compiler supports a working @code{long double} type with more
23750 range or precision than the @code{double} type, define
23751 @code{HAVE_LONG_DOUBLE}.
23753 You should use @code{AC_TYPE_LONG_DOUBLE} or
23754 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23757 @defmac AC_LONG_FILE_NAMES
23758 @acindex{LONG_FILE_NAMES}
23761 AC_SYS_LONG_FILE_NAMES
23764 @xref{AC_SYS_LONG_FILE_NAMES}.
23767 @defmac AC_MAJOR_HEADER
23768 @acindex{MAJOR_HEADER}
23769 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23772 @defmac AC_MEMORY_H
23774 @cvindex NEED_MEMORY_H
23775 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23776 defined in @file{memory.h}. Today it is equivalent to
23777 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}). Adjust
23778 your code to get the @code{mem} functions from @file{string.h} instead.
23783 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23784 environment and sets @code{MINGW32}. Don't use this macro, the
23785 dignified means to check the nature of the host is using
23786 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23792 @cvindex _POSIX_SOURCE
23793 @cvindex _POSIX_1_SOURCE
23794 This macro is a platform-specific subset of
23795 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23798 @defmac AC_MINUS_C_MINUS_O
23799 @acindex{MINUS_C_MINUS_O}
23800 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23805 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23810 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23816 Defined the output variable @code{OBJEXT} based on the output of the
23817 compiler, after .c files have been excluded. Typically set to @samp{o}
23818 if POSIX, @samp{obj} if a DOS variant.
23819 Now the compiler checking macros handle
23820 this automatically.
23823 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23825 Make M4 print a message to the standard error output warning that
23826 @var{this-macro-name} is obsolete, and giving the file and line number
23827 where it was called. @var{this-macro-name} should be the name of the
23828 macro that is calling @code{AC_OBSOLETE}. If @var{suggestion} is given,
23829 it is printed at the end of the warning message; for example, it can be
23830 a suggestion for what to use instead of @var{this-macro-name}.
23835 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23839 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23840 services to the user (@pxref{AU_DEFUN}).
23845 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23848 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23850 The use of @code{AC_OUTPUT} with arguments is deprecated. This obsoleted
23851 interface is equivalent to:
23855 AC_CONFIG_FILES(@var{file}@dots{})
23856 AC_CONFIG_COMMANDS([default],
23857 @var{extra-cmds}, @var{init-cmds})
23863 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23866 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23867 @acindex{OUTPUT_COMMANDS}
23868 Specify additional shell commands to run at the end of
23869 @file{config.status}, and shell commands to initialize any variables
23870 from @command{configure}. This macro may be called multiple times. It is
23871 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23873 Here is an unrealistic example:
23877 AC_OUTPUT_COMMANDS(
23878 [AS_ECHO(["this is extra $fubar, and so on."])],
23880 AC_OUTPUT_COMMANDS(
23881 [AS_ECHO(["this is another, extra, bit"])],
23882 [AS_ECHO(["init bit"])])
23885 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23886 additional key, an important difference is that
23887 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23888 @code{AC_CONFIG_COMMANDS}. This means that @code{AC_CONFIG_COMMANDS}
23889 can safely be given macro calls as arguments:
23892 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23896 Conversely, where one level of quoting was enough for literal strings
23897 with @code{AC_OUTPUT_COMMANDS}, you need two with
23898 @code{AC_CONFIG_COMMANDS}. The following lines are equivalent:
23902 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23903 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23910 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23915 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23918 @defmac AC_PROG_CC_C89
23919 @acindex{PROG_CC_C89}
23920 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23923 @defmac AC_PROG_CC_C99
23924 @acindex{PROG_CC_C99}
23925 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23928 @defmac AC_PROG_CC_STDC
23929 @acindex{PROG_CC_STDC}
23930 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23933 @anchor{AC_PROG_GCC_TRADITIONAL}
23934 @defmac AC_PROG_GCC_TRADITIONAL
23935 @acindex{PROG_GCC_TRADITIONAL}
23936 Used to put GCC into ``traditional'' (pre-ISO C) compilation mode,
23937 on systems with headers that did not work correctly with a
23938 standard-compliant compiler. GCC has not supported traditional
23939 compilation in many years, and all of the systems that required this are
23940 long obsolete themselves. This macro is now a compatibility synonym for
23941 @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23945 @defmac AC_PROGRAMS_CHECK
23946 @acindex{PROGRAMS_CHECK}
23947 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23950 @defmac AC_PROGRAMS_PATH
23951 @acindex{PROGRAMS_PATH}
23952 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23955 @defmac AC_PROGRAM_CHECK
23956 @acindex{PROGRAM_CHECK}
23957 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23960 @defmac AC_PROGRAM_EGREP
23961 @acindex{PROGRAM_EGREP}
23962 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23965 @defmac AC_PROGRAM_PATH
23966 @acindex{PROGRAM_PATH}
23967 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23970 @defmac AC_REMOTE_TAPE
23971 @acindex{REMOTE_TAPE}
23972 Removed because of limited usefulness.
23975 @defmac AC_RESTARTABLE_SYSCALLS
23976 @acindex{RESTARTABLE_SYSCALLS}
23977 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}. However,
23978 these days portable programs should use @code{sigaction} with
23979 @code{SA_RESTART} if they want restartable system calls. They should
23980 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23981 system call is restartable is a dynamic issue, not a configuration-time
23985 @defmac AC_RETSIGTYPE
23986 @acindex{RETSIGTYPE}
23987 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23993 Removed because of limited usefulness.
23996 @defmac AC_SCO_INTL
23999 Equivalent to the obsolescent macro @code{AC_FUNC_STRFTIME}.
24000 @xref{AC_FUNC_STRFTIME}.
24003 @defmac AC_SETVBUF_REVERSED
24004 @acindex{SETVBUF_REVERSED}
24007 AC_FUNC_SETVBUF_REVERSED
24010 @xref{AC_FUNC_SETVBUF_REVERSED}.
24013 @defmac AC_SET_MAKE
24015 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
24018 @defmac AC_SIZEOF_TYPE
24019 @acindex{SIZEOF_TYPE}
24020 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
24025 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
24028 @defmac AC_STAT_MACROS_BROKEN
24029 @acindex{STAT_MACROS_BROKEN}
24030 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
24033 @defmac AC_STDC_HEADERS
24034 @acindex{STDC_HEADERS}
24035 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
24036 is itself obsolete. Nowadays it is safe to assume the facilities of C89
24042 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
24045 @defmac AC_STRUCT_ST_BLKSIZE
24046 @acindex{STRUCT_ST_BLKSIZE}
24047 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
24048 @cvindex HAVE_ST_BLKSIZE
24049 If @code{struct stat} contains an @code{st_blksize} member, define
24050 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}. The former name,
24051 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
24052 the future. This macro is obsoleted, and should be replaced by
24055 AC_CHECK_MEMBERS([struct stat.st_blksize])
24058 @xref{AC_CHECK_MEMBERS}.
24061 @defmac AC_STRUCT_ST_RDEV
24062 @acindex{STRUCT_ST_RDEV}
24063 @cvindex HAVE_ST_RDEV
24064 @cvindex HAVE_STRUCT_STAT_ST_RDEV
24065 If @code{struct stat} contains an @code{st_rdev} member, define
24066 @code{HAVE_STRUCT_STAT_ST_RDEV}. The former name for this macro,
24067 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24068 in the future. Actually, even the new macro is obsolete and should be
24071 AC_CHECK_MEMBERS([struct stat.st_rdev])
24074 @xref{AC_CHECK_MEMBERS}.
24077 @defmac AC_ST_BLKSIZE
24078 @acindex{ST_BLKSIZE}
24079 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24082 @defmac AC_ST_BLOCKS
24083 @acindex{ST_BLOCKS}
24084 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24089 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24092 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24093 @acindex{SYS_RESTARTABLE_SYSCALLS}
24094 @cvindex HAVE_RESTARTABLE_SYSCALLS
24095 If the system automatically restarts a system call that is interrupted
24096 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}. This macro does
24097 not check whether system calls are restarted in general---it checks whether a
24098 signal handler installed with @code{signal} (but not @code{sigaction})
24099 causes system calls to be restarted. It does not check whether system calls
24100 can be restarted when interrupted by signals that have no handler.
24102 These days portable programs should use @code{sigaction} with
24103 @code{SA_RESTART} if they want restartable system calls. They should
24104 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24105 system call is restartable is a dynamic issue, not a configuration-time
24109 @defmac AC_SYS_SIGLIST_DECLARED
24110 @acindex{SYS_SIGLIST_DECLARED}
24111 This macro was renamed @code{AC_DECL_SYS_SIGLIST}. However, even that
24112 name is obsolete, as the same functionality is now achieved via
24113 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24116 @defmac AC_TEST_CPP
24118 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24119 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24122 @defmac AC_TEST_PROGRAM
24123 @acindex{TEST_PROGRAM}
24124 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24125 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24128 @defmac AC_TIMEZONE
24130 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24133 @defmac AC_TIME_WITH_SYS_TIME
24134 @acindex{TIME_WITH_SYS_TIME}
24135 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24136 itself obsolete; nowadays one need only do
24137 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24140 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24141 @ovar{action-if-true}, @ovar{action-if-false})
24142 @acindex{TRY_COMPILE}
24147 [AC_LANG_PROGRAM([[@var{includes}]],
24148 [[@var{function-body}]])],
24149 [@var{action-if-true}],
24150 [@var{action-if-false}])
24154 @xref{Running the Compiler}.
24156 This macro double quotes both @var{includes} and @var{function-body}.
24158 For C and C++, @var{includes} is any @code{#include} statements needed
24159 by the code in @var{function-body} (@var{includes} is ignored if
24160 the currently selected language is Fortran or Fortran 77). The compiler
24161 and compilation flags are determined by the current language
24162 (@pxref{Language Choice}).
24165 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24171 [AC_LANG_SOURCE([[@var{input}]])],
24172 [@var{action-if-true}],
24173 [@var{action-if-false}])
24177 @xref{Running the Preprocessor}.
24179 This macro double quotes the @var{input}.
24182 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24183 @ovar{action-if-true}, @ovar{action-if-false})
24189 [AC_LANG_PROGRAM([[@var{includes}]],
24190 [[@var{function-body}]])],
24191 [@var{action-if-true}],
24192 [@var{action-if-false}])
24196 @xref{Running the Linker}.
24198 This macro double quotes both @var{includes} and @var{function-body}.
24200 Depending on the current language (@pxref{Language Choice}), create a
24201 test program to see whether a function whose body consists of
24202 @var{function-body} can be compiled and linked. If the file compiles
24203 and links successfully, run shell commands @var{action-if-found},
24204 otherwise run @var{action-if-not-found}.
24206 This macro double quotes both @var{includes} and @var{function-body}.
24208 For C and C++, @var{includes} is any @code{#include} statements needed
24209 by the code in @var{function-body} (@var{includes} is ignored if
24210 the currently selected language is Fortran or Fortran 77). The compiler
24211 and compilation flags are determined by the current language
24212 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24213 @code{LIBS} are used for linking.
24216 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24217 @ovar{action-if-not-found})
24218 @acindex{TRY_LINK_FUNC}
24219 This macro is equivalent to
24221 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24222 [@var{action-if-found}], [@var{action-if-not-found}])
24225 @xref{Running the Linker}.
24228 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24229 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24235 [AC_LANG_SOURCE([[@var{program}]])],
24236 [@var{action-if-true}],
24237 [@var{action-if-false}],
24238 [@var{action-if-cross-compiling}])
24245 @anchor{AC_TYPE_SIGNAL}
24246 @defmac AC_TYPE_SIGNAL
24247 @acindex{TYPE_SIGNAL}
24248 @cvindex RETSIGTYPE
24249 @hdrindex{signal.h}
24250 If @file{signal.h} declares @code{signal} as returning a pointer to a
24251 function returning @code{void}, define @code{RETSIGTYPE} to be
24252 @code{void}; otherwise, define it to be @code{int}. These days, it is
24253 portable to assume C89, and that signal handlers return @code{void},
24254 without needing to use this macro or @code{RETSIGTYPE}.
24259 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24262 @defmac AC_UNISTD_H
24264 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24265 which is one of the tests done as a side effect by
24266 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24267 unnecessary to write explicitly.
24273 Define @code{USG} if the BSD string functions (@code{bcopy},
24274 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24275 in @file{strings.h}. Modern code should assume @file{string.h} exists
24276 and should use the standard C string functions (@code{memmove}, @code{memset},
24277 @code{strchr}, @code{strrchr}, etc) unconditionally.
24279 @file{strings.h} may be the only header that declares @code{strcasecmp},
24280 @code{strncasecmp}, and @code{ffs}. @code{AC_INCLUDES_DEFAULT} checks
24281 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24284 @defmac AC_UTIME_NULL
24285 @acindex{UTIME_NULL}
24286 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24289 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24290 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24291 If the cache file is inconsistent with the current host, target and
24292 build system types, it used to execute @var{cmd} or print a default
24293 error message. This is now handled by default.
24296 @defmac AC_VERBOSE (@var{result-description})
24298 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24303 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24308 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24313 This macro was renamed @code{AC_FUNC_WAIT3}. However, these days
24314 portable programs should use @code{waitpid}, not @code{wait3}, as
24315 @code{wait3} has been removed from POSIX.
24320 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24323 @defmac AC_WARNING (@var{message})
24325 Replaced by @code{m4_warn} (@pxref{m4_warn}).
24328 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24329 @ovar{action-if-not-given})
24331 This is an obsolete version of @code{AC_ARG_WITH} that does not
24332 support providing a help string (@pxref{AC_ARG_WITH}).
24335 @defmac AC_WORDS_BIGENDIAN
24336 @acindex{WORDS_BIGENDIAN}
24337 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24340 @defmac AC_XENIX_DIR
24341 @acindex{XENIX_DIR}
24343 This macro is equivalent to the obsolescent @code{AC_HEADER_DIRENT}
24344 macro, plus it also sets the shell variable @code{XENIX}.
24345 Don't use this macro, the dignified means to check the nature of the
24346 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24349 @defmac AC_YYTEXT_POINTER
24350 @acindex{YYTEXT_POINTER}
24351 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24352 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24356 @section Upgrading From Version 1
24357 @cindex Upgrading autoconf
24358 @cindex Autoconf upgrading
24360 Autoconf version 2 is mostly backward compatible with version 1.
24361 However, it introduces better ways to do some things, and doesn't
24362 support some of the ugly things in version 1. So, depending on how
24363 sophisticated your @file{configure.ac} files are, you might have to do
24364 some manual work in order to upgrade to version 2. This chapter points
24365 out some problems to watch for when upgrading. Also, perhaps your
24366 @command{configure} scripts could benefit from some of the new features in
24367 version 2; the changes are summarized in the file @file{NEWS} in the
24368 Autoconf distribution.
24371 * Changed File Names:: Files you might rename
24372 * Changed Makefiles:: New things to put in @file{Makefile.in}
24373 * Changed Macros:: Macro calls you might replace
24374 * Changed Results:: Changes in how to check test results
24375 * Changed Macro Writing:: Better ways to write your own macros
24378 @node Changed File Names
24379 @subsection Changed File Names
24381 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24382 in a particular package's source directory), you must rename it to
24383 @file{acsite.m4}. @xref{autoconf Invocation}.
24385 If you distribute @file{install.sh} with your package, rename it to
24386 @file{install-sh} so @command{make} builtin rules don't inadvertently
24387 create a file called @file{install} from it. @code{AC_PROG_INSTALL}
24388 looks for the script under both names, but it is best to use the new name.
24390 If you were using @file{config.h.top}, @file{config.h.bot}, or
24391 @file{acconfig.h}, you still can, but you have less clutter if you
24392 use the @code{AH_} macros. @xref{Autoheader Macros}.
24394 @node Changed Makefiles
24395 @subsection Changed Makefiles
24397 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24398 your @file{Makefile.in} files, so they can take advantage of the values
24399 of those variables in the environment when @command{configure} is run.
24400 Doing this isn't necessary, but it's a convenience for users.
24402 Also add @samp{@@configure_input@@} in a comment to each input file for
24403 @code{AC_OUTPUT}, so that the output files contain a comment saying
24404 they were produced by @command{configure}. Automatically selecting the
24405 right comment syntax for all the kinds of files that people call
24406 @code{AC_OUTPUT} on became too much work.
24408 Add @file{config.log} and @file{config.cache} to the list of files you
24409 remove in @code{distclean} targets.
24411 If you have the following in @file{Makefile.in}:
24414 prefix = /usr/local
24415 exec_prefix = $(prefix)
24419 you must change it to:
24422 prefix = @@prefix@@
24423 exec_prefix = @@exec_prefix@@
24427 The old behavior of replacing those variables without @samp{@@}
24428 characters around them has been removed.
24430 @node Changed Macros
24431 @subsection Changed Macros
24433 Many of the macros were renamed in Autoconf version 2. You can still
24434 use the old names, but the new ones are clearer, and it's easier to find
24435 the documentation for them. @xref{Obsolete Macros}, for a table showing the
24436 new names for the old macros. Use the @command{autoupdate} program to
24437 convert your @file{configure.ac} to using the new macro names.
24438 @xref{autoupdate Invocation}.
24440 Some macros have been superseded by similar ones that do the job better,
24441 but are not call-compatible. If you get warnings about calling obsolete
24442 macros while running @command{autoconf}, you may safely ignore them, but
24443 your @command{configure} script generally works better if you follow
24444 the advice that is printed about what to replace the obsolete macros with. In
24445 particular, the mechanism for reporting the results of tests has
24446 changed. If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24447 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24448 looks better if you switch to @code{AC_MSG_CHECKING} and
24449 @code{AC_MSG_RESULT}. @xref{Printing Messages}. Those macros work best
24450 in conjunction with cache variables. @xref{Caching Results}.
24454 @node Changed Results
24455 @subsection Changed Results
24457 If you were checking the results of previous tests by examining the
24458 shell variable @code{DEFS}, you need to switch to checking the values of
24459 the cache variables for those tests. @code{DEFS} no longer exists while
24460 @command{configure} is running; it is only created when generating output
24461 files. This difference from version 1 is because properly quoting the
24462 contents of that variable turned out to be too cumbersome and
24463 inefficient to do every time @code{AC_DEFINE} is called. @xref{Cache
24466 For example, here is a @file{configure.ac} fragment written for Autoconf
24470 AC_HAVE_FUNCS(syslog)
24472 *-DHAVE_SYSLOG*) ;;
24473 *) # syslog is not in the default libraries. See if it's in some other.
24475 for lib in bsd socket inet; do
24476 AC_CHECKING(for syslog in -l$lib)
24477 LIBS="-l$lib $saved_LIBS"
24478 AC_HAVE_FUNCS(syslog)
24480 *-DHAVE_SYSLOG*) break ;;
24488 Here is a way to write it for version 2:
24491 AC_CHECK_FUNCS([syslog])
24492 AS_IF([test "x$ac_cv_func_syslog" = xno],
24493 [# syslog is not in the default libraries. See if it's in some other.
24494 for lib in bsd socket inet; do
24495 AC_CHECK_LIB([$lib], [syslog],
24496 [AC_DEFINE([HAVE_SYSLOG])
24497 LIBS="-l$lib $LIBS"; break])
24501 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24502 backslashes before quotes, you need to remove them. It now works
24503 predictably, and does not treat quotes (except back quotes) specially.
24504 @xref{Setting Output Variables}.
24506 All of the Boolean shell variables set by Autoconf macros now use
24507 @samp{yes} for the true value. Most of them use @samp{no} for false,
24508 though for backward compatibility some use the empty string instead. If
24509 you were relying on a shell variable being set to something like 1 or
24510 @samp{t} for true, you need to change your tests.
24512 @node Changed Macro Writing
24513 @subsection Changed Macro Writing
24515 When defining your own macros, you should now use @code{AC_DEFUN}
24516 instead of @code{define}. @code{AC_DEFUN} automatically calls
24517 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24518 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24519 messages on the screen. There's no actual harm in continuing to use the
24520 older way, but it's less convenient and attractive. @xref{Macro
24523 You probably looked at the macros that came with Autoconf as a guide for
24524 how to do things. It would be a good idea to take a look at the new
24525 versions of them, as the style is somewhat improved and they take
24526 advantage of some new features.
24528 If you were doing tricky things with undocumented Autoconf internals
24529 (macros, variables, diversions), check whether you need to change
24530 anything to account for changes that have been made. Perhaps you can
24531 even use an officially supported technique in version 2 instead of
24532 kludging. Or perhaps not.
24534 To speed up your locally written feature tests, add caching to them.
24535 See whether any of your tests are of general enough usefulness to
24536 encapsulate them into macros that you can share.
24539 @node Autoconf 2.13
24540 @section Upgrading From Version 2.13
24541 @cindex Upgrading autoconf
24542 @cindex Autoconf upgrading
24544 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24545 suits this section@enddots{}
24548 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24549 However, it introduces better ways to do some things, and doesn't
24550 support some of the ugly things in version 2.13. So, depending on how
24551 sophisticated your @file{configure.ac} files are, you might have to do
24552 some manual work in order to upgrade to version 2.50. This chapter
24553 points out some problems to watch for when upgrading. Also, perhaps
24554 your @command{configure} scripts could benefit from some of the new
24555 features in version 2.50; the changes are summarized in the file
24556 @file{NEWS} in the Autoconf distribution.
24560 * Changed Quotation:: Broken code which used to work
24561 * New Macros:: Interaction with foreign macros
24562 * Hosts and Cross-Compilation:: Bugward compatibility kludges
24563 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
24564 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
24567 @node Changed Quotation
24568 @subsection Changed Quotation
24570 The most important changes are invisible to you: the implementation of
24571 most macros have completely changed. This allowed more factorization of
24572 the code, better error messages, a higher uniformity of the user's
24573 interface etc. Unfortunately, as a side effect, some construct which
24574 used to (miraculously) work might break starting with Autoconf 2.50.
24575 The most common culprit is bad quotation.
24577 For instance, in the following example, the message is not properly
24582 AC_CHECK_HEADERS(foo.h, ,
24583 AC_MSG_ERROR(cannot find foo.h, bailing out))
24588 Autoconf 2.13 simply ignores it:
24591 $ @kbd{autoconf-2.13; ./configure --silent}
24592 creating cache ./config.cache
24593 configure: error: cannot find foo.h
24598 while Autoconf 2.50 produces a broken @file{configure}:
24601 $ @kbd{autoconf-2.50; ./configure --silent}
24602 configure: error: cannot find foo.h
24603 ./configure: exit: bad non-numeric arg `bailing'
24604 ./configure: exit: bad non-numeric arg `bailing'
24608 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24612 AC_INIT([Example], [1.0], [bug-example@@example.org])
24613 AC_CHECK_HEADERS([foo.h], [],
24614 [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24618 Many many (and many more) Autoconf macros were lacking proper quotation,
24619 including no less than@dots{} @code{AC_DEFUN} itself!
24622 $ @kbd{cat configure.in}
24623 AC_DEFUN([AC_PROG_INSTALL],
24624 [# My own much better version
24629 $ @kbd{autoconf-2.13}
24630 autoconf: Undefined macros:
24631 ***BUG in Autoconf--please report*** AC_FD_MSG
24632 ***BUG in Autoconf--please report*** AC_EPI
24633 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24634 configure.in:5:AC_PROG_INSTALL
24635 $ @kbd{autoconf-2.50}
24641 @subsection New Macros
24643 @cindex undefined macro
24644 @cindex @code{_m4_divert_diversion}
24646 While Autoconf was relatively dormant in the late 1990s, Automake
24647 provided Autoconf-like macros for a while. Starting with Autoconf 2.50
24648 in 2001, Autoconf provided
24649 versions of these macros, integrated in the @code{AC_} namespace,
24650 instead of @code{AM_}. But in order to ease the upgrading via
24651 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24653 Unfortunately older versions of Automake (e.g., Automake 1.4)
24654 did not quote the names of these macros.
24655 Therefore, when @command{m4} finds something like
24656 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24657 @code{AM_TYPE_PTRDIFF_T} is
24658 expanded, replaced with its Autoconf definition.
24660 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24661 complains, in its own words:
24664 $ @kbd{cat configure.ac}
24665 AC_INIT([Example], [1.0], [bug-example@@example.org])
24667 $ @kbd{aclocal-1.4}
24669 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24670 aclocal.m4:17: the top level
24671 autom4te: m4 failed with exit status: 1
24675 Modern versions of Automake no longer define most of these
24676 macros, and properly quote the names of the remaining macros.
24677 If you must use an old Automake, do not depend upon macros from Automake
24678 as it is simply not its job
24679 to provide macros (but the one it requires itself):
24682 $ @kbd{cat configure.ac}
24683 AC_INIT([Example], [1.0], [bug-example@@example.org])
24685 $ @kbd{rm aclocal.m4}
24687 autoupdate: 'configure.ac' is updated
24688 $ @kbd{cat configure.ac}
24689 AC_INIT([Example], [1.0], [bug-example@@example.org])
24690 AC_CHECK_TYPES([ptrdiff_t])
24691 $ @kbd{aclocal-1.4}
24697 @node Hosts and Cross-Compilation
24698 @subsection Hosts and Cross-Compilation
24699 @cindex Cross compilation
24701 Based on the experience of compiler writers, and after long public
24702 debates, many aspects of the cross-compilation chain have changed:
24706 the relationship between the build, host, and target architecture types,
24709 the command line interface for specifying them to @command{configure},
24712 the variables defined in @command{configure},
24715 the enabling of cross-compilation mode.
24720 The relationship between build, host, and target have been cleaned up:
24721 the chain of default is now simply: target defaults to host, host to
24722 build, and build to the result of @command{config.guess}. Nevertheless,
24723 in order to ease the transition from 2.13 to 2.50, the following
24724 transition scheme is implemented. @emph{Do not rely on it}, as it will
24725 be completely disabled in a couple of releases (we cannot keep it, as it
24726 proves to cause more problems than it cures).
24728 They all default to the result of running @command{config.guess}, unless
24729 you specify either @option{--build} or @option{--host}. In this case,
24730 the default becomes the system type you specified. If you specify both,
24731 and they're different, @command{configure} enters cross compilation
24732 mode, so it doesn't run any tests that require execution.
24734 Hint: if you mean to override the result of @command{config.guess},
24735 prefer @option{--build} over @option{--host}.
24739 For backward compatibility, @command{configure} accepts a system
24740 type as an option by itself. Such an option overrides the
24741 defaults for build, host, and target system types. The following
24742 configure statement configures a cross toolchain that runs on
24743 NetBSD/aarch64 but generates code for GNU Hurd/riscv64,
24744 which is also the build platform.
24747 ./configure --host=aarch64-netbsd riscv64-gnu
24752 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24753 and @code{target} had a different semantics before and after the
24754 invocation of @code{AC_CANONICAL_BUILD} etc. Now, the argument of
24755 @option{--build} is strictly copied into @code{build_alias}, and is left
24756 empty otherwise. After the @code{AC_CANONICAL_BUILD}, @code{build} is
24757 set to the canonicalized build type. To ease the transition, before,
24758 its contents is the same as that of @code{build_alias}. Do @emph{not}
24759 rely on this broken feature.
24761 For consistency with the backward compatibility scheme exposed above,
24762 when @option{--host} is specified but @option{--build} isn't, the build
24763 system is assumed to be the same as @option{--host}, and
24764 @samp{build_alias} is set to that value. Eventually, this
24765 historically incorrect behavior will go away.
24769 The former scheme to enable cross-compilation proved to cause more harm
24770 than good, in particular, it used to be triggered too easily, leaving
24771 regular end users puzzled in front of cryptic error messages.
24772 @command{configure} could even enter cross-compilation mode only
24773 because the compiler was not functional. This is mainly because
24774 @command{configure} used to try to detect cross-compilation, instead of
24775 waiting for an explicit flag from the user.
24777 Now, @command{configure} enters cross-compilation mode if and only if
24778 @option{--host} is passed.
24780 That's the short documentation. To ease the transition between 2.13 and
24781 its successors, a more complicated scheme is implemented. @emph{Do not
24782 rely on the following}, as it will be removed in the near future.
24784 If you specify @option{--host}, but not @option{--build}, when
24785 @command{configure} performs the first compiler test it tries to run
24786 an executable produced by the compiler. If the execution fails, it
24787 enters cross-compilation mode. This is fragile. Moreover, by the time
24788 the compiler test is performed, it may be too late to modify the
24789 build-system type: other tests may have already been performed.
24790 Therefore, whenever you specify @option{--host}, be sure to specify
24791 @option{--build} too.
24794 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
24798 enters cross-compilation mode. The former interface, which
24799 consisted in setting the compiler to a cross-compiler without informing
24800 @command{configure} is obsolete. For instance, @command{configure}
24801 fails if it can't run the code generated by the specified compiler if you
24802 configure as follows:
24805 ./configure CC=x86_64-w64-mingw64-gcc
24809 @node AC_LIBOBJ vs LIBOBJS
24810 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24812 Up to Autoconf 2.13, the replacement of functions was triggered via the
24813 variable @code{LIBOBJS}. Since Autoconf 2.50, the macro
24814 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24815 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24817 This change is mandated by the unification of the GNU Build System
24818 components. In particular, the various fragile techniques used to parse
24819 a @file{configure.ac} are all replaced with the use of traces. As a
24820 consequence, any action must be traceable, which obsoletes critical
24821 variable assignments. Fortunately, @code{LIBOBJS} was the only problem,
24822 and it can even be handled gracefully (read, ``without your having to
24823 change something'').
24825 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24826 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24830 As for function replacement, the fix is immediate: use
24831 @code{AC_LIBOBJ}. For instance:
24834 LIBOBJS="$LIBOBJS fnmatch.o"
24835 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24839 should be replaced with:
24842 AC_LIBOBJ([fnmatch])
24843 AC_LIBOBJ([malloc])
24849 When used with Automake 1.10 or newer, a suitable value for
24850 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24851 can be referenced from any @file{Makefile.am}. Even without Automake,
24852 arranging for @code{LIBOBJDIR} to be set correctly enables
24853 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24854 The @code{LIBOBJDIR} feature is experimental.
24857 @node AC_ACT_IFELSE vs AC_TRY_ACT
24858 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24859 @c the anchor keeps the old node name, to try to avoid breaking links
24860 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24862 @acindex{@var{ACT}_IFELSE}
24863 @acindex{TRY_@var{ACT}}
24864 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24865 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24866 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24867 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24868 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24869 @code{AC_TRY_RUN}. The motivations where:
24872 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24873 quoting their arguments;
24876 the combinatorial explosion is solved by decomposing on the one hand the
24877 generation of sources, and on the other hand executing the program;
24880 this scheme helps supporting more languages than plain C and C++.
24883 In addition to the change of syntax, the philosophy has changed too:
24884 while emphasis was put on speed at the expense of accuracy, today's
24885 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24889 As a perfect example of what is @emph{not} to be done, here is how to
24890 find out whether a header file contains a particular declaration, such
24891 as a typedef, a structure, a structure member, or a function. Use
24892 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24893 header file; on some systems the symbol might be defined in another
24894 header file that the file you are checking includes.
24896 As a (bad) example, here is how you should not check for C preprocessor
24897 symbols, either defined by header files or predefined by the C
24898 preprocessor: using @code{AC_EGREP_CPP}:
24906 ], is_aix=yes, is_aix=no)
24910 The above example, properly written would (i) use
24911 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24915 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24917 error: This isn't AIX!
24926 @c ============================= Generating Test Suites with Autotest
24928 @node Using Autotest
24929 @chapter Generating Test Suites with Autotest
24934 @strong{N.B.: This section describes a feature which is still
24935 stabilizing. Although we believe that Autotest is useful as-is, this
24936 documentation describes an interface which might change in the future:
24937 do not depend upon Autotest without subscribing to the Autoconf mailing
24941 It is paradoxical that portable projects depend on nonportable tools
24942 to run their test suite. Autoconf by itself is the paragon of this
24943 problem: although it aims at perfectly portability, up to 2.13 its
24944 test suite was using DejaGNU, a rich and complex testing
24945 framework, but which is far from being standard on POSIX systems.
24946 Worse yet, it was likely to be missing on the most fragile platforms,
24947 the very platforms that are most likely to torture Autoconf and
24948 exhibit deficiencies.
24950 To circumvent this problem, many package maintainers have developed their
24951 own testing framework, based on simple shell scripts whose sole outputs
24952 are exit status values describing whether the test succeeded. Most of
24953 these tests share common patterns, and this can result in lots of
24954 duplicated code and tedious maintenance.
24956 Following exactly the same reasoning that yielded to the inception of
24957 Autoconf, Autotest provides a test suite generation framework, based on
24958 M4 macros building a portable shell script. The suite itself is
24959 equipped with automatic logging and tracing facilities which greatly
24960 diminish the interaction with bug reporters, and simple timing reports.
24962 Autoconf itself has been using Autotest for years, and we do attest that
24963 it has considerably improved the strength of the test suite and the
24964 quality of bug reports. Other projects are known to use some generation
24965 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
24966 them with different needs, and this usage has validated Autotest as a general
24969 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24970 interactive tool testing, which is probably its main limitation.
24973 * Using an Autotest Test Suite:: Autotest and the user
24974 * Writing Testsuites:: Autotest macros
24975 * testsuite Invocation:: Running @command{testsuite} scripts
24976 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
24979 @node Using an Autotest Test Suite
24980 @section Using an Autotest Test Suite
24983 * testsuite Scripts:: The concepts of Autotest
24984 * Autotest Logs:: Their contents
24987 @node testsuite Scripts
24988 @subsection @command{testsuite} Scripts
24990 @cindex @command{testsuite}
24992 Generating testing or validation suites using Autotest is rather easy.
24993 The whole validation suite is held in a file to be processed through
24994 @command{autom4te}, itself using GNU M4 under the hood, to
24995 produce a stand-alone Bourne shell script which then gets distributed.
24996 Neither @command{autom4te} nor GNU M4 are needed at
24997 the installer's end.
25000 Each test of the validation suite should be part of some test group. A
25001 @dfn{test group} is a sequence of interwoven tests that ought to be
25002 executed together, usually because one test in the group creates data
25003 files that a later test in the same group needs to read. Complex test
25004 groups make later debugging more tedious. It is much better to
25005 keep only a few tests per test group. Ideally there is only one test
25008 For all but the simplest packages, some file such as @file{testsuite.at}
25009 does not fully hold all test sources, as these are often easier to
25010 maintain in separate files. Each of these separate files holds a single
25011 test group, or a sequence of test groups all addressing some common
25012 functionality in the package. In such cases, @file{testsuite.at}
25013 merely initializes the validation suite, and sometimes does elementary
25014 health checking, before listing include statements for all other test
25015 files. The special file @file{package.m4}, containing the
25016 identification of the package, is automatically included if found.
25018 A convenient alternative consists in moving all the global issues
25019 (local Autotest macros, elementary health checking, and @code{AT_INIT}
25020 invocation) into the file @code{local.at}, and making
25021 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
25022 suites. In such case, generating the whole test suite or pieces of it
25023 is only a matter of choosing the @command{autom4te} command line
25026 The validation scripts that Autotest produces are by convention called
25027 @command{testsuite}. When run, @command{testsuite} executes each test
25028 group in turn, producing only one summary line per test to say if that
25029 particular test succeeded or failed. At end of all tests, summarizing
25030 counters get printed. One debugging directory is left for each test
25031 group which failed, if any: such directories are named
25032 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
25033 the test group, and they include:
25036 @item a debugging script named @file{run} which reruns the test in
25037 @dfn{debug mode} (@pxref{testsuite Invocation}). The automatic generation
25038 of debugging scripts has the purpose of easing the chase for bugs.
25040 @item all the files created with @code{AT_DATA}
25042 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25044 @item a log of the run, named @file{testsuite.log}
25047 In the ideal situation, none of the tests fail, and consequently no
25048 debugging directory is left behind for validation.
25050 It often happens in practice that individual tests in the validation
25051 suite need to get information coming out of the configuration process.
25052 Some of this information, common for all validation suites, is provided
25053 through the file @file{atconfig}, automatically created by
25054 @code{AC_CONFIG_TESTDIR}. For configuration information which your
25055 testing environment specifically needs, you might prepare an optional
25056 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25057 The configuration process produces @file{atconfig} and @file{atlocal}
25058 out of these two input files, and these two produced files are
25059 automatically read by the @file{testsuite} script.
25061 Here is a diagram showing the relationship between files.
25064 Files used in preparing a software package for distribution:
25069 subfile-1.at ->. [local.at] ---->+
25071 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25077 Files used in configuring a software package:
25082 [atlocal.in] --> config.status* --<
25088 Files created during test suite execution:
25091 atconfig -->. .--> testsuite.log
25095 [atlocal] ->' `--> [testsuite.dir]
25099 @node Autotest Logs
25100 @subsection Autotest Logs
25102 When run, the test suite creates a log file named after itself, e.g., a
25103 test suite named @command{testsuite} creates @file{testsuite.log}. It
25104 contains a lot of information, usually more than maintainers actually
25105 need, but therefore most of the time it contains all that is needed:
25108 @item command line arguments
25109 A bad but unfortunately widespread habit consists of
25110 setting environment variables before the command, such as in
25111 @samp{CC=my-home-grown-cc ./testsuite}. The test suite does not
25112 know this change, hence (i) it cannot report it to you, and (ii)
25113 it cannot preserve the value of @code{CC} for subsequent runs.
25114 Autoconf faced exactly the same problem, and solved it by asking
25115 users to pass the variable definitions as command line arguments.
25116 Autotest requires this rule, too, but has no means to enforce it; the log
25117 then contains a trace of the variables that were changed by the user.
25119 @item @file{ChangeLog} excerpts
25120 The topmost lines of all the @file{ChangeLog} files found in the source
25121 hierarchy. This is especially useful when bugs are reported against
25122 development versions of the package, since the version string does not
25123 provide sufficient information to know the exact state of the sources
25124 the user compiled. Of course, this relies on the use of a
25127 @item build machine
25128 Running a test suite in a cross-compile environment is not an easy task,
25129 since it would mean having the test suite run on a machine @var{build},
25130 while running programs on a machine @var{host}. It is much simpler to
25131 run both the test suite and the programs on @var{host}, but then, from
25132 the point of view of the test suite, there remains a single environment,
25133 @var{host} = @var{build}. The log contains relevant information on the
25134 state of the @var{build} machine, including some important environment
25136 @c FIXME: How about having an M4sh macro to say "hey, log the value
25137 @c of '@dots{}'"? This would help both Autoconf and Autotest.
25139 @item tested programs
25140 The absolute file name and answers to @option{--version} of the tested
25141 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25143 @item configuration log
25144 The contents of @file{config.log}, as created by @command{configure},
25145 are appended. It contains the configuration flags and a detailed report
25146 on the configuration itself.
25150 @node Writing Testsuites
25151 @section Writing @file{testsuite.at}
25153 The @file{testsuite.at} is a Bourne shell script making use of special
25154 Autotest M4 macros. It often contains a call to @code{AT_INIT} near
25155 its beginning followed by one call to @code{m4_include} per source file
25156 for tests. Each such included file, or the remainder of
25157 @file{testsuite.at} if include files are not used, contain a sequence of
25158 test groups. Each test group begins with a call to @code{AT_SETUP},
25159 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25160 and then completes with a call to @code{AT_CLEANUP}. Multiple test
25161 groups can be categorized by a call to @code{AT_BANNER}.
25163 All of the public Autotest macros have all-uppercase names in the
25164 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25165 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25166 internal macros. All shell variables used in the testsuite for internal
25167 purposes have mostly-lowercase names starting with @samp{at_}. Autotest
25168 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25169 makes use of the file system namespace @samp{^at-}.
25171 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25172 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25173 of those namespaces (@samp{^_?\(m4\|AS\)_}). In general, you
25174 @emph{should not use} the namespace of a package that does not own the
25175 macro or shell code you are writing.
25177 @defmac AT_INIT (@ovar{name})
25179 @c FIXME: Not clear, plus duplication of the information.
25180 Initialize Autotest. Giving a @var{name} to the test suite is
25181 encouraged if your package includes several test suites. Before this
25182 macro is called, @code{AT_PACKAGE_STRING} and
25183 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25184 information about the testsuite to the user. Typically, these macros
25185 are provided by a file @file{package.m4} built by @command{make}
25186 (@pxref{Making testsuite Scripts}), in order to inherit the package
25187 name, version, and bug reporting address from @file{configure.ac}.
25190 @defmac AT_COPYRIGHT (@var{copyright-notice})
25191 @atindex{COPYRIGHT}
25192 @cindex Copyright Notice
25193 State that, in addition to the Free Software Foundation's copyright on
25194 the Autotest macros, parts of your test suite are covered by
25195 @var{copyright-notice}.
25197 The @var{copyright-notice} shows up in both the head of
25198 @command{testsuite} and in @samp{testsuite --version}.
25201 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25202 @ovar{action-if-given}, @ovar{action-if-not-given})
25203 @atindex{ARG_OPTION}
25204 @vrindex at_arg_@var{option}
25205 Accept options from the space-separated list @var{options}, a list that
25206 has leading dashes removed from the options. Long options will be
25207 prefixed with @samp{--}, single-character options with @samp{-}. The
25208 first word in this list is the primary @var{option}, any others are
25209 assumed to be short-hand aliases. The variable associated with it
25210 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25213 If the user passes @option{--@var{option}} to the @command{testsuite},
25214 the variable will be set to @samp{:}. If the user does not pass the
25215 option, or passes @option{--no-@var{option}}, then the variable will be
25216 set to @samp{false}.
25219 @vrindex at_optarg_@var{option}
25220 @var{action-if-given} is run each time the option is encountered; here,
25221 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25222 appropriate. @code{at_optarg} is actually just a copy of
25223 @code{at_arg_@var{option}}.
25225 @var{action-if-not-given} will be run once after option parsing is
25226 complete and if no option from @var{options} was used.
25228 @var{help-text} is added to the end of the list of options shown in
25229 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25231 It is recommended that you use a package-specific prefix to @var{options}
25232 names in order to avoid clashes with future Autotest built-in options.
25235 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25236 @ovar{action-if-given}, @ovar{action-if-not-given})
25237 @atindex{ARG_OPTION_ARG}
25238 @vrindex at_arg_@var{option}
25239 Accept options with arguments from the space-separated list
25240 @var{options}, a list that has leading dashes removed from the options.
25241 Long options will be prefixed with @samp{--}, single-character options
25242 with @samp{-}. The first word in this list is the primary @var{option},
25243 any others are assumed to be short-hand aliases. The variable associated
25244 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25245 replaced with underscores.
25247 If the user passes @option{--@var{option}=@var{arg}} or
25248 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25249 variable will be set to @samp{@var{arg}}.
25252 @var{action-if-given} is run each time the option is encountered; here,
25253 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25254 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25256 @var{action-if-not-given} will be run once after option parsing is
25257 complete and if no option from @var{options} was used.
25259 @var{help-text} is added to the end of the list of options shown in
25260 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25262 It is recommended that you use a package-specific prefix to @var{options}
25263 names in order to avoid clashes with future Autotest built-in options.
25266 @defmac AT_COLOR_TESTS
25267 @atindex{COLOR_TESTS}
25268 Enable colored test results by default when the output is connected to
25272 @defmac AT_TESTED (@var{executables})
25274 Log the file name and answer to @option{--version} of each program in
25275 space-separated list @var{executables}. Several invocations register
25276 new executables, in other words, don't fear registering one program
25279 Autotest test suites rely on @env{PATH} to find the tested program.
25280 This avoids the need to generate absolute names of the various tools, and
25281 makes it possible to test installed programs. Therefore, knowing which
25282 programs are being exercised is crucial to understanding problems in
25283 the test suite itself, or its occasional misuses. It is a good idea to
25284 also subscribe foreign programs you depend upon, to avoid incompatible
25287 @var{executables} is implicitly wrapped in shell double quotes, but it
25288 will still use shell variable expansion (@samp{$}), command substitution
25289 (@samp{`}), and backslash escaping (@samp{\}). In particular, the
25290 @env{EXEEXT} variable is available if it is passed to the testsuite
25291 via @file{atlocal} or @file{atconfig}.
25294 @defmac AT_PREPARE_TESTS (@var{shell-code})
25295 @atindex{PREPARE_TESTS}
25296 Execute @var{shell-code} in the main testsuite process,
25297 after initializing the test suite and processing command-line options,
25298 but before running any tests. If this macro is used several times,
25299 all of the @var{shell-code}s will be executed,
25300 in the order they appeared in @file{testsuite.at}.
25302 One reason to use @code{AT_PREPARE_TESTS} is when the programs under
25303 test are sensitive to environment variables: you can unset all these
25304 variables or reset them to safe values in @var{shell-code}.
25306 @var{shell-code} is only executed if at least one test is going to be
25307 run. In particular, it will not be executed if any of the @option{--help},
25308 @option{--version}, @option{--list}, or @option{--clean} options are
25309 given to @command{testsuite} (@pxref{testsuite Invocation}).
25312 @defmac AT_PREPARE_EACH_TEST (@var{shell-code})
25313 @atindex{AT_PREPARE_EACH_TEST}
25314 Execute @var{shell-code} in each test group's subshell, at the point of
25315 the @code{AT_SETUP} that starts the test group.
25318 @defmac AT_TEST_HELPER_FN (@var{name}, @var{args}, @var{description}, @var{code})
25319 Define a shell function that will be available to the code for each test
25320 group. Its name will be @code{ath_fn_@var{name}}, and its body will be
25321 @var{code}. (The prefix prevents name conflicts with shell functions
25322 defined by M4sh and Autotest.)
25324 @var{args} should describe the function's arguments and @var{description}
25325 what it does; these are used only for documentation comments in the
25326 generated testsuite script.
25331 @defmac AT_BANNER (@var{test-category-name})
25333 This macro identifies the start of a category of related test groups.
25334 When the resulting @file{testsuite} is invoked with more than one test
25335 group to run, its output will include a banner containing
25336 @var{test-category-name} prior to any tests run from that category. The
25337 banner should be no more than about 40 or 50 characters. A blank banner
25338 indicates uncategorized tests; an empty line will be inserted after
25339 tests from an earlier category, effectively ending that category.
25342 @defmac AT_SETUP (@var{test-group-name})
25344 This macro starts a group of related tests, all to be executed in the
25345 same subshell. It accepts a single argument, which holds a few words
25346 (no more than about 30 or 40 characters) quickly describing the purpose
25347 of the test group being started. @var{test-group-name} must not expand
25348 to unbalanced quotes, although quadrigraphs can be used.
25351 @defmac AT_KEYWORDS (@var{keywords})
25353 Associate the space-separated list of @var{keywords} to the enclosing
25354 test group. This makes it possible to run ``slices'' of the test suite.
25355 For instance, if some of your test groups exercise some @samp{foo}
25356 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25357 @samp{./testsuite -k foo} to run exclusively these test groups. The
25358 @var{test-group-name} of the test group is automatically recorded to
25359 @code{AT_KEYWORDS}.
25361 Several invocations within a test group accumulate new keywords. In
25362 other words, don't fear registering the same keyword several times in a
25366 @defmac AT_CAPTURE_FILE (@var{file})
25367 @atindex{CAPTURE_FILE}
25368 If the current test group fails, log the contents of @var{file}.
25369 Several identical calls within one test group have no additional effect.
25372 @defmac AT_FAIL_IF (@var{shell-condition})
25374 Make the test group fail and skip the rest of its execution, if
25375 @var{shell-condition} is true. @var{shell-condition} is a shell expression
25376 such as a @code{test} command. Tests before @command{AT_FAIL_IF}
25377 will be executed and may still cause the test group to be skipped.
25378 You can instantiate this macro many times from within the same test group.
25380 You should use this macro only for very simple failure conditions. If the
25381 @var{shell-condition} could emit any kind of output you should instead
25382 use @command{AT_CHECK} like
25384 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25387 so that such output is properly recorded in the @file{testsuite.log}
25391 @defmac AT_SKIP_IF (@var{shell-condition})
25393 Determine whether the test should be skipped because it requires
25394 features that are unsupported on the machine under test.
25395 @var{shell-condition} is a shell expression such as a @code{test}
25396 command. Tests before @command{AT_SKIP_IF} will be executed
25397 and may still cause the test group to fail. You can instantiate this
25398 macro many times from within the same test group.
25400 You should use this macro only for very simple skip conditions. If the
25401 @var{shell-condition} could emit any kind of output you should instead
25402 use @command{AT_CHECK} like
25404 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25407 so that such output is properly recorded in the @file{testsuite.log}
25411 @defmac AT_XFAIL_IF (@var{shell-condition})
25413 Determine whether the test is expected to fail because it is a known
25414 bug (for unsupported features, you should skip the test).
25415 @var{shell-condition} is a shell expression such as a @code{test}
25416 command; you can instantiate this macro many times from within the
25417 same test group, and one of the conditions is enough to turn
25418 the test into an expected failure.
25423 End the current test group.
25428 @defmac AT_DATA (@var{file}, @var{contents})
25429 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25431 Initialize an input data @var{file} with given @var{contents}. Of
25432 course, the @var{contents} have to be properly quoted between square
25433 brackets to protect against included commas or spurious M4
25434 expansion. @var{contents} must be empty or end with a newline.
25436 be a single shell word that expands into a single file name.
25438 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25439 that only the latter performs shell variable expansion (@samp{$}),
25440 command substitution (@samp{`}), and backslash escaping (@samp{\})
25444 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25445 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25446 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25447 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25449 @atindex{CHECK_UNQUOTED}
25451 Perform a test, by running the shell @var{commands} in a subshell.
25452 @var{commands} is output as-is, so shell expansions are honored.
25453 These commands are expected to have a final exit status of @var{status},
25454 and to produce output as described by @var{stdout} and @var{stderr}
25457 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25459 If @var{commands} exit with unexpected status 77, then the rest of the
25460 test group is skipped. If @var{commands} exit with unexpected status
25461 99, then the test group is immediately failed; this is called a
25462 @emph{hard failure}. Otherwise, the test is considered to have
25463 succeeded if all of the status, stdout, and stderr expectations were
25466 If @var{run-if-fail} is nonempty, it provides extra shell commands to
25467 run when the test fails; if @var{run-if-pass} is nonempty, it provides
25468 extra shell commands to run when the test succeeds. These commands are
25469 @emph{not} run in a subshell, and they are not run when the test group
25470 is skipped (exit code 77) or hard-failed (exit code 99). They may
25471 change whether the test group is considered to have succeeded, by
25472 modifying the shell variable @code{at_failed}; set it to @code{:} to
25473 indicate that the test group has failed, or @code{false} to indicate
25474 that it has succeeded.
25476 The exit status of @var{commands} is available to @var{run-if-fail} and
25477 @var{run-if-pass} commands in the @code{at_status} shell variable. The
25478 output from @var{commands} is also available, in the files named by the
25479 @code{at_stdout} and @code{at_stderr} variables.
25481 If @var{status} is the literal @samp{ignore}, then the exit status of
25482 @var{commands} is not checked, except for the special cases of 77 (skip)
25483 and 99 (hard failure). The existence of hard failures allows one to
25484 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25485 feature has not yet been implemented, but to still distinguish between
25486 gracefully handling the missing feature and dumping core.
25488 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25489 literals in the following table, then the test treats the output
25490 according to the rules of that literal.
25494 The content of the output is ignored, but still captured in the test
25495 group log (if the testsuite is run with the @option{-v} option, the test
25496 group log is displayed as the test is run; if the test group later
25497 fails, the test group log is also copied into the overall testsuite
25498 log). This action is valid for both @var{stdout} and @var{stderr}.
25501 The content of the output is ignored, and nothing is captured in the log
25502 files. If @var{commands} are likely to produce binary output (including
25503 long lines) or large amounts of output, then logging the output can make
25504 it harder to locate details related to subsequent tests within the
25505 group, and could potentially corrupt terminal display of a user running
25506 @command{testsuite -v}. This action is valid for both @var{stdout} and
25510 Only valid as the @var{stdout} parameter. Capture the content of
25511 standard output in both a file named @file{stdout} and the test group log.
25512 Subsequent commands in the test group can then post-process the file.
25513 This action is often used when it is desired to use @command{grep} to
25514 look for a substring in the output, or when the output must be
25515 post-processed to normalize error messages into a common form.
25518 Only valid as the @var{stderr} parameter. Capture the content of
25519 standard error in both a file named @file{stderr} and the test group log.
25522 @itemx stderr-nolog
25523 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25524 not duplicated into the test group log. This action is particularly
25525 useful for an intermediate check that produces large amounts of data,
25526 which will be followed by another check that filters down to the
25527 relevant data, as it makes it easier to locate details in the log.
25530 Only valid as the @var{stdout} parameter. Compare standard output with
25531 the previously created file @file{expout}, and list any differences in
25535 Only valid as the @var{stderr} parameter. Compare standard error with
25536 the previously created file @file{experr}, and list any differences in
25540 Otherwise, the values of the @var{stdout} and @var{stderr} parameters
25541 are treated as text that must exactly match the output given by
25542 @var{commands} on standard output and standard error (including an empty
25543 parameter for no output); any differences are captured in the testsuite
25544 log and the test is failed (unless an unexpected exit status of 77
25545 skipped the test instead).
25547 @code{AT_CHECK_UNQUOTED} performs shell variable expansion (@samp{$}),
25548 command substitution (@samp{`}), and backslash escaping (@samp{\}) on
25549 comparison text given in the @var{stdout} and @var{stderr} parameters;
25550 @code{AT_CHECK} does not. There is no difference in the interpretation
25554 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25555 @ovar{run-if-fail}, @ovar{run-if-pass})
25556 @atindex{CHECK_EUNIT}
25557 Initialize and execute an Erlang module named @var{module} that performs
25558 tests following the @var{test-spec} EUnit test specification.
25559 @var{test-spec} must be a valid EUnit test specification, as defined in
25560 the @uref{https://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25561 Reference Manual}. @var{erlflags} are optional command-line options
25562 passed to the Erlang interpreter to execute the test Erlang module.
25563 Typically, @var{erlflags} defines at least the paths to directories
25564 containing the compiled Erlang modules under test, as @samp{-pa path1
25567 For example, the unit tests associated with Erlang module @samp{testme},
25568 which compiled code is in subdirectory @file{src}, can be performed
25572 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25573 [-pa "$@{abs_top_builddir@}/src"])
25576 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25578 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25579 must be defined as the path of the Erlang interpreter, the path of the
25580 Erlang compiler, and the command-line flags to pass to the compiler,
25581 respectively. Those variables should be configured in
25582 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25583 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25584 variables are automatically defined in the testsuite. If @code{ERL} or
25585 @code{ERLC} is not defined, the test group is skipped.
25587 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25588 be loaded, the test group is skipped. Otherwise, if @var{test-spec} is
25589 an invalid EUnit test specification, the test group fails. Otherwise,
25590 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25591 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25592 executed and the test group fails.
25594 Only the generated test Erlang module is automatically compiled and
25595 executed. If @var{test-spec} involves testing other Erlang modules,
25596 e.g. module @samp{testme} in the example above, those modules must be
25599 If the testsuite is run in verbose mode and with the @option{--verbose} option,
25600 EUnit is also run in verbose mode to output more details about
25601 individual unit tests.
25605 @node testsuite Invocation
25606 @section Running @command{testsuite} Scripts
25607 @cindex @command{testsuite}
25609 Autotest test suites support the following options:
25614 Display the list of options and exit successfully.
25618 Display the version of the test suite and exit successfully.
25620 @item --directory=@var{dir}
25621 @itemx -C @var{dir}
25622 Change the current directory to @var{dir} before creating any files.
25623 Useful for running the testsuite in a subdirectory from a top-level
25626 @item --jobs@r{[}=@var{n}@r{]}
25628 Run @var{n} tests in parallel, if possible. If @var{n} is not given,
25629 run all given tests in parallel. Note that there should be no space
25630 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25631 the separate arguments @option{-j} and @option{@var{number}}, see below.
25633 In parallel mode, the standard input device of the testsuite script is
25634 not available to commands inside a test group. Furthermore, banner
25635 lines are not printed, and the summary line for each test group is
25636 output after the test group completes. Summary lines may appear
25637 unordered. If verbose and trace output are enabled (see below), they
25638 may appear intermixed from concurrently running tests.
25640 Parallel mode requires the @command{mkfifo} command to work, and will be
25641 silently disabled otherwise.
25645 Remove all the files the test suite might have created and exit. Meant
25646 for @code{clean} Make targets.
25650 List all the tests (or only the selection), including their possible
25656 By default all tests are performed (or described with @option{--list})
25657 silently in the default environment, but the environment, set of tests,
25658 and verbosity level can be tuned:
25661 @item @var{variable}=@var{value}
25662 Set the environment @var{variable} to @var{value}. Use this rather
25663 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25664 different environment.
25666 @cindex @code{AUTOTEST_PATH}
25667 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25668 to @env{PATH}. Relative directory names (not starting with
25669 @samp{/}) are considered to be relative to the top level of the
25670 package being built. All directories are made absolute, first
25671 starting from the top level @emph{build} tree, then from the
25672 @emph{source} tree. For instance @samp{./testsuite
25673 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25674 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25675 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25679 @itemx @var{number}-@var{number}
25680 @itemx @var{number}-
25681 @itemx -@var{number}
25682 Add the corresponding test groups, with obvious semantics, to the
25685 @item --keywords=@var{keywords}
25686 @itemx -k @var{keywords}
25687 Add to the selection the test groups with title or keywords (arguments
25688 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25689 of the comma separated list @var{keywords}, case-insensitively. Use
25690 @samp{!} immediately before the keyword to invert the selection for this
25691 keyword. By default, the keywords match whole words; enclose them in
25692 @samp{.*} to also match parts of words.
25694 For example, running
25697 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25701 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25702 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25706 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25710 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25711 containing @samp{FUNC}.
25715 If any test fails, immediately abort testing. This implies
25716 @option{--debug}: post test group clean up, and top-level logging
25717 are inhibited. This option is meant for the full test
25718 suite, it is not really useful for generated debugging scripts.
25719 If the testsuite is run in parallel mode using @option{--jobs},
25720 then concurrently running tests will finish before exiting.
25724 Force more verbosity in the detailed output of what is being done. This
25725 is the default for debugging scripts.
25728 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25729 Enable colored test results. Without an argument, or with @samp{always},
25730 test results will be colored. With @samp{never}, color mode is turned
25731 off. Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25732 the testsuite author, or the argument @samp{auto} is given, then test
25733 results are colored if standard output is connected to a terminal.
25737 Do not remove the files after a test group was performed---but they are
25738 still removed @emph{before}, therefore using this option is sane when
25739 running several test groups. Create debugging scripts. Do not
25740 overwrite the top-level
25741 log (in order to preserve a supposedly existing full log file). This is
25742 the default for debugging scripts, but it can also be useful to debug
25743 the testsuite itself.
25746 Add to the selection all test groups that failed or passed unexpectedly
25747 during the last non-debugging test run.
25751 Trigger shell tracing of the test groups.
25754 Besides these options accepted by every Autotest testsuite, the
25755 testsuite author might have added package-specific options
25756 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25757 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25758 the package documentation for details.
25761 @node Making testsuite Scripts
25762 @section Making @command{testsuite} Scripts
25764 For putting Autotest into movement, you need some configuration and
25765 makefile machinery. We recommend, at least if your package uses deep or
25766 shallow hierarchies, that you use @file{tests/} as the name of the
25767 directory holding all your tests and their makefile. Here is a
25768 check list of things to do, followed by an example, taking into
25769 consideration whether you are also using Automake.
25774 @cindex @file{package.m4}
25775 @atindex{PACKAGE_STRING}
25776 @atindex{PACKAGE_BUGREPORT}
25777 @atindex{PACKAGE_NAME}
25778 @atindex{PACKAGE_TARNAME}
25779 @atindex{PACKAGE_VERSION}
25780 @atindex{PACKAGE_URL}
25781 Make sure to create the file @file{package.m4}, which defines the
25782 identity of the package. It must define @code{AT_PACKAGE_STRING}, the
25783 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25784 address to which bug reports should be sent. For sake of completeness,
25785 we suggest that you also define @code{AT_PACKAGE_NAME},
25786 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25787 @code{AT_PACKAGE_URL}.
25788 @xref{Initializing configure}, for a description of these variables.
25789 Be sure to distribute @file{package.m4} and to put it into the source
25790 hierarchy: the test suite ought to be shipped! See below for an example.
25793 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25795 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25796 @acindex{CONFIG_TESTDIR}
25797 An Autotest test suite is to be configured in @var{directory}. This
25798 macro causes @file{@var{directory}/atconfig} to be created by
25799 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25800 @var{test-path} (@pxref{testsuite Invocation}).
25804 Still within @file{configure.ac}, as appropriate, ensure that some
25805 @code{AC_CONFIG_FILES} command includes substitution for
25806 @file{tests/atlocal}.
25809 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25810 variable to be set.
25813 The appropriate @file{Makefile} should be modified so the validation in
25814 your package is triggered by @samp{make check}.
25817 The following example demonstrates the above checklist, first by
25818 assuming that you are using Automake (see below for tweaks to make to
25819 get the same results without Automake). Begin by adding the following
25820 lines to your @file{configure.ac}:
25823 # Initialize the test suite.
25824 AC_CONFIG_TESTDIR([tests])
25825 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25826 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25829 Next, add the following lines to your @file{tests/Makefile.am}, in order
25830 to link @samp{make check} with a validation suite.
25833 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25834 printf >'$@@' '%s\n' \
25835 '# Signature of the current package.' \
25836 'm4_define([AT_PACKAGE_NAME], [$(PACKAGE_NAME)])' \
25837 'm4_define([AT_PACKAGE_TARNAME], [$(PACKAGE_TARNAME)])' \
25838 'm4_define([AT_PACKAGE_VERSION], [$(PACKAGE_VERSION)])' \
25839 'm4_define([AT_PACKAGE_STRING], [$(PACKAGE_STRING)])' \
25840 'm4_define([AT_PACKAGE_URL], [$(PACKAGE_URL)])' \
25841 'm4_define([AT_PACKAGE_BUGREPORT], [$(PACKAGE_BUGREPORT)])'
25843 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25844 TESTSUITE = $(srcdir)/testsuite
25846 check-local: atconfig atlocal $(TESTSUITE)
25847 $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25849 installcheck-local: atconfig atlocal $(TESTSUITE)
25850 $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25854 test ! -f '$(TESTSUITE)' || \
25855 $(SHELL) '$(TESTSUITE)' --clean
25857 AUTOTEST = $(AUTOM4TE) --language=autotest
25858 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25859 $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25863 Note that the built testsuite is distributed; this is necessary because
25864 users might not have Autoconf installed, and thus would not be able to
25865 rebuild it. Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25866 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25867 provide the user with
25868 a nicer error message if they modify a source file to the testsuite, and
25869 accidentally trigger the rebuild rules.
25871 You might want to list explicitly the dependencies, i.e., the list of
25872 the files @file{testsuite.at} includes.
25874 If you don't use Automake, you should make the following tweaks. In
25875 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25876 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}. You are
25877 welcome to also try using the @command{missing} script from the Automake
25878 project instead of @command{false}, to try to get a nicer error message
25879 when the user modifies prerequisites but did not have Autoconf
25880 installed, but at that point you may be better off using Automake.
25881 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25882 place it in your @file{tests/@/Makefile.in} instead. Add code to your
25883 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25884 distributed, as well as adding the following additional lines to prepare
25885 the set of needed Makefile variables:
25889 PACKAGE_NAME = @@PACKAGE_NAME@@
25890 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25891 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25892 PACKAGE_STRING = @@PACKAGE_STRING@@
25893 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25894 PACKAGE_URL = @@PACKAGE_URL@@
25895 AUTOM4TE = @@AUTOM4TE@@
25897 atconfig: $(top_builddir)/config.status
25898 cd $(top_builddir) && \
25899 $(SHELL) ./config.status $(subdir)/$@@
25901 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25902 cd $(top_builddir) && \
25903 $(SHELL) ./config.status $(subdir)/$@@
25906 Using the above example (with or without Automake), and assuming you
25907 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25908 makefile, you can now fine-tune test suite execution at runtime by
25909 altering this variable, for example:
25912 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25917 @c =============================== Frequent Autoconf Questions, with answers
25920 @chapter Frequent Autoconf Questions, with answers
25922 Several questions about Autoconf come up occasionally. Here some of them
25926 * Distributing:: Distributing @command{configure} scripts
25927 * Why GNU M4:: Why not use the standard M4?
25928 * Bootstrapping:: Autoconf and GNU M4 require each other?
25929 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
25930 * Defining Directories:: Passing @code{datadir} to program
25931 * Autom4te Cache:: What is it? Can I remove it?
25932 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
25933 * Expanded Before Required:: Expanded Before Required
25934 * Debugging:: Debugging @command{configure} scripts
25938 @section Distributing @command{configure} Scripts
25942 What are the restrictions on distributing @command{configure}
25943 scripts that Autoconf generates? How does that affect my
25944 programs that use them?
25947 There are no restrictions on how the configuration scripts that Autoconf
25948 produces may be distributed or used. In Autoconf version 1, they were
25949 covered by the GNU General Public License. We still encourage
25950 software authors to distribute their work under terms like those of the
25951 GPL, but doing so is not required to use Autoconf.
25953 Of the other files that might be used with @command{configure},
25954 @file{config.h.in} is under whatever copyright you use for your
25955 @file{configure.ac}. @file{config.sub} and @file{config.guess} have an
25956 exception to the GPL when they are used with an Autoconf-generated
25957 @command{configure} script, which permits you to distribute them under the
25958 same terms as the rest of your package. @file{install-sh} is from the X
25959 Consortium and is not copyrighted.
25962 @section Why Require GNU M4?
25965 Why does Autoconf require GNU M4?
25968 Many M4 implementations have hard-coded limitations on the size and
25969 number of macros that Autoconf exceeds. They also lack several
25970 builtin macros that it would be difficult to get along without in a
25971 sophisticated application like Autoconf, including:
25981 Autoconf requires version 1.4.8 or later of GNU M4.
25982 It works better with version 1.4.16 or later.
25984 Since only software maintainers need to use Autoconf, and since GNU
25985 M4 is simple to configure and install, it seems reasonable to require
25986 GNU M4 to be installed also. Many maintainers of GNU and
25987 other free software already have most of the GNU utilities
25988 installed, since they prefer them.
25990 @node Bootstrapping
25991 @section How Can I Bootstrap?
25995 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25996 @command{configure} script, how do I bootstrap? It seems like a chicken
26000 This is a misunderstanding. Although GNU M4 does come with a
26001 @command{configure} script produced by Autoconf, Autoconf is not required
26002 in order to run the script and install GNU M4. Autoconf is only
26003 required if you want to change the M4 @command{configure} script, which few
26004 people have to do (mainly its maintainer).
26006 @node Why Not Imake
26007 @section Why Not Imake?
26011 Why not use Imake instead of @command{configure} scripts?
26014 Several people have written addressing this question, so
26015 adaptations of their explanations are included here.
26017 The following answer is based on one written by Richard Pixley:
26020 Autoconf generated scripts frequently work on machines that it has
26021 never been set up to handle before. That is, it does a good job of
26022 inferring a configuration for a new system. Imake cannot do this.
26024 Imake uses a common database of host specific data. For X11, this makes
26025 sense because the distribution is made as a collection of tools, by one
26026 central authority who has control over the database.
26028 GNU tools are not released this way. Each GNU tool has a
26029 maintainer; these maintainers are scattered across the world. Using a
26030 common database would be a maintenance nightmare. Autoconf may appear
26031 to be this kind of database, but in fact it is not. Instead of listing
26032 host dependencies, it lists program requirements.
26034 If you view the GNU suite as a collection of native tools, then the
26035 problems are similar. But the GNU development tools can be
26036 configured as cross tools in almost any host+target permutation. All of
26037 these configurations can be installed concurrently. They can even be
26038 configured to share host independent files across hosts. Imake doesn't
26039 address these issues.
26041 Imake templates are a form of standardization. The GNU coding
26042 standards address the same issues without necessarily imposing the same
26047 Here is some further explanation, written by Per Bothner:
26050 One of the advantages of Imake is that it is easy to generate large
26051 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
26052 However, @code{cpp} is not programmable: it has limited conditional
26053 facilities, and no looping. And @code{cpp} cannot inspect its
26056 All of these problems are solved by using @code{sh} instead of
26057 @code{cpp}. The shell is fully programmable, has macro substitution,
26058 can execute (or source) other shell scripts, and can inspect its
26063 Paul Eggert elaborates more:
26066 With Autoconf, installers need not assume that Imake itself is already
26067 installed and working well. This may not seem like much of an advantage
26068 to people who are accustomed to Imake. But on many hosts Imake is not
26069 installed or the default installation is not working well, and requiring
26070 Imake to install a package hinders the acceptance of that package on
26071 those hosts. For example, the Imake template and configuration files
26072 might not be installed properly on a host, or the Imake build procedure
26073 might wrongly assume that all source files are in one big directory
26074 tree, or the Imake configuration might assume one compiler whereas the
26075 package or the installer needs to use another, or there might be a
26076 version mismatch between the Imake expected by the package and the Imake
26077 supported by the host. These problems are much rarer with Autoconf,
26078 where each package comes with its own independent configuration
26081 Also, Imake often suffers from unexpected interactions between
26082 @command{make} and the installer's C preprocessor. The fundamental problem
26083 here is that the C preprocessor was designed to preprocess C programs,
26084 not makefiles. This is much less of a problem with Autoconf,
26085 which uses the general-purpose preprocessor M4, and where the
26086 package's author (rather than the installer) does the preprocessing in a
26091 Finally, Mark Eichin notes:
26094 Imake isn't all that extensible, either. In order to add new features to
26095 Imake, you need to provide your own project template, and duplicate most
26096 of the features of the existing one. This means that for a sophisticated
26097 project, using the vendor-provided Imake templates fails to provide any
26098 leverage---since they don't cover anything that your own project needs
26099 (unless it is an X11 program).
26101 On the other side, though:
26103 The one advantage that Imake has over @command{configure}:
26104 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26105 than @file{Makefile.in} files. There is a fix to this, however---at least
26106 for the Kerberos V5 tree, we've modified things to call in common
26107 @file{post.in} and @file{pre.in} makefile fragments for the
26108 entire tree. This means that a lot of common things don't have to be
26109 duplicated, even though they normally are in @command{configure} setups.
26113 @node Defining Directories
26114 @section How Do I @code{#define} Installation Directories?
26117 My program needs library files, installed in @code{datadir} and
26121 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26122 [Define to the read-only architecture-independent
26130 #define DATADIR "$@{prefix@}/share"
26134 As already explained, this behavior is on purpose, mandated by the
26135 GNU Coding Standards, see @ref{Installation Directory
26136 Variables}. There are several means to achieve a similar goal:
26140 Do not use @code{AC_DEFINE} but use your makefile to pass the
26141 actual value of @code{datadir} via compilation flags.
26142 @xref{Installation Directory Variables}, for the details.
26145 This solution can be simplified when compiling a program: you may either
26146 extend the @code{CPPFLAGS}:
26149 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26153 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26156 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26160 Alternatively, create a dedicated header file:
26163 DISTCLEANFILES = myprog-paths.h
26164 myprog-paths.h: Makefile
26165 printf '%s\n' '#define DATADIR "$(datadir)"' >$@@
26169 The Gnulib module @samp{configmake} provides such a header with all the
26170 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26174 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26175 value of @code{datadir} and others. Many people have wrapped macros to
26176 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26177 the @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26180 This solution does not conform to the GNU Coding Standards.
26183 Note that all the previous solutions hard wire the absolute name of
26184 these directories in the executables, which is not a good property. You
26185 may try to compute the names relative to @code{prefix}, and try to
26186 find @code{prefix} at runtime, this way your package is relocatable.
26190 @node Autom4te Cache
26191 @section What is @file{autom4te.cache}?
26194 What is this directory @file{autom4te.cache}? Can I safely remove it?
26197 In the GNU Build System, @file{configure.ac} plays a central
26198 role and is read by many tools: @command{autoconf} to create
26199 @file{configure}, @command{autoheader} to create @file{config.h.in},
26200 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26201 check the completeness of @file{configure.ac}, @command{autoreconf} to
26202 check the GNU Build System components that are used. To
26203 ``read @file{configure.ac}'' actually means to compile it with M4,
26204 which can be a long process for complex @file{configure.ac}.
26206 This is why all these tools, instead of running directly M4, invoke
26207 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26208 a specific demand, stores additional information in
26209 @file{autom4te.cache} for future runs. For instance, if you run
26210 @command{autoconf}, behind the scenes, @command{autom4te} also
26211 stores information for the other tools, so that when you invoke
26212 @command{autoheader} or @command{automake} etc., reprocessing
26213 @file{configure.ac} is not needed. The speed up is frequently 30%,
26214 and is increasing with the size of @file{configure.ac}.
26216 But it is and remains being simply a cache: you can safely remove it.
26221 Can I permanently get rid of it?
26224 The creation of this cache can be disabled from
26225 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26226 details. You should be aware that disabling the cache slows down the
26227 Autoconf test suite by 40%. The more GNU Build System
26228 components are used, the more the cache is useful; for instance
26229 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26230 the cache @emph{although @option{--force} implies that the cache is
26231 not fully exploited}, and eight times slower than without
26235 @node Present But Cannot Be Compiled
26236 @section Header Present But Cannot Be Compiled
26238 The most important guideline to bear in mind when checking for
26239 features is to mimic as much as possible the intended use.
26240 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26241 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26242 the preprocessor, instead of the compiler, to check for headers. As a
26243 result, incompatibilities between headers went unnoticed during
26244 configuration, and maintainers finally had to deal with this issue
26247 The transition began with Autoconf 2.56. As of Autoconf 2.64 both
26248 checks are performed, and @command{configure} complains loudly if the
26249 compiler and the preprocessor do not agree. However, only the compiler
26250 result is considered. As of Autoconf 2.70, only the compiler check is
26253 Consider the following example:
26256 $ @kbd{cat number.h}
26257 typedef int number;
26259 const number pi = 3;
26260 $ @kbd{cat configure.ac}
26261 AC_INIT([Example], [1.0], [bug-example@@example.org])
26262 AC_CHECK_HEADERS([pi.h])
26263 $ @kbd{autoconf -Wall}
26264 $ @kbd{./configure CPPFLAGS='-I.'}
26265 checking for gcc... gcc
26266 checking whether the C compiler works... yes
26267 checking for C compiler default output file name... a.out
26268 checking for suffix of executables...
26269 checking whether we are cross compiling... no
26270 checking for suffix of object files... o
26271 checking whether the compiler supports GNU C... yes
26272 checking whether gcc accepts -g... yes
26273 checking for gcc option to enable C23 features... -std=gnu23
26274 checking for sys/types.h... yes
26275 checking for sys/stat.h... yes
26276 checking for strings.h... yes
26277 checking for inttypes.h... yes
26278 checking for stdint.h... yes
26279 checking for unistd.h... yes
26280 checking for pi.h... no
26284 The proper way to handle this case is using the fourth argument
26285 (@pxref{Generic Headers}):
26288 $ @kbd{cat configure.ac}
26289 AC_INIT([Example], [1.0], [bug-example@@example.org])
26290 AC_CHECK_HEADERS([number.h pi.h], [], [],
26291 [[#ifdef HAVE_NUMBER_H
26292 # include <number.h>
26295 $ @kbd{autoconf -Wall}
26296 $ @kbd{./configure CPPFLAGS='-I.'}
26297 checking for gcc... gcc
26298 checking whether the C compiler works... yes
26299 checking for C compiler default output file name... a.out
26300 checking for suffix of executables...
26301 checking whether we are cross compiling... no
26302 checking for suffix of object files... o
26303 checking whether the compiler supports GNU C... yes
26304 checking whether gcc accepts -g... yes
26305 checking for gcc option to enable C23 features... -std=gnu23
26306 checking for number.h... yes
26307 checking for pi.h... yes
26310 See @ref{Particular Headers}, for a list of headers with their
26313 @node Expanded Before Required
26314 @section Expanded Before Required
26316 @cindex expanded before required
26317 Older versions of Autoconf silently built files with incorrect ordering
26318 between dependent macros if an outer macro first expanded, then later
26319 indirectly required, an inner macro. Starting with Autoconf 2.64, this
26320 situation no longer generates out-of-order code, but results in
26321 duplicate output and a syntax warning:
26324 $ @kbd{cat configure.ac}
26325 @result{}AC_DEFUN([TESTA], [[echo in A
26326 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26327 @result{}SEEN_A=:]])
26328 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26329 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26330 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26331 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26338 @result{}configure.ac:11: warning: AC_REQUIRE:
26339 @result{} 'TESTA' was expanded before it was required
26340 @result{}configure.ac:4: TESTB is expanded from...
26341 @result{}configure.ac:6: TESTC is expanded from...
26342 @result{}configure.ac:7: OUTER is expanded from...
26343 @result{}configure.ac:11: the top level
26347 To avoid this warning, decide what purpose the macro in question serves.
26348 If it only needs to be expanded once (for example, if it provides
26349 initialization text used by later macros), then the simplest fix is to
26350 change the macro to be declared with @code{AC_DEFUN_ONCE}
26351 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26352 newer. A more portable fix is to change all
26353 instances of direct calls to instead go through @code{AC_REQUIRE}
26354 (@pxref{Prerequisite Macros}). If, instead, the macro is parameterized
26355 by arguments or by the current definition of other macros in the m4
26356 environment, then the macro should always be directly expanded instead
26359 For another case study, consider this example trimmed down from an
26360 actual package. Originally, the package contained shell code and
26361 multiple macro invocations at the top level of @file{configure.ac}:
26364 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26371 but that was getting complex, so the author wanted to offload some of
26372 the text into a new macro in another file included via
26373 @file{aclocal.m4}. The naïve approach merely wraps the text in a new
26377 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26387 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26388 before the single compiler check, as the author intended. But with
26389 Autoconf 2.64, this issues the ``expanded before it was required''
26390 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26391 check, one before @samp{foobar=}, and one after. To understand why this
26392 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26393 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood. According to
26394 the documented semantics of @code{AC_REQUIRE}, this means that
26395 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26396 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26397 use of @samp{foobar=}. The older versions of Autoconf were broken with
26398 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26399 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26400 autoconf. In other words, the author was unknowingly relying on a bug
26401 exploit to get the desired results, and that exploit broke once the bug
26404 So, what recourse does the author have, to restore their intended
26405 semantics of setting @samp{foobar=} prior to a single compiler check,
26406 regardless of whether Autoconf 2.63 or 2.64 is used? One idea is to
26407 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26408 there is always the possibility of using the lower-level
26412 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26422 This works great if everything is in the same file. However, it does
26423 not help in the case where the author wants to have @command{aclocal}
26424 find the definition of @code{BAR} from its own file, since
26425 @command{aclocal} requires the use of @code{AC_DEFUN}. In this case, a
26426 better fix is to recognize that if @code{BAR} also uses
26427 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26428 to a subsequent require. Then, by creating yet another helper macro,
26429 the author can once again guarantee a single invocation of
26430 @code{AC_PROG_CC}, which will still occur after @code{foobar=}. The
26431 author can also use @code{AC_BEFORE} to make sure no other macro
26432 appearing before @code{BAR} has triggered an unwanted expansion of
26436 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26437 AC_DEFUN([BEFORE_CC], [
26441 AC_BEFORE([$0], [AC_PROG_CC])dnl
26442 AC_REQUIRE([BEFORE_CC])dnl
26443 AC_REQUIRE([AC_PROG_CC])dnl
26451 @section Debugging @command{configure} scripts
26453 While in general, @command{configure} scripts generated by Autoconf
26454 strive to be fairly portable to various systems, compilers, shells, and
26455 other tools, it may still be necessary to debug a failing test, broken
26456 script or makefile, or fix or override an incomplete, faulty, or erroneous
26457 test, especially during macro development. Failures can occur at all levels,
26458 in M4 syntax or semantics, shell script issues, or due to bugs in the
26459 test or the tools invoked by @command{configure}. Together with the
26460 rather arcane error message that @command{m4} and @command{make} may
26461 produce when their input contains syntax errors, this can make debugging
26464 Nevertheless, here is a list of hints and strategies that may help:
26468 When @command{autoconf} fails, common causes for error include:
26472 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26475 @item under- or over-quoted macro arguments (@pxref{Autoconf
26476 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26479 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26483 Typically, it helps to go back to the last working version of the input
26484 and compare the differences for each of these errors. Another
26485 possibility is to sprinkle pairs of @code{m4_traceon} and
26486 @code{m4_traceoff} judiciously in the code, either without a parameter
26487 or listing some macro names and watch @command{m4} expand its input
26488 verbosely (@pxref{Debugging via autom4te}).
26491 Sometimes @command{autoconf} succeeds but the generated
26492 @command{configure} script has invalid shell syntax. You can detect this
26493 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26494 If this command fails, the same tips apply, as if @command{autoconf} had
26498 Debugging @command{configure} script execution may be done by sprinkling
26499 pairs of @code{set -x} and @code{set +x} into the shell script before
26500 and after the region that contains a bug. Running the whole script with
26501 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26502 @var{shell} may work, but produces lots of output. Here, it can help to
26503 search for markers like @samp{checking for} a particular test in the
26507 Alternatively, you might use a shell with debugging capabilities like
26508 @uref{https://bashdb.sourceforge.net/, bashdb}.
26511 When @command{configure} tests produce invalid results for your system,
26512 it may be necessary to override them:
26516 For programs, tools or libraries variables, preprocessor, compiler, or
26517 linker flags, it is often sufficient to override them at @command{make}
26518 run time with some care (@pxref{Macros and Submakes}). Since this
26519 normally won't cause @command{configure} to be run again with these
26520 changed settings, it may fail if the changed variable would have caused
26521 different test results from @command{configure}, so this may work only
26522 for simple differences.
26525 Most tests which produce their result in a substituted variable allow to
26526 override the test by setting the variable on the @command{configure}
26527 command line (@pxref{Compilers and Options}, @pxref{Defining Variables}).
26530 Many tests store their result in a cache variable (@pxref{Caching
26531 Results}). This lets you override them either on the
26532 @command{configure} command line as above, or through a primed cache or
26533 site file (@pxref{Cache Files}, @pxref{Site Defaults}). The name of a
26534 cache variable is documented with a test macro or may be inferred from
26535 @ref{Cache Variable Names}; the precise semantics of undocumented
26536 variables are often internal details, subject to change.
26540 Alternatively, @command{configure} may produce invalid results because
26541 of uncaught programming errors, in your package or in an upstream
26542 library package. For example, when @code{AC_CHECK_LIB} fails to find a
26543 library with a specified function, always check @file{config.log}. This
26544 will reveal the exact error that produced the failing result: the
26545 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26548 Conversely, as macro author, you can make it easier for users of your
26553 by minimizing dependencies between tests and between test results as far
26557 by using @command{make} variables to factorize and allow
26558 override of settings at @command{make} run time,
26561 by honoring the GNU Coding Standards and not overriding flags
26562 reserved for the user except temporarily during @command{configure}
26566 by not requiring users of your macro to use the cache variables.
26567 Instead, expose the result of the test via @var{run-if-true} and
26568 @var{run-if-false} parameters. If the result is not a boolean,
26569 then provide it through documented shell variables.
26573 @c ===================================================== History of Autoconf.
26576 @chapter History of Autoconf
26577 @cindex History of autoconf
26579 @emph{This chapter was written by the original author, David MacKenzie.}
26581 You may be wondering, Why was Autoconf originally written? How did it
26582 get into its present form? (Why does it look like gorilla spit?) If
26583 you're not wondering, then this chapter contains no information useful
26584 to you, and you might as well skip it. If you @emph{are} wondering,
26585 then let there be light@enddots{}
26588 * Genesis:: Prehistory and naming of @command{configure}
26589 * Exodus:: The plagues of M4 and Perl
26590 * Leviticus:: The priestly code of portability arrives
26591 * Numbers:: Growth and contributors
26592 * Deuteronomy:: Approaching the promises of easy configuration
26598 In June 1991 I was maintaining many of the GNU utilities for the
26599 Free Software Foundation. As they were ported to more platforms and
26600 more programs were added, the number of @option{-D} options that users
26601 had to select in the makefile (around 20) became burdensome.
26602 Especially for me---I had to test each new release on a bunch of
26603 different systems. So I wrote a little shell script to guess some of
26604 the correct settings for the fileutils package, and released it as part
26605 of fileutils 2.0. That @command{configure} script worked well enough that
26606 the next month I adapted it (by hand) to create similar @command{configure}
26607 scripts for several other GNU utilities packages. Brian Berliner
26608 also adapted one of my scripts for his CVS revision control system.
26610 Later that summer, I learned that Richard Stallman and Richard Pixley
26611 were developing similar scripts to use in the GNU compiler tools;
26612 so I adapted my @command{configure} scripts to support their evolving
26613 interface: using the file name @file{Makefile.in} as the templates;
26614 adding @samp{+srcdir}, the first option (of many); and creating
26615 @file{config.status} files.
26620 As I got feedback from users, I incorporated many improvements, using
26621 Emacs to search and replace, cut and paste, similar changes in each of
26622 the scripts. As I adapted more GNU utilities packages to use
26623 @command{configure} scripts, updating them all by hand became impractical.
26624 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26625 mail saying that the @command{configure} scripts were great, and asking if
26626 I had a tool for generating them that I could send him. No, I thought,
26627 but I should! So I started to work out how to generate them. And the
26628 journey from the slavery of hand-written @command{configure} scripts to the
26629 abundance and ease of Autoconf began.
26631 Cygnus @command{configure}, which was being developed at around that time,
26632 is table driven; it is meant to deal mainly with a discrete number of
26633 system types with a small number of mainly unguessable features (such as
26634 details of the object file format). The automatic configuration system
26635 that Brian Fox had developed for Bash takes a similar approach. For
26636 general use, it seems to me a hopeless cause to try to maintain an
26637 up-to-date database of which features each variant of each operating
26638 system has. It's easier and more reliable to check for most features on
26639 the fly---especially on hybrid systems that people have hacked on
26640 locally or that have patches from vendors installed.
26642 I considered using an architecture similar to that of Cygnus
26643 @command{configure}, where there is a single @command{configure} script that
26644 reads pieces of @file{configure.in} when run. But I didn't want to have
26645 to distribute all of the feature tests with every package, so I settled
26646 on having a different @command{configure} made from each
26647 @file{configure.in} by a preprocessor. That approach also offered more
26648 control and flexibility.
26650 I looked briefly into using the Metaconfig package, by Larry Wall,
26651 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26652 reasons. The @command{Configure} scripts it produces are interactive,
26653 which I find quite inconvenient; I didn't like the ways it checked for
26654 some features (such as library functions); I didn't know that it was
26655 still being maintained, and the @command{Configure} scripts I had
26656 seen didn't work on many modern systems (such as System V R4 and NeXT);
26657 it wasn't flexible in what it could do in response to a feature's
26658 presence or absence; I found it confusing to learn; and it was too big
26659 and complex for my needs (I didn't realize then how much Autoconf would
26660 eventually have to grow).
26662 I considered using Perl to generate my style of @command{configure}
26663 scripts, but decided that M4 was better suited to the job of simple
26664 textual substitutions: it gets in the way less, because output is
26665 implicit. Plus, everyone already has it. (Initially I didn't rely on
26666 the GNU extensions to M4.) Also, some of my friends at the
26667 University of Maryland had recently been putting M4 front ends on
26668 several programs, including @code{tvtwm}, and I was interested in trying
26669 out a new language.
26674 Since my @command{configure} scripts determine the system's capabilities
26675 automatically, with no interactive user intervention, I decided to call
26676 the program that generates them Autoconfig. But with a version number
26677 tacked on, that name would be too long for old Unix file systems,
26678 so I shortened it to Autoconf.
26680 In the fall of 1991 I called together a group of fellow questers after
26681 the Holy Grail of portability (er, that is, alpha testers) to give me
26682 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26683 and continued to add features and improve the techniques used in the
26684 checks. Prominent among the testers were François Pinard, who came up
26685 with the idea of making an Autoconf shell script to run M4
26686 and check for unresolved macro calls; Richard Pixley, who suggested
26687 running the compiler instead of searching the file system to find
26688 include files and symbols, for more accurate results; Karl Berry, who
26689 got Autoconf to configure @TeX{} and added the macro index to the
26690 documentation; and Ian Lance Taylor, who added support for creating a C
26691 header file as an alternative to putting @option{-D} options in a
26692 makefile, so he could use Autoconf for his UUCP package.
26693 The alpha testers cheerfully adjusted their files again and again as the
26694 names and calling conventions of the Autoconf macros changed from
26695 release to release. They all contributed many specific checks, great
26696 ideas, and bug fixes.
26701 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26702 and converted many GNU packages to use it. I was surprised by how
26703 positive the reaction to it was. More people started using it than I
26704 could keep track of, including people working on software that wasn't
26705 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26706 Autoconf continued to improve rapidly, as many people using the
26707 @command{configure} scripts reported problems they encountered.
26709 Autoconf turned out to be a good torture test for M4 implementations.
26710 Unix M4 started to dump core because of the length of the
26711 macros that Autoconf defined, and several bugs showed up in GNU
26712 M4 as well. Eventually, we realized that we needed to use some
26713 features that only GNU M4 has. 4.3BSD M4, in
26714 particular, has an impoverished set of builtin macros; the System V
26715 version is better, but still doesn't provide everything we need.
26717 More development occurred as people put Autoconf under more stresses
26718 (and to uses I hadn't anticipated). Karl Berry added checks for X11.
26719 david zuhn contributed C++ support. François Pinard made it diagnose
26720 invalid arguments. Jim Blandy bravely coerced it into configuring
26721 GNU Emacs, laying the groundwork for several later improvements.
26722 Roland McGrath got it to configure the GNU C Library, wrote the
26723 @command{autoheader} script to automate the creation of C header file
26724 templates, and added a @option{--verbose} option to @command{configure}.
26725 Noah Friedman added the @option{--autoconf-dir} option and
26726 @code{AC_MACRODIR} environment variable. (He also coined the term
26727 @dfn{autoconfiscate} to mean ``adapt a software package to use
26728 Autoconf''.) Roland and Noah improved the quoting protection in
26729 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26730 dealing with portability problems from February through June, 1993.
26733 @section Deuteronomy
26735 A long wish list for major features had accumulated, and the effect of
26736 several years of patching by various people had left some residual
26737 cruft. In April 1994, while working for Cygnus Support, I began a major
26738 revision of Autoconf. I added most of the features of the Cygnus
26739 @command{configure} that Autoconf had lacked, largely by adapting the
26740 relevant parts of Cygnus @command{configure} with the help of david zuhn
26741 and Ken Raeburn. These features include support for using
26742 @file{config.sub}, @file{config.guess}, @option{--host}, and
26743 @option{--target}; making links to files; and running @command{configure}
26744 scripts in subdirectories. Adding these features enabled Ken to convert
26745 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26748 I added more features in response to other peoples' requests. Many
26749 people had asked for @command{configure} scripts to share the results of
26750 the checks between runs, because (particularly when configuring a large
26751 source tree, like Cygnus does) they were frustratingly slow. Mike
26752 Haertel suggested adding site-specific initialization scripts. People
26753 distributing software that had to unpack on MS-DOS asked for a way to
26754 override the @file{.in} extension on the file names, which produced file
26755 names like @file{config.h.in} containing two dots. Jim Avera did an
26756 extensive examination of the problems with quoting in @code{AC_DEFINE}
26757 and @code{AC_SUBST}; his insights led to significant improvements.
26758 Richard Stallman asked that compiler output be sent to @file{config.log}
26759 instead of @file{/dev/null}, to help people debug the Emacs
26760 @command{configure} script.
26762 I made some other changes because of my dissatisfaction with the quality
26763 of the program. I made the messages showing results of the checks less
26764 ambiguous, always printing a result. I regularized the names of the
26765 macros and cleaned up coding style inconsistencies. I added some
26766 auxiliary utilities that I had developed to help convert source code
26767 packages to use Autoconf. With the help of François Pinard, I made
26768 the macros not interrupt each others' messages. (That feature revealed
26769 some performance bottlenecks in GNU M4, which he hastily
26770 corrected!) I reorganized the documentation around problems people want
26771 to solve. And I began a test suite, because experience had shown that
26772 Autoconf has a pronounced tendency to regress when we change it.
26774 Again, several alpha testers gave invaluable feedback, especially
26775 François Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26778 Finally, version 2.0 was ready. And there was much rejoicing. (And I
26779 have free time again. I think. Yeah, right.)
26782 @c ========================================================== Appendices
26785 @node GNU Free Documentation License
26786 @appendix GNU Free Documentation License
26794 * Environment Variable Index:: Index of environment variables used
26795 * Output Variable Index:: Index of variables set in output files
26796 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
26797 * Cache Variable Index:: Index of documented cache variables
26798 * Autoconf Macro Index:: Index of Autoconf macros
26799 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
26800 * Autotest Macro Index:: Index of Autotest macros
26801 * Program & Function Index:: Index of those with portability problems
26802 * Concept Index:: General index
26805 @node Environment Variable Index
26806 @appendixsec Environment Variable Index
26808 This is an alphabetical list of the environment variables that might
26809 influence Autoconf checks.
26813 @node Output Variable Index
26814 @appendixsec Output Variable Index
26816 This is an alphabetical list of the variables that Autoconf can
26817 substitute into files that it creates, typically one or more
26818 makefiles. @xref{Setting Output Variables}, for more information
26819 on how this is done.
26823 @node Preprocessor Symbol Index
26824 @appendixsec Preprocessor Symbol Index
26826 This is an alphabetical list of the C preprocessor symbols that the
26827 Autoconf macros define. To work with Autoconf, C source code needs to
26828 use these names in @code{#if} or @code{#ifdef} directives.
26832 @node Cache Variable Index
26833 @appendixsec Cache Variable Index
26835 This is an alphabetical list of documented cache variables used
26836 by macros defined in Autoconf. Autoconf macros may use additional cache
26837 variables internally.
26838 @ifset shortindexflag
26839 To make the list easier to use, the variables are listed without their
26840 preceding @samp{ac_cv_}.
26845 @node Autoconf Macro Index
26846 @appendixsec Autoconf Macro Index
26848 This is an alphabetical list of the Autoconf macros.
26849 @ifset shortindexflag
26850 To make the list easier to use, the macros are listed without their
26851 preceding @samp{AC_}.
26856 @node M4 Macro Index
26857 @appendixsec M4 Macro Index
26859 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26860 @ifset shortindexflag
26861 To make the list easier to use, the macros are listed without their
26862 preceding @samp{m4_} or @samp{AS_}. The prefix is @samp{m4_} for
26863 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26869 @node Autotest Macro Index
26870 @appendixsec Autotest Macro Index
26872 This is an alphabetical list of the Autotest macros.
26873 @ifset shortindexflag
26874 To make the list easier to use, the macros are listed without their
26875 preceding @samp{AT_}.
26880 @node Program & Function Index
26881 @appendixsec Program and Function Index
26883 This is an alphabetical list of the programs and functions whose
26884 portability is discussed in this document.
26888 @node Concept Index
26889 @appendixsec Concept Index
26891 This is an alphabetical list of the files, tools, and concepts
26892 introduced in this document.
26898 @c LocalWords: texinfo setfilename autoconf texi settitle setchapternewpage
26899 @c LocalWords: setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26900 @c LocalWords: makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26901 @c LocalWords: shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26902 @c LocalWords: asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26903 @c LocalWords: msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26904 @c LocalWords: direntry autoscan autoreconf autoheader autoupdate config FDs
26905 @c LocalWords: testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26906 @c LocalWords: insertcopying Autoconf's detailmenu Automake Libtool POSIX ois
26907 @c LocalWords: Systemology Checkpointing Changequote INTERCAL changequote dfn
26908 @c LocalWords: Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26909 @c LocalWords: LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26910 @c LocalWords: distclean uninstall noindent versioning Tromey dir vr
26911 @c LocalWords: SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26912 @c LocalWords: evindex automake Gettext autopoint gettext symlink libtoolize
26913 @c LocalWords: defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26914 @c LocalWords: SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26915 @c LocalWords: builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26916 @c LocalWords: CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26917 @c LocalWords: datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26918 @c LocalWords: includedir infodir libexecdir localedir localstatedir mandir
26919 @c LocalWords: oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26920 @c LocalWords: sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26921 @c LocalWords: undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26922 @c LocalWords: PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26923 @c LocalWords: inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26924 @c LocalWords: LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26925 @c LocalWords: inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26926 @c LocalWords: isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26927 @c LocalWords: ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26928 @c LocalWords: snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26929 @c LocalWords: strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26930 @c LocalWords: PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26931 @c LocalWords: closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26932 @c LocalWords: largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26933 @c LocalWords: SETGID getloadavg nlist GETMNTENT irix acxindex autom
26934 @c LocalWords: getmntent UnixWare GETPGRP getpgid getpgrp POSIX's pid LSTAT
26935 @c LocalWords: lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26936 @c LocalWords: localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26937 @c LocalWords: SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26938 @c LocalWords: STRTOD strtod DECL STRFTIME strftime UTIME utime VPRINTF
26939 @c LocalWords: DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26940 @c LocalWords: linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26941 @c LocalWords: NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26942 @c LocalWords: inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26943 @c LocalWords: STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm te
26944 @c LocalWords: ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26945 @c LocalWords: WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26946 @c LocalWords: DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26947 @c LocalWords: passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26948 @c LocalWords: gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26949 @c LocalWords: ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26950 @c LocalWords: varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26951 @c LocalWords: const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26952 @c LocalWords: xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26953 @c LocalWords: ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26954 @c LocalWords: fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26955 @c LocalWords: statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26956 @c LocalWords: GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26957 @c LocalWords: changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26958 @c LocalWords: Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26959 @c LocalWords: bregexp Overquote overquotation meisch maisch meische maische
26960 @c LocalWords: miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26961 @c LocalWords: EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26962 @c LocalWords: pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26963 @c LocalWords: drivespec POSIXy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26964 @c LocalWords: yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26965 @c LocalWords: CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26966 @c LocalWords: MAILPATH scanset arg NetBSD Almquist printf expr cp pR
26967 @c LocalWords: Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM url fc
26968 @c LocalWords: sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc ing FP
26969 @c LocalWords: mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26970 @c LocalWords: fooXXXXXX Unicos utimes hpux hppa unescaped SUBST'ed
26971 @c LocalWords: pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26972 @c LocalWords: cpu wildcards rpcc rdtsc powerpc readline
26973 @c LocalWords: withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26974 @c LocalWords: cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26975 @c LocalWords: lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26976 @c LocalWords: intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26977 @c LocalWords: fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26978 @c LocalWords: ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26979 @c LocalWords: installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26980 @c LocalWords: DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26981 @c LocalWords: Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26982 @c LocalWords: autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26983 @c LocalWords: printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26984 @c LocalWords: VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26985 @c LocalWords: GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26986 @c LocalWords: esyscmd len maketemp pushdef substr syscmd sysval translit txt
26987 @c LocalWords: sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26988 @c LocalWords: Dynix basename aname cname macroexpands xno xcheck iso
26989 @c LocalWords: LIBREADLINE lreadline lncurses libreadline vrindex SYS
26990 @c LocalWords: syncodeindex define'd caindex CAindex MacKenzie DIRS
26991 @c LocalWords: Runtime runtime Submakes submakes MAKEFLAGS whitespace
26992 @c LocalWords: Timestamps Unportability Canonicalizing stdckdint dirN
26993 @c LocalWords: acinclude AMFLAGS LIBS OBJCXXFLAGS GOFLAGS runstatedir
26994 @c LocalWords: metacharacter EXPENSIVEP errno setjmp wctype sys mawk
26995 @c LocalWords: nawk ggrep egrep gegrep fgrep gfgrep LEX lex yytext nm
26996 @c LocalWords: yywrap xflex lexyy YFLAGS yacc divnum libs fuindex ffs
26997 @c LocalWords: environ sigaction extern ftello nonnull STRTOLD LLONG
26998 @c LocalWords: strtold vfprintf ULLONG strcasecmp strncasecmp MSVC th
26999 @c LocalWords: NDEBUG INO libc ISDIR ISREG Tektronix Amdahl ino
27000 @c LocalWords: typedef pxref fileblocks submembers INTMAX intmax UINT
27001 @c LocalWords: INTPTR intptr SSIZE ssize uint UINTPTR uintptr OPENMP
27002 @c LocalWords: openmp OpenMP omp Alignas Alignof Noreturn UTF vals gl
27003 @c LocalWords: offsetof VARARRAYS VLA CCC stdcxx nullptr
27004 @c LocalWords: constexpr decltype unicode fstreams iostreams iomanip
27005 @c LocalWords: stringstreams GXX OBJCPP OBJCXX objcxx GOBJCXX erlc tx
27006 @c LocalWords: OBJCXXCPP FIXEDFORM GFC argc argv shellvar fpp MODEXT
27007 @c LocalWords: freeform fixedform MODINC MODOUT gccgo GOC xmkmf fseek
27008 @c LocalWords: interpval ftell Interix macOS PTHREAD NonStop XOPEN xc
27009 @c LocalWords: IEC ATTRIBS BFP DFP O'Donell Sebor ERTS Erlang's erts
27010 @c LocalWords: erlang Wundef scalable USG NOTMAKE DOUCH
27011 @c LocalWords: IVE changesyntax ifnotinfo oline num cfg debugfile cdr
27012 @c LocalWords: debugmode traceoff traceon patsubst dumpdefs ifelse aa
27013 @c LocalWords: mkstemp undivert lifo errprintn BINSH sanitization bcd
27014 @c LocalWords: cleardivert bmatch bpatsubsts subst cond nblank ifval
27015 @c LocalWords: ifblank ifnblank ifvaln fputc fgetc argn mapall dvarv
27016 @c LocalWords: shiftn abcd elt noquote mkargs joinall SHA prereq dup
27017 @c LocalWords: listc setb seta ARITH HNUM xcurly xoccupied
27018 @c LocalWords: TESTA TESTB TESTC hoc xpg xxyzzyz dtksh nosuch fifos
27019 @c LocalWords: fifo Stardent sig WIF WIFSIGNALED SIGQUIT tty perl ret
27020 @c LocalWords: SIGINT NUL SFN PRN aeiou MSYS SIGTERM xhi arith UWIN
27021 @c LocalWords: CLICOLOR FPATH POSIXLY Shellshock CVE doit ec ci
27022 @c LocalWords: notreached cim nc ACL faccessat Alexandre getline sqrt
27023 @c LocalWords: CONVFMT FS OFMT CDS chgrp futimens utimensat oo esc od
27024 @c LocalWords: ownerships mape readdir mkfifo mknod testsuites XSI rf
27025 @c LocalWords: bcdox hexdump filelist rmdir flushleft busybox nl HAZy
27026 @c LocalWords: ABCDEFGHIJKLMNOPQRSTUVWXYZ Fantazy FAntAZy adc unix xb
27027 @c LocalWords: SUBMAKEFLAGS ehBc ehB hBc hvB dmake hostname nlinit xf
27028 @c LocalWords: DCOMMENT bart pathnames ifhtml randx
27029 @c LocalWords: sumc hic ic fwrapv ftrapv SIGFPE memset fmudflap ctime
27030 @c LocalWords: asctime lvalues lvalue Multithreaded decstation gdb na
27031 @c LocalWords: enableval lesskey FHS superset waitpid libfoo cposix
27032 @c LocalWords: mem RESTARTABLE bzero DejaGNU EUNIT subfile optarg ive
27033 @c LocalWords: nolog expout experr erlflags EUnit testme eunit myprog
27034 @c LocalWords: configmake vx bashdb tvtwm questers UUCP McGrath
27035 @c LocalWords: ispell
27036 @c Local Variables:
27039 @c ispell-local-dictionary: "american"
27040 @c indent-tabs-mode: nil
27041 @c whitespace-check-buffer-indent: nil