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.
5394 If you don't want to maintain a @code{malloc.c} file in your package
5395 manually, you can instead use the Gnulib module @code{malloc-gnu}.
5398 @defmac AC_FUNC_MBRTOWC
5399 @acindex{FUNC_MBRTOWC}
5400 @cvindex HAVE_MBRTOWC
5402 @prindex @code{mbrtowc}
5403 @caindex func_mbrtowc
5404 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5405 type @code{mbstate_t} are properly declared.
5407 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5410 The Gnulib module @code{mbrtowc} not only ensures that the
5411 function is declared, but also works around other portability
5412 problems of this function.
5415 @defmac AC_FUNC_MEMCMP
5416 @acindex{FUNC_MEMCMP}
5419 @prindex @code{memcmp}
5420 @caindex func_memcmp_working
5421 If the @code{memcmp} function is not available or does not work, require an
5422 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5424 The result of this macro is cached in the
5425 @code{ac_cv_func_memcmp_working} variable.
5427 This macro is obsolescent, as current systems have a working
5428 @code{memcmp}. New programs need not use this macro.
5431 @defmac AC_FUNC_MKTIME
5432 @acindex{FUNC_MKTIME}
5435 @prindex @code{mktime}
5436 @caindex func_working_mktime
5437 If the @code{mktime} function is not available, or does not work
5438 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5439 For the purposes of this test, @code{mktime} should conform to the
5440 POSIX standard and should be the inverse of
5443 The result of this macro is cached in the
5444 @code{ac_cv_func_working_mktime} variable.
5446 The @code{AC_FUNC_MKTIME} macro is obsolescent. New programs should
5447 use Gnulib's @code{mktime} module. @xref{Gnulib}.
5450 @anchor{AC_FUNC_MMAP}
5451 @defmac AC_FUNC_MMAP
5455 @prindex @code{mmap}
5456 @caindex func_mmap_fixed_mapped
5457 If the @code{mmap} function exists and works correctly, define
5458 @code{HAVE_MMAP}. This checks only private fixed mapping of already-mapped
5461 The result of this macro is cached in the
5462 @code{ac_cv_func_mmap_fixed_mapped} variable.
5464 Note: This macro asks for more than what an average program needs from
5465 @code{mmap}. In particular, the use of @code{MAP_FIXED} fails on
5466 HP-UX 11, whereas @code{mmap} otherwise works fine on this platform.
5469 @defmac AC_FUNC_OBSTACK
5470 @acindex{FUNC_OBSTACK}
5471 @cvindex HAVE_OBSTACK
5473 @caindex func_obstack
5474 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5475 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5477 The result of this macro is cached in the @code{ac_cv_func_obstack}
5480 The @code{AC_FUNC_OBSTACK} macro is obsolescent. New programs should use
5481 Gnulib's @code{obstack} module. @xref{Gnulib}.
5484 @defmac AC_FUNC_REALLOC
5485 @acindex{FUNC_REALLOC}
5486 @cvindex HAVE_REALLOC
5489 @prindex @code{realloc}
5490 @caindex func_realloc_0_nonnull
5491 If a successful call to @samp{realloc (NULL, 0)} returns a
5492 non-null pointer, define @code{HAVE_REALLOC} to 1. Otherwise define
5493 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5494 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5495 the native @code{realloc} is not used in the main project. See
5496 @code{AC_FUNC_MALLOC} for details.
5498 The result of this macro is cached in the
5499 @code{ac_cv_func_realloc_0_nonnull} variable.
5501 This macro does not check compatibility with glibc @code{realloc (@var{p}, 0)}
5502 when @var{p} is non-null, as glibc 1--2.1 behaves differently from glibc
5503 2.1.1--2.40 (at least), and the C standard says behavior is undefined.
5506 @defmac AC_FUNC_SELECT_ARGTYPES
5507 @acindex{FUNC_SELECT_ARGTYPES}
5508 @cvindex SELECT_TYPE_ARG1
5509 @cvindex SELECT_TYPE_ARG234
5510 @cvindex SELECT_TYPE_ARG5
5512 @prindex @code{select}
5513 @c @caindex func_select_args
5514 Determines the correct type to be passed for each of the
5515 @code{select} function's arguments, and defines those types
5516 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5517 @code{SELECT_TYPE_ARG5} respectively. @code{SELECT_TYPE_ARG1} defaults
5518 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5519 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5521 This macro is obsolescent, as current systems have a @code{select} whose
5522 signature conforms to POSIX. New programs need not use this macro.
5525 @defmac AC_FUNC_SETPGRP
5526 @acindex{FUNC_SETPGRP}
5527 @cvindex SETPGRP_VOID
5529 @prindex @code{setpgrp}
5530 @caindex func_setpgrp_void
5531 If @code{setpgrp} takes no argument (the POSIX version), define
5532 @code{SETPGRP_VOID}. Otherwise, it is the BSD version, which takes
5533 two process IDs as arguments. This macro does not check whether
5534 @code{setpgrp} exists at all; if you need to work in that situation,
5535 first call @code{AC_CHECK_FUNC} for @code{setpgrp}. This macro also
5536 does not check for the Solaris variant of @code{setpgrp}, which returns
5537 a @code{pid_t} instead of an @code{int}; portable code should only use
5538 the return value by comparing it against @code{-1} to check for errors.
5540 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5543 This macro is obsolescent, as all forms of @code{setpgrp} are also
5544 obsolescent. New programs should use the POSIX function @code{setpgid},
5545 which takes two process IDs as arguments (like the BSD @code{setpgrp}).
5548 @defmac AC_FUNC_STAT
5549 @defmacx AC_FUNC_LSTAT
5551 @acindex{FUNC_LSTAT}
5552 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5553 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5555 @prindex @code{stat}
5557 @prindex @code{lstat}
5558 @caindex func_stat_empty_string_bug
5559 @caindex func_lstat_empty_string_bug
5560 Determine whether @code{stat} or @code{lstat} have the bug that it
5561 succeeds when given the zero-length file name as argument.
5563 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5564 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5567 The results of these macros are cached in the
5568 @code{ac_cv_func_stat_empty_string_bug} and the
5569 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5571 These macros are obsolescent, as no current systems have the bug.
5572 New programs need not use these macros.
5575 @anchor{AC_FUNC_STRCOLL}
5576 @defmac AC_FUNC_STRCOLL
5577 @acindex{FUNC_STRCOLL}
5578 @cvindex HAVE_STRCOLL
5580 @prindex @code{strcoll}
5581 @caindex func_strcoll_works
5582 If the @code{strcoll} function exists and works correctly, define
5583 @code{HAVE_STRCOLL}. This does a bit more than
5584 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5585 definitions of @code{strcoll} that should not be used. But it does
5586 not check against a known bug of this function on Solaris 10.
5588 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5592 @defmac AC_FUNC_STRERROR_R
5593 @acindex{FUNC_STRERROR_R}
5594 @cvindex HAVE_STRERROR_R
5595 @cvindex HAVE_DECL_STRERROR_R
5596 @cvindex STRERROR_R_CHAR_P
5597 @c @fuindex strerror_r
5598 @caindex func_strerror_r_char_p
5599 @prindex @code{strerror_r}
5600 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5601 it is declared, define @code{HAVE_DECL_STRERROR_R}. If it returns a
5602 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5603 returns an @code{int} error number. The Thread-Safe Functions option of
5604 POSIX requires @code{strerror_r} to return @code{int}, but
5605 many systems (including, for example, version 2.2.4 of the GNU C
5606 Library) return a @code{char *} value that is not necessarily equal to
5607 the buffer argument.
5609 The result of this macro is cached in the
5610 @code{ac_cv_func_strerror_r_char_p} variable.
5612 The Gnulib module @code{strerror_r} not only ensures that the function
5613 has the return type specified by POSIX, but also works around other
5614 portability problems of this function.
5617 @anchor{AC_FUNC_STRFTIME}
5618 @defmac AC_FUNC_STRFTIME
5619 @acindex{FUNC_STRFTIME}
5620 @cvindex HAVE_STRFTIME
5621 @c @fuindex strftime
5622 @prindex @code{strftime}
5623 Check for @code{strftime} in the @file{intl} library.
5624 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5626 This macro is obsolescent, as no current systems require the @file{intl}
5627 library for @code{strftime}. New programs need not use this macro.
5630 @defmac AC_FUNC_STRTOD
5631 @acindex{FUNC_STRTOD}
5634 @prindex @code{strtod}
5635 @caindex func_strtod
5637 If the @code{strtod} function does not exist or doesn't work correctly,
5638 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}. In this case,
5639 because @file{strtod.c} is likely to need @samp{pow}, set the output
5640 variable @code{POW_LIB} to the extra library needed.
5642 This macro caches its result in the @code{ac_cv_func_strtod} variable
5643 and depends upon the result in the @code{ac_cv_func_pow} variable.
5645 The @code{AC_FUNC_STRTOD} macro is obsolescent. New programs should
5646 use Gnulib's @code{strtod} module. @xref{Gnulib}.
5649 @defmac AC_FUNC_STRTOLD
5650 @acindex{FUNC_STRTOLD}
5651 @cvindex HAVE_STRTOLD
5652 @prindex @code{strtold}
5653 @caindex func_strtold
5654 If the @code{strtold} function exists and conforms to C99 or later, define
5655 @code{HAVE_STRTOLD}.
5657 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5659 The Gnulib module @code{strtold} not only ensures that the
5660 function exists, but also works around other portability
5661 problems of this function.
5664 @defmac AC_FUNC_STRNLEN
5665 @acindex{FUNC_STRNLEN}
5666 @cvindex HAVE_STRNLEN
5668 @prindex @code{strnlen}
5669 @caindex func_strnlen_working
5670 If the @code{strnlen} function is not available, or is buggy (like the one
5671 from Android 5.0 or AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5673 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5676 The @code{AC_FUNC_STRNLEN} macro is obsolescent. New programs should
5677 use Gnulib's @code{strnlen} module. @xref{Gnulib}.
5680 @anchor{AC_FUNC_UTIME_NULL}
5681 @defmac AC_FUNC_UTIME_NULL
5682 @acindex{FUNC_UTIME_NULL}
5683 @cvindex HAVE_UTIME_NULL
5685 @prindex @code{utime}
5686 @caindex func_utime_null
5687 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5688 the present, define @code{HAVE_UTIME_NULL}.
5690 This macro caches its result in the @code{ac_cv_func_utime_null}
5693 This macro is obsolescent, as all current systems have a @code{utime}
5694 that behaves this way. New programs need not use this macro.
5697 @anchor{AC_FUNC_VPRINTF}
5698 @defmac AC_FUNC_VPRINTF
5699 @acindex{FUNC_VPRINTF}
5700 @cvindex HAVE_VPRINTF
5701 @cvindex HAVE_DOPRNT
5703 @prindex @code{vprintf}
5704 @c @fuindex vsprintf
5705 @prindex @code{vsprintf}
5706 If @code{vprintf} is found, define @code{HAVE_VPRINTF}. Otherwise, if
5707 @code{_doprnt} is found, define @code{HAVE_DOPRNT}. (If @code{vprintf}
5708 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5709 are also available.)
5711 This macro is obsolescent, as all current systems have @code{vprintf}.
5712 New programs need not use this macro.
5715 @defmac AC_REPLACE_FNMATCH
5716 @acindex{REPLACE_FNMATCH}
5718 @prindex @code{fnmatch}
5719 @hdrindex{fnmatch.h}
5720 @caindex func_fnmatch_works
5721 If the @code{fnmatch} function does not conform to POSIX (see
5722 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5724 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5725 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5726 copy of the source code of GNU @code{fnmatch}. If necessary,
5727 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5728 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5729 included in place of the system @code{<fnmatch.h>}.
5731 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5734 This macro is obsolescent, as it assumes the use of particular source
5735 files. New programs should use Gnulib's @code{fnmatch-posix} module,
5736 which provides this macro along with the source files. @xref{Gnulib}.
5741 @node Generic Functions
5742 @subsection Generic Function Checks
5744 These macros are used to find functions not covered by the ``particular''
5745 test macros. If the functions might be in libraries other than the
5746 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5747 If you need to check the behavior of a function as well as find out
5748 whether it is present, you have to write your own test for
5749 it (@pxref{Writing Tests}).
5751 @anchor{AC_CHECK_FUNC}
5752 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5753 @ovar{action-if-not-found})
5754 @acindex{CHECK_FUNC}
5755 @caindex func_@var{function}
5756 If C function @var{function} is available, run shell commands
5757 @var{action-if-found}, otherwise @var{action-if-not-found}. If you just
5758 want to define a symbol if the function is available, consider using
5759 @code{AC_CHECK_FUNCS} instead. This macro checks for functions with C
5760 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5761 standardized than C++. (@pxref{Language Choice}, for more information
5762 about selecting the language for checks.)
5764 This macro caches its result in the @code{ac_cv_func_@var{function}}
5768 @anchor{AC_CHECK_FUNCS}
5769 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5770 @ovar{action-if-not-found})
5771 @acindex{CHECK_FUNCS}
5772 @cvindex HAVE_@var{function}
5773 For each @var{function} enumerated in the blank-or-newline-separated argument
5774 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5775 If @var{action-if-found} is given, it is additional shell code to
5776 execute when one of the functions is found. You can give it a value of
5777 @samp{break} to break out of the loop on the first match. If
5778 @var{action-if-not-found} is given, it is executed when one of the
5779 functions is not found.
5781 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5784 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5785 @acindex{CHECK_FUNCS_ONCE}
5786 @cvindex HAVE_@var{function}
5787 For each @var{function} enumerated in the blank-or-newline-separated argument
5788 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5789 This is a once-only variant of @code{AC_CHECK_FUNCS}. It generates the
5790 checking code at most once, so that @command{configure} is smaller and
5791 faster; but the checks cannot be conditionalized and are always done once,
5792 early during the @command{configure} run.
5797 Autoconf follows a philosophy that was formed over the years by those
5798 who have struggled for portability: isolate the portability issues in
5799 specific files, and then program as if you were in a POSIX
5800 environment. Some functions may be missing or unfixable, and your
5801 package must be ready to replace them.
5803 Suitable replacements for many such problem functions are available from
5804 Gnulib (@pxref{Gnulib}).
5806 @defmac AC_LIBOBJ (@var{function})
5809 Specify that @samp{@var{function}.c} must be included in the executables
5810 to replace a missing or broken implementation of @var{function}.
5813 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5814 variable @code{LIBOBJS} if it is not already in, and calls
5815 @code{AC_LIBSOURCE} for @samp{@var{function}.c}. You should not
5816 directly change @code{LIBOBJS}, since this is not traceable.
5819 @defmac AC_LIBSOURCE (@var{file})
5821 Specify that @var{file} might be needed to compile the project. If you
5822 need to know what files might be needed by a @file{configure.ac}, you
5823 should trace @code{AC_LIBSOURCE}. @var{file} must be a literal.
5825 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5826 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}. In
5827 that case, since shell variables cannot be traced statically, you must
5828 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5829 might cause @code{AC_LIBOBJ} to need. For example, if you want to pass
5830 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5831 @code{"foo"} or @code{"bar"}, you should do:
5834 AC_LIBSOURCE([foo.c])
5835 AC_LIBSOURCE([bar.c])
5836 AC_LIBOBJ([$foo_or_bar])
5840 There is usually a way to avoid this, however, and you are encouraged to
5841 simply call @code{AC_LIBOBJ} with literal arguments.
5843 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5844 slightly different semantics: the old macro took the function name,
5845 e.g., @code{foo}, as its argument rather than the file name.
5848 @defmac AC_LIBSOURCES (@var{files})
5849 @acindex{LIBSOURCES}
5850 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5851 comma-separated M4 list. Thus, the above example might be rewritten:
5854 AC_LIBSOURCES([foo.c, bar.c])
5855 AC_LIBOBJ([$foo_or_bar])
5859 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5860 @acindex{CONFIG_LIBOBJ_DIR}
5861 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5862 @var{directory}, a name relative to the top level of the
5863 source tree. The replacement directory defaults to @file{.}, the top
5864 level directory, and the most typical value is @file{lib}, corresponding
5865 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5867 @command{configure} might need to know the replacement directory for the
5868 following reasons: (i) some checks use the replacement files, (ii) some
5869 macros bypass broken system headers by installing links to the
5870 replacement headers (iii) when used in conjunction with Automake,
5871 within each makefile, @var{directory} is used as a relative path
5872 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5873 @code{LTLIBOBJS}, etc.
5878 It is common to merely check for the existence of a function, and ask
5879 for its @code{AC_LIBOBJ} replacement if missing. The following macro is
5880 a convenient shorthand.
5882 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5883 @acindex{REPLACE_FUNCS}
5884 @cvindex HAVE_@var{function}
5886 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5887 @var{action-if-not-found}. You can declare your replacement function by
5888 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}. If the
5889 system has the function, it probably declares it in a header file you
5890 should be including, so you shouldn't redeclare it lest your declaration
5895 @section Header Files
5896 @cindex Header, checking
5898 The following macros check for the presence of certain C header files.
5899 If there is no macro specifically defined to check for a header file you need,
5900 and you don't need to check for any special properties of
5901 it, then you can use one of the general header-file check macros.
5904 * Header Portability:: Collected knowledge on common headers
5905 * Particular Headers:: Special handling to find certain headers
5906 * Generic Headers:: How to find other headers
5909 @node Header Portability
5910 @subsection Portability of Headers
5911 @cindex Portability of headers
5912 @cindex Header portability
5914 This section documents some collected knowledge about common headers,
5915 and the problems they cause. By definition, this list always requires
5916 additions. A much more complete list is maintained by the Gnulib
5917 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5918 POSIX Headers, gnulib, Gnulib} and @ref{Glibc Header File
5919 Substitutes, , Glibc Headers, gnulib, Gnulib}. Please help us keep
5920 the Gnulib list as complete as possible.
5922 When we say that a header ``may require'' some set of other headers, we
5923 mean that it may be necessary for you to manually include those other
5924 headers first, or the contents of the header under test will fail to
5925 compile. When checking for these headers, you must provide the
5926 potentially-required headers in the @var{includes} argument to
5927 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5928 fail spuriously. @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5929 arranges to include a number of common requirements and should normally
5930 come first in your @var{includes}. For example, @file{net/if.h} may
5931 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5932 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5933 @file{sys/socket.h}, so you should check for it like this:
5936 AC_CHECK_HEADERS([sys/socket.h])
5937 AC_CHECK_HEADERS([net/if.h], [], [],
5938 [AC_INCLUDES_DEFAULT[
5939 #ifdef HAVE_SYS_SOCKET_H
5940 # include <sys/socket.h>
5945 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5946 so that it gets expanded) and double quoting (to ensure that each
5947 preprocessor @code{#} gets treated as a literal string rather than a
5952 @item @file{limits.h}
5953 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5954 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5955 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5958 @item @file{memory.h}
5960 This header file is obsolete; use @file{string.h} instead.
5962 @item @file{strings.h}
5963 @hdrindex{strings.h}
5964 On some systems, this is the only header that declares
5965 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5967 This header may or may not include @file{string.h} for you. However, on
5968 all recent systems it is safe to include both @file{string.h} and
5969 @file{strings.h}, in either order, in the same source file.
5971 @item @file{inttypes.h} vs.@: @file{stdint.h}
5972 @hdrindex{inttypes.h}
5974 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5975 no need to include @file{stdint.h} separately in a standard environment.
5976 However, some implementations have @file{stdint.h} but not @file{inttypes.h}
5977 (e.g. MSVC 2012). Therefore, it is necessary to check for each and include
5978 each only if available.
5980 @item @file{linux/irda.h}
5981 @hdrindex{linux/irda.h}
5982 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5984 @item @file{linux/random.h}
5985 @hdrindex{linux/random.h}
5986 This header may require @file{linux/types.h}.
5988 @item @file{net/if.h}
5990 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5992 @item @file{netinet/if_ether.h}
5993 @hdrindex{netinet/if_ether.h}
5994 This header may require some combination of @file{sys/types.h},
5995 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5997 @item @file{sys/mount.h}
5998 @hdrindex{sys/mount.h}
5999 This header may require @file{sys/params.h}.
6001 @item @file{sys/ptem.h}
6002 @hdrindex{sys/ptem.h}
6003 This header may require @file{sys/stream.h}.
6005 @item @file{sys/socket.h}
6006 @hdrindex{sys/socket.h}
6007 This header may require @file{sys/types.h}.
6009 @item @file{sys/ucred.h}
6010 @hdrindex{sys/ucred.h}
6011 This header may require @file{sys/types.h}.
6013 @item @file{X11/extensions/scrnsaver.h}
6014 @hdrindex{X11/extensions/scrnsaver.h}
6015 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
6016 so required that you might not even consider looking for it.
6021 @node Particular Headers
6022 @subsection Particular Header Checks
6024 These macros check for particular system header files---whether they
6025 exist, and in some cases whether they declare certain symbols.
6027 @defmac AC_CHECK_HEADER_STDBOOL
6028 @acindex{CHECK_HEADER_STDBOOL}
6030 @hdrindex{stdbool.h}
6031 @caindex header_stdbool_h
6032 Check whether @file{stdbool.h} exists and conforms to C99 or later,
6033 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
6034 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
6036 This macro is obsolescent, as all current C compilers have @file{stdbool.h},
6037 a header that is itself obsolescent as of C23.
6039 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
6040 packages that supply a substitute @file{stdbool.h} on platforms lacking
6041 a conforming one. The @code{AC_HEADER_STDBOOL} macro is better for code
6042 that explicitly checks for @file{stdbool.h}.
6045 @defmac AC_HEADER_ASSERT
6046 @acindex{HEADER_ASSERT}
6049 Check whether to enable assertions in the style of @file{assert.h}.
6050 Assertions are enabled by default, but the user can override this by
6051 invoking @command{configure} with the @option{--disable-assert} option.
6054 @anchor{AC_HEADER_DIRENT}
6055 @defmac AC_HEADER_DIRENT
6056 @acindex{HEADER_DIRENT}
6057 @cvindex HAVE_DIRENT_H
6058 @cvindex HAVE_NDIR_H
6059 @cvindex HAVE_SYS_DIR_H
6060 @cvindex HAVE_SYS_NDIR_H
6062 @hdrindex{sys/ndir.h}
6063 @hdrindex{sys/dir.h}
6065 Check for the following header files. For the first one that is
6066 found and defines @samp{DIR}, define the listed C preprocessor macro:
6068 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
6069 @item @file{dirent.h} @tab @code{HAVE_DIRENT_H}
6070 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
6071 @item @file{sys/dir.h} @tab @code{HAVE_SYS_DIR_H}
6072 @item @file{ndir.h} @tab @code{HAVE_NDIR_H}
6075 The directory-library declarations in your source code should look
6076 something like the following:
6080 #include <sys/types.h>
6081 #ifdef HAVE_DIRENT_H
6082 # include <dirent.h>
6083 # define NAMLEN(dirent) strlen ((dirent)->d_name)
6085 # define dirent direct
6086 # define NAMLEN(dirent) ((dirent)->d_namlen)
6087 # ifdef HAVE_SYS_NDIR_H
6088 # include <sys/ndir.h>
6090 # ifdef HAVE_SYS_DIR_H
6091 # include <sys/dir.h>
6100 Using the above declarations, the program would declare variables to be
6101 of type @code{struct dirent}, not @code{struct direct}, and would access
6102 the length of a directory entry name by passing a pointer to a
6103 @code{struct dirent} to the @code{NAMLEN} macro.
6105 This macro also checks for the obsolete @file{dir} and @file{x} libraries.
6107 This macro is obsolescent, as all current systems with directory
6108 libraries have @code{<dirent.h>}. New programs need not use this macro.
6110 Also see @code{AC_STRUCT_DIRENT_D_INO} and
6111 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
6114 @anchor{AC_HEADER_MAJOR}
6115 @defmac AC_HEADER_MAJOR
6116 @acindex{HEADER_MAJOR}
6117 @cvindex MAJOR_IN_MKDEV
6118 @cvindex MAJOR_IN_SYSMACROS
6119 @hdrindex{sys/mkdev.h}
6120 @hdrindex{sys/sysmacros.h}
6121 Detect the headers required to use @code{makedev}, @code{major}, and
6122 @code{minor}. These functions may be defined by @file{sys/mkdev.h},
6123 @code{sys/sysmacros.h}, or @file{sys/types.h}.
6125 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
6126 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6127 @file{sys/sysmacros.h}. If neither macro is defined, they are either in
6128 @file{sys/types.h} or unavailable.
6130 To properly use these functions, your code should contain something
6134 #include <sys/types.h>
6135 #ifdef MAJOR_IN_MKDEV
6136 # include <sys/mkdev.h>
6137 #elif defined MAJOR_IN_SYSMACROS
6138 # include <sys/sysmacros.h>
6142 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6143 detect a problem if @file{sys/types.h} contains definitions of
6144 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6145 warnings upon use. This is known to occur with GNU libc 2.25, where
6146 those definitions are being deprecated to reduce namespace pollution.
6147 If it is not practical to use Autoconf 2.70 to regenerate the configure
6148 script of affected software, you can work around the problem by setting
6149 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6150 @command{configure} or as part of a @file{config.site} site default file
6151 (@pxref{Site Defaults}).
6154 @defmac AC_HEADER_RESOLV
6155 @acindex{HEADER_RESOLV}
6156 @cvindex HAVE_RESOLV_H
6158 Checks for header @file{resolv.h}, checking for prerequisites first.
6159 To properly use @file{resolv.h}, your code should contain something like
6163 #ifdef HAVE_SYS_TYPES_H
6164 # include <sys/types.h>
6166 #ifdef HAVE_NETINET_IN_H
6167 # include <netinet/in.h> /* inet_ functions / structs */
6169 #ifdef HAVE_ARPA_NAMESER_H
6170 # include <arpa/nameser.h> /* DNS HEADER struct */
6179 @anchor{AC_HEADER_STAT}
6180 @defmac AC_HEADER_STAT
6181 @acindex{HEADER_STAT}
6182 @cvindex STAT_MACROS_BROKEN
6183 @hdrindex{sys/stat.h}
6184 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6185 @file{sys/stat.h} do not work properly (returning false positives),
6186 define @code{STAT_MACROS_BROKEN}. This is the case on Tektronix UTekV,
6187 Amdahl UTS and Motorola System V/88.
6189 This macro is obsolescent, as no current systems have the bug.
6190 New programs need not use this macro.
6193 @defmac AC_HEADER_STDBOOL
6194 @acindex{HEADER_STDBOOL}
6195 @cvindex HAVE_STDBOOL_H
6197 @hdrindex{stdbool.h}
6198 @caindex header_stdbool_h
6199 If @file{stdbool.h} exists and conforms to C99 or later, define
6200 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6201 @code{HAVE__BOOL} to 1.
6203 This macro is obsolescent, as all current C compilers have
6204 @file{stdbool.h}, a header that is itself obsolescent as of C23.
6205 Nowadays programs that need @code{bool}, @code{true} and @code{false}
6206 can include @file{stdbool.h} unconditionally, without using
6207 @code{AC_HEADER_STDBOOL}, and if such a program needs to be portable
6208 only to C23 or later it need not even include @file{stdbool.h}.
6210 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6213 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6214 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6218 @anchor{AC_HEADER_STDC}
6219 @defmac AC_HEADER_STDC
6220 @acindex{HEADER_STDC}
6221 @cvindex STDC_HEADERS
6222 @caindex header_stdc
6224 This macro is obsolescent. Its sole effect is to make sure that all the
6225 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6226 Includes}), but not part of C89, have been checked for.
6228 All hosted environments that are still of interest for portable code
6229 provide all of the headers specified in C89 (as amended in 1995).
6232 @defmac AC_HEADER_SYS_WAIT
6233 @acindex{HEADER_SYS_WAIT}
6234 @cvindex HAVE_SYS_WAIT_H
6235 @hdrindex{sys/wait.h}
6236 @caindex header_sys_wait_h
6237 If @file{sys/wait.h} exists and is compatible with POSIX, define
6238 @code{HAVE_SYS_WAIT_H}. Incompatibility can occur if @file{sys/wait.h}
6239 does not exist, or if it uses the old BSD @code{union wait} instead
6240 of @code{int} to store a status value. If @file{sys/wait.h} is not
6241 POSIX compatible, then instead of including it, define the
6242 POSIX macros with their usual interpretations. Here is an
6247 #include <sys/types.h>
6248 #ifdef HAVE_SYS_WAIT_H
6249 # include <sys/wait.h>
6252 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6255 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6261 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6264 This macro is obsolescent, as current systems are compatible with POSIX.
6265 New programs need not use this macro.
6268 @cvindex _POSIX_VERSION
6270 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6271 POSIX systems. If there is no @file{unistd.h}, it is definitely
6272 not a POSIX system. However, some non-POSIX systems do
6273 have @file{unistd.h}.
6275 The way to check whether the system supports POSIX is:
6279 #ifdef HAVE_UNISTD_H
6280 # include <sys/types.h>
6281 # include <unistd.h>
6284 #ifdef _POSIX_VERSION
6285 /* Code for POSIX systems. */
6290 @defmac AC_HEADER_TIOCGWINSZ
6291 @acindex{HEADER_TIOCGWINSZ}
6292 @cvindex GWINSZ_IN_SYS_IOCTL
6293 @hdrindex{sys/ioctl.h}
6294 @hdrindex{termios.h}
6295 @c FIXME: I need clarifications from Jim.
6296 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6297 define @code{GWINSZ_IN_SYS_IOCTL}. Otherwise @code{TIOCGWINSZ} can be
6298 found in @file{<termios.h>}.
6304 #ifdef HAVE_TERMIOS_H
6305 # include <termios.h>
6308 #ifdef GWINSZ_IN_SYS_IOCTL
6309 # include <sys/ioctl.h>
6315 @node Generic Headers
6316 @subsection Generic Header Checks
6318 These macros are used to find system header files not covered by the
6319 ``particular'' test macros. If you need to check the contents of a header
6320 as well as find out whether it is present, you have to write your own
6321 test for it (@pxref{Writing Tests}).
6323 @anchor{AC_CHECK_HEADER}
6324 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6325 @ovar{action-if-not-found}, @ovar{includes})
6326 @acindex{CHECK_HEADER}
6327 @caindex header_@var{header-file}
6328 If the system header file @var{header-file} is compilable, execute shell
6329 commands @var{action-if-found}, otherwise execute
6330 @var{action-if-not-found}. If you just want to define a symbol if the
6331 header file is available, consider using @code{AC_CHECK_HEADERS}
6334 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6335 whatever might be required to appear above
6336 @samp{#include <@var{header-file}>} for it to compile without error.
6337 This can be anything, but will normally be additional @samp{#include}
6338 directives. If @var{includes} is omitted or empty, @file{configure} will
6339 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6340 @xref{Default Includes}.
6342 This macro used to check only for the @emph{presence} of a header, not
6343 whether its contents were acceptable to the compiler. Some older
6344 @command{configure} scripts rely on this behavior, so it is still
6345 available by specifying @samp{-} as @var{includes}. This mechanism is
6346 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6347 check is required should use @code{AC_PREPROC_IFELSE}.
6348 @xref{Running the Preprocessor}.
6350 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6351 variable, with characters not suitable for a variable name mapped to
6355 @anchor{AC_CHECK_HEADERS}
6356 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6357 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6359 @acindex{CHECK_HEADERS}
6360 @cvindex HAVE_@var{header}
6361 @caindex header_@var{header-file}
6362 For each given system header file @var{header-file} in the
6363 blank-separated argument list that exists, define
6364 @code{HAVE_@var{header-file}} (in all capitals). If @var{action-if-found}
6365 is given, it is additional shell code to execute when one of the header
6366 files is found. You can give it a value of @samp{break} to break out of
6367 the loop on the first match. If @var{action-if-not-found} is given, it
6368 is executed when one of the header files is not found.
6370 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6371 choose the set of preprocessor directives supplied before the header
6374 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6375 variable, with characters not suitable for a variable name mapped to
6379 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6380 @acindex{CHECK_HEADERS_ONCE}
6381 @cvindex HAVE_@var{header}
6382 For each given system header file @var{header-file} in the
6383 blank-separated argument list that exists, define
6384 @code{HAVE_@var{header-file}} (in all capitals).
6386 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6387 variant generates smaller, faster @command{configure} files. All
6388 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6389 pass, early during the @command{configure} run. The checks cannot be
6390 conditionalized, you cannot specify an @var{action-if-found} or
6391 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6392 for the prerequisites.
6395 In previous versions of Autoconf, these macros merely checked whether
6396 the header was accepted by the preprocessor. This was changed because
6397 the old test was inappropriate for typical uses. Headers are typically
6398 used to compile, not merely to preprocess, and the old behavior
6399 sometimes accepted headers that clashed at compile-time
6400 (@pxref{Present But Cannot Be Compiled}). If for some reason it is
6401 inappropriate to check whether a header is compilable, you should use
6402 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6405 Requiring each header to compile improves the robustness of the test,
6406 but it also requires you to make sure that the @var{includes} are
6407 correct. Most system headers nowadays make sure to @code{#include}
6408 whatever they require, or else have their dependencies satisfied by
6409 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6410 @pxref{Header Portability}, for known exceptions. In general, if you
6411 are looking for @file{bar.h}, which requires that @file{foo.h} be
6412 included first if it exists, you should do something like this:
6415 AC_CHECK_HEADERS([foo.h])
6416 AC_CHECK_HEADERS([bar.h], [], [],
6424 @section Declarations
6425 @cindex Declaration, checking
6427 The following macros check for the declaration of variables and
6428 functions. If there is no macro specifically defined to check for a
6429 symbol you need, then you can use the general macros (@pxref{Generic
6430 Declarations}) or, for more complex tests, you may use
6431 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6434 * Particular Declarations:: Macros to check for certain declarations
6435 * Generic Declarations:: How to find other declarations
6438 @node Particular Declarations
6439 @subsection Particular Declaration Checks
6441 There are no specific macros for declarations.
6443 @node Generic Declarations
6444 @subsection Generic Declaration Checks
6446 These macros are used to find declarations not covered by the ``particular''
6449 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6450 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6451 @acindex{CHECK_DECL}
6452 @caindex have_decl_@var{symbol}
6453 If @var{symbol} (a function, variable, or constant) is not declared in
6454 @var{includes} and a declaration is needed, run the shell commands
6455 @var{action-if-not-found}, otherwise @var{action-if-found}.
6456 @var{includes} is a series of include directives, defaulting to
6457 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6458 prior to the declaration under test.
6460 This macro actually tests whether @var{symbol} is defined as a macro or
6461 can be used as an r-value, not whether it is really declared, because it
6462 is much safer to avoid introducing extra declarations when they are not
6463 needed. In order to facilitate use of C++ and overloaded function
6464 declarations, it is possible to specify function argument types in
6465 parentheses for types which can be zero-initialized:
6468 AC_CHECK_DECL([basename(char *)])
6471 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6472 variable, with characters not suitable for a variable name mapped to
6476 @anchor{AC_CHECK_DECLS}
6477 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6478 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6479 @acindex{CHECK_DECLS}
6480 @cvindex HAVE_DECL_@var{symbol}
6481 @caindex have_decl_@var{symbol}
6482 For each of the @var{symbols} (@emph{comma}-separated list with optional
6483 function argument types for C++ overloads), define
6484 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6485 @var{symbol} is declared, otherwise to @samp{0}. If
6486 @var{action-if-not-found} is given, it is additional shell code to
6487 execute when one of the function declarations is needed, otherwise
6488 @var{action-if-found} is executed.
6490 @var{includes} is a series of include directives, defaulting to
6491 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6492 prior to the declarations under test.
6494 This macro uses an M4 list as first argument:
6496 AC_CHECK_DECLS([strdup])
6497 AC_CHECK_DECLS([strlen])
6498 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6499 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6500 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6503 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6504 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6505 of leaving @code{HAVE_DECL_@var{symbol}} undeclared. When you are
6506 @emph{sure} that the check was performed, use
6507 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6510 #if !HAVE_DECL_SYMBOL
6511 extern char *symbol;
6516 If the test may have not been performed, however, because it is safer
6517 @emph{not} to declare a symbol than to use a declaration that conflicts
6518 with the system's one, you should use:
6521 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6522 void *malloc (size_t *s);
6527 You fall into the second category only in extreme situations: either
6528 your files may be used without being configured, or they are used during
6529 the configuration. In most cases the traditional approach is enough.
6531 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6532 variables, with characters not suitable for a variable name mapped to
6536 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6537 @acindex{CHECK_DECLS_ONCE}
6538 @cvindex HAVE_DECL_@var{symbol}
6539 For each of the @var{symbols} (@emph{comma}-separated list), define
6540 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6541 @var{symbol} is declared in the default include files, otherwise to
6542 @samp{0}. This is a once-only variant of @code{AC_CHECK_DECLS}. It
6543 generates the checking code at most once, so that @command{configure} is
6544 smaller and faster; but the checks cannot be conditionalized and are
6545 always done once, early during the @command{configure} run.
6551 @cindex Structure, checking
6553 The following macros check for the presence of certain members in C
6554 structures. If there is no macro specifically defined to check for a
6555 member you need, then you can use the general structure-member macros
6556 (@pxref{Generic Structures}) or, for more complex tests, you may use
6557 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6560 * Particular Structures:: Macros to check for certain structure members
6561 * Generic Structures:: How to find other structure members
6564 @node Particular Structures
6565 @subsection Particular Structure Checks
6567 The following macros check for certain structures or structure members.
6569 @defmac AC_STRUCT_DIRENT_D_INO
6570 @acindex{STRUCT_DIRENT_D_INO}
6571 @cvindex HAVE_STRUCT_DIRENT_D_INO
6572 @c @caindex header_dirent_dirent_h
6573 @c @caindex member_struct_dirent_d_ino
6574 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6575 Headers}). Then, if @code{struct dirent} contains a @code{d_ino}
6576 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6578 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6579 @code{d_ino}, not whether its contents are always reliable.
6580 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6581 though current systems hide this detail from the user and never return
6582 zero @code{d_ino} values.
6583 Many current systems report an incorrect @code{d_ino} for a directory
6584 entry that is a mount point.
6587 @defmac AC_STRUCT_DIRENT_D_TYPE
6588 @acindex{STRUCT_DIRENT_D_TYPE}
6589 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6590 @c @caindex header_dirent_dirent_h
6591 @c @caindex member_struct_dirent_d_type
6592 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6593 Headers}). Then, if @code{struct dirent} contains a @code{d_type}
6594 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6597 @anchor{AC_STRUCT_ST_BLOCKS}
6598 @defmac AC_STRUCT_ST_BLOCKS
6599 @acindex{STRUCT_ST_BLOCKS}
6600 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6601 @cvindex HAVE_ST_BLOCKS
6603 @caindex member_struct_stat_st_blocks
6604 If @code{struct stat} contains an @code{st_blocks} member, define
6605 @code{HAVE_STRUCT_STAT_ST_BLOCKS}. Otherwise, require an
6606 @code{AC_LIBOBJ} replacement of @samp{fileblocks}. The former name,
6607 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6610 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6614 @defmac AC_STRUCT_TM
6616 @cvindex TM_IN_SYS_TIME
6618 @hdrindex{sys/time.h}
6619 If @file{time.h} does not define @code{struct tm}, define
6620 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6621 had better define @code{struct tm}.
6623 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6624 current systems. New programs need not use this macro.
6627 @anchor{AC_STRUCT_TIMEZONE}
6628 @defmac AC_STRUCT_TIMEZONE
6629 @acindex{STRUCT_TIMEZONE}
6630 @cvindex HAVE_DECL_TZNAME
6631 @cvindex HAVE_STRUCT_TM_TM_ZONE
6632 @cvindex HAVE_TM_ZONE
6633 @cvindex HAVE_TZNAME
6634 @c @caindex member_struct_tm_tm_zone
6635 @c @caindex struct_tm
6636 Figure out how to get the current timezone. If @code{struct tm} has a
6637 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6638 obsoleted @code{HAVE_TM_ZONE}). Otherwise, if the external array
6639 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6640 define @code{HAVE_DECL_TZNAME}.
6643 @node Generic Structures
6644 @subsection Generic Structure Checks
6646 These macros are used to find structure members not covered by the
6647 ``particular'' test macros.
6649 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6650 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6651 @dvar{includes, AC_INCLUDES_DEFAULT})
6652 @acindex{CHECK_MEMBER}
6653 @caindex member_@var{aggregate}_@var{member}
6654 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6655 If no @var{includes} are specified, the default includes are used
6656 (@pxref{Default Includes}).
6659 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6660 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6661 [[#include <pwd.h>]])
6664 You can use this macro for submembers:
6667 AC_CHECK_MEMBER(struct top.middle.bot)
6670 This macro caches its result in the
6671 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6672 characters not suitable for a variable name mapped to underscores.
6675 @anchor{AC_CHECK_MEMBERS}
6676 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6677 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6678 @acindex{CHECK_MEMBERS}
6679 @cvindex HAVE_@var{aggregate}_@var{member}
6680 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6681 @var{members} using the previous macro. When @var{member} belongs to
6682 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6683 capitals, with spaces and dots replaced by underscores). If
6684 @var{action-if-found} is given, it is executed for each of the found
6685 members. If @var{action-if-not-found} is given, it is executed for each
6686 of the members that could not be found.
6688 @var{includes} is a series of include directives, defaulting to
6689 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6690 prior to the members under test.
6692 This macro uses M4 lists:
6694 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6704 The following macros check for C types, either builtin or typedefs. If
6705 there is no macro specifically defined to check for a type you need, and
6706 you don't need to check for any special properties of it, then you can
6707 use a general type-check macro.
6710 * Particular Types:: Special handling to find certain types
6711 * Generic Types:: How to find other types
6714 @node Particular Types
6715 @subsection Particular Type Checks
6717 @hdrindex{sys/types.h}
6720 @hdrindex{inttypes.h}
6721 These macros check for particular C types in @file{sys/types.h},
6722 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6725 The Gnulib @code{stdint} module is an alternate way to define many of
6726 these symbols; it is useful if you prefer your code to assume a
6727 C99-or-better environment. @xref{Gnulib}.
6729 @anchor{AC_TYPE_GETGROUPS}
6730 @defmac AC_TYPE_GETGROUPS
6731 @acindex{TYPE_GETGROUPS}
6732 @cvindex GETGROUPS_T
6733 @caindex type_getgroups
6734 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6735 is the base type of the array argument to @code{getgroups}.
6737 This macro caches the base type in the @code{ac_cv_type_getgroups}
6741 @defmac AC_TYPE_INT8_T
6742 @acindex{TYPE_INT8_T}
6743 @cvindex HAVE_INT8_T
6746 If @file{stdint.h} or @file{inttypes.h} does not define the type
6747 @code{int8_t}, define @code{int8_t} to a signed
6748 integer type that is exactly 8 bits wide and that uses two's complement
6749 representation, if such a type exists.
6750 If you are worried about porting to hosts that lack such a type, you can
6751 use the results of this macro as follows:
6755 # include <stdint.h>
6757 #if defined INT8_MAX || defined int8_t
6758 @emph{code using int8_t}
6760 @emph{complicated alternative using >8-bit 'signed char'}
6764 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6767 @defmac AC_TYPE_INT16_T
6768 @acindex{TYPE_INT16_T}
6769 @cvindex HAVE_INT16_T
6772 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6775 @defmac AC_TYPE_INT32_T
6776 @acindex{TYPE_INT32_T}
6777 @cvindex HAVE_INT32_T
6780 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6783 @defmac AC_TYPE_INT64_T
6784 @acindex{TYPE_INT64_T}
6785 @cvindex HAVE_INT64_T
6788 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6791 @defmac AC_TYPE_INTMAX_T
6792 @acindex{TYPE_INTMAX_T}
6793 @cvindex HAVE_INTMAX_T
6795 @c @caindex type_intmax_t
6796 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6797 define @code{HAVE_INTMAX_T}. Otherwise, define @code{intmax_t} to the
6798 widest signed integer type.
6801 @defmac AC_TYPE_INTPTR_T
6802 @acindex{TYPE_INTPTR_T}
6803 @cvindex HAVE_INTPTR_T
6805 @c @caindex type_intptr_t
6806 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6807 define @code{HAVE_INTPTR_T}. Otherwise, define @code{intptr_t} to a
6808 signed integer type wide enough to hold a pointer, if such a type
6812 @defmac AC_TYPE_LONG_DOUBLE
6813 @acindex{TYPE_LONG_DOUBLE}
6814 @cvindex HAVE_LONG_DOUBLE
6815 @caindex type_long_double
6816 If the C compiler supports a working @code{long double} type, define
6817 @code{HAVE_LONG_DOUBLE}. The @code{long double} type might have the
6818 same range and precision as @code{double}.
6820 This macro caches its result in the @code{ac_cv_type_long_double}
6823 This macro is obsolescent, as current C compilers support @code{long
6824 double}. New programs need not use this macro.
6827 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6828 @acindex{TYPE_LONG_DOUBLE_WIDER}
6829 @cvindex HAVE_LONG_DOUBLE_WIDER
6830 @caindex type_long_double_wider
6831 If the C compiler supports a working @code{long double} type with more
6832 range or precision than the @code{double} type, define
6833 @code{HAVE_LONG_DOUBLE_WIDER}.
6835 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6839 @defmac AC_TYPE_LONG_LONG_INT
6840 @acindex{TYPE_LONG_LONG_INT}
6841 @cvindex HAVE_LONG_LONG_INT
6842 @caindex type_long_long_int
6843 If the C compiler supports a working @code{long long int} type, define
6844 @code{HAVE_LONG_LONG_INT}. However, this test does not test
6845 @code{long long int} values in preprocessor @code{#if} expressions,
6846 because too many compilers mishandle such expressions.
6847 @xref{Preprocessor Arithmetic}.
6849 This macro caches its result in the @code{ac_cv_type_long_long_int}
6853 @defmac AC_TYPE_MBSTATE_T
6854 @acindex{TYPE_MBSTATE_T}
6857 @caindex type_mbstate_t
6858 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6859 @code{mbstate_t} type. Also, define @code{mbstate_t} to be a type if
6860 @code{<wchar.h>} does not declare it.
6862 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6866 @anchor{AC_TYPE_MODE_T}
6867 @defmac AC_TYPE_MODE_T
6868 @acindex{TYPE_MODE_T}
6870 @caindex type_mode_t
6871 Define @code{mode_t} to a suitable type, if standard headers do not
6874 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6877 @anchor{AC_TYPE_OFF_T}
6878 @defmac AC_TYPE_OFF_T
6879 @acindex{TYPE_OFF_T}
6882 Define @code{off_t} to a suitable type, if standard headers do not
6885 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6888 @anchor{AC_TYPE_PID_T}
6889 @defmac AC_TYPE_PID_T
6890 @acindex{TYPE_PID_T}
6893 Define @code{pid_t} to a suitable type, if standard headers do not
6896 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6899 @anchor{AC_TYPE_SIZE_T}
6900 @defmac AC_TYPE_SIZE_T
6901 @acindex{TYPE_SIZE_T}
6903 @caindex type_size_t
6904 Define @code{size_t} to a suitable type, if standard headers do not
6907 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6910 @defmac AC_TYPE_SSIZE_T
6911 @acindex{TYPE_SSIZE_T}
6913 @caindex type_ssize_t
6914 Define @code{ssize_t} to a suitable type, if standard headers do not
6917 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6920 @anchor{AC_TYPE_UID_T}
6921 @defmac AC_TYPE_UID_T
6922 @acindex{TYPE_UID_T}
6926 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6927 headers do not define them.
6929 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6932 @defmac AC_TYPE_UINT8_T
6933 @acindex{TYPE_UINT8_T}
6934 @cvindex HAVE_UINT8_T
6937 If @file{stdint.h} or @file{inttypes.h} does not define the type
6938 @code{uint8_t}, define @code{uint8_t} to an
6939 unsigned integer type that is exactly 8 bits wide, if such a type
6941 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6944 @defmac AC_TYPE_UINT16_T
6945 @acindex{TYPE_UINT16_T}
6946 @cvindex HAVE_UINT16_T
6949 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6952 @defmac AC_TYPE_UINT32_T
6953 @acindex{TYPE_UINT32_T}
6954 @cvindex HAVE_UINT32_T
6957 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6960 @defmac AC_TYPE_UINT64_T
6961 @acindex{TYPE_UINT64_T}
6962 @cvindex HAVE_UINT64_T
6965 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6968 @defmac AC_TYPE_UINTMAX_T
6969 @acindex{TYPE_UINTMAX_T}
6970 @cvindex HAVE_UINTMAX_T
6972 @c @caindex type_uintmax_t
6973 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6974 define @code{HAVE_UINTMAX_T}. Otherwise, define @code{uintmax_t} to the
6975 widest unsigned integer type.
6978 @defmac AC_TYPE_UINTPTR_T
6979 @acindex{TYPE_UINTPTR_T}
6980 @cvindex HAVE_UINTPTR_T
6982 @c @caindex type_uintptr_t
6983 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6984 define @code{HAVE_UINTPTR_T}. Otherwise, define @code{uintptr_t} to an
6985 unsigned integer type wide enough to hold a pointer, if such a type
6989 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6990 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6991 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6992 @caindex type_unsigned_long_long_int
6993 If the C compiler supports a working @code{unsigned long long int} type,
6994 define @code{HAVE_UNSIGNED_LONG_LONG_INT}. However, this test does not test
6995 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6996 because too many compilers mishandle such expressions.
6997 @xref{Preprocessor Arithmetic}.
6999 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
7004 @subsection Generic Type Checks
7006 These macros are used to check for types not covered by the ``particular''
7009 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
7010 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7011 @acindex{CHECK_TYPE}
7012 @caindex type_@var{type}
7013 Check whether @var{type} is defined. It may be a compiler builtin type
7014 or defined by the @var{includes}. @var{includes} is a series of include
7015 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
7016 Includes}), which are used prior to the type under test.
7018 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
7019 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not). The
7020 same test is applied when compiling for C++, which means that in C++
7021 @var{type} should be a type-id and should not be an anonymous
7022 @samp{struct} or @samp{union}.
7024 This macro caches its result in the @code{ac_cv_type_@var{type}}
7025 variable, with @samp{*} mapped to @samp{p} and other characters not
7026 suitable for a variable name mapped to underscores.
7030 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
7031 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7032 @acindex{CHECK_TYPES}
7033 @cvindex HAVE_@var{type}
7034 For each @var{type} of the @var{types} that is defined, define
7035 @code{HAVE_@var{type}} (in all capitals). Each @var{type} must follow
7036 the rules of @code{AC_CHECK_TYPE}. If no @var{includes} are
7037 specified, the default includes are used (@pxref{Default Includes}). If
7038 @var{action-if-found} is given, it is additional shell code to execute
7039 when one of the types is found. If @var{action-if-not-found} is given,
7040 it is executed when one of the types is not found.
7042 This macro uses M4 lists:
7044 AC_CHECK_TYPES([ptrdiff_t])
7045 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
7046 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
7051 Autoconf, up to 2.13, used to provide to another version of
7052 @code{AC_CHECK_TYPE}, broken by design. In order to keep backward
7053 compatibility, a simple heuristic, quite safe but not totally, is
7054 implemented. In case of doubt, read the documentation of the former
7055 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
7058 @node Compilers and Preprocessors
7059 @section Compilers and Preprocessors
7061 @cindex Preprocessors
7064 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
7065 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
7066 the output of the compiler, typically to the empty string if
7067 POSIX and @samp{.exe} if a DOS variant.
7070 They also define the output variable @code{OBJEXT} based on the
7071 output of the compiler, after @file{.c} files have been excluded, typically
7072 to @samp{o} if POSIX, @samp{obj} if a DOS variant.
7074 If the compiler being used does not produce executables, the tests fail. If
7075 the executables can't be run, and cross-compilation is not enabled, they
7076 fail too. @xref{Manual Configuration}, for more on support for cross
7080 * Specific Compiler Characteristics:: Some portability issues
7081 * Generic Compiler Characteristics:: Language independent tests and features
7082 * C Compiler:: Checking its characteristics
7083 * C++ Compiler:: Likewise
7084 * Objective C Compiler:: Likewise
7085 * Objective C++ Compiler:: Likewise
7086 * Erlang Compiler and Interpreter:: Likewise
7087 * Fortran Compiler:: Likewise
7088 * Go Compiler:: Likewise
7091 @node Specific Compiler Characteristics
7092 @subsection Specific Compiler Characteristics
7094 Some compilers exhibit different behaviors.
7097 @item Static/Dynamic Expressions
7098 Autoconf relies on a trick to extract one bit of information from the C
7099 compiler: using negative array sizes. For instance the following
7100 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7104 static int test_array[sizeof (int) == 4 ? 1 : -1];
7108 To our knowledge, there is a single compiler that does not support this
7109 trick: the HP C compilers (the real ones, not only the
7110 ``bundled'') on HP-UX 11.00.
7111 They incorrectly reject the above program with the diagnostic
7112 ``Variable-length arrays cannot have static storage.''
7113 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7114 not from the @code{? 1 : -1}, and
7115 Autoconf works around this problem by casting @code{sizeof (int)} to
7116 @code{long int} before comparing it.
7119 @node Generic Compiler Characteristics
7120 @subsection Generic Compiler Characteristics
7122 @anchor{AC_CHECK_SIZEOF}
7123 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7124 @dvar{includes, AC_INCLUDES_DEFAULT})
7125 @acindex{CHECK_SIZEOF}
7126 @cvindex SIZEOF_@var{type-or-expr}
7127 @caindex sizeof_@var{type-or-expr}
7128 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7129 the size in bytes of @var{type-or-expr}, which may be either a type or
7130 an expression returning a value that has a size. If the expression
7131 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7132 @var{includes} is a series of include directives, defaulting to
7133 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7134 prior to the expression under test.
7136 This macro now works even when cross-compiling. The @var{unused}
7137 argument was used when cross-compiling.
7139 For example, the call
7142 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7143 AC_CHECK_SIZEOF([int *])
7147 defines @code{SIZEOF_INT_P} to be 8 on x86-64 systems.
7149 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7150 variable, with @samp{*} mapped to @samp{p} and other characters not
7151 suitable for a variable name mapped to underscores.
7154 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7155 @acindex{CHECK_ALIGNOF}
7156 @cvindex ALIGNOF_@var{type}
7157 @caindex alignof_@var{type-or-expr}
7158 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7159 alignment in bytes of @var{type}. @samp{@var{type} y;} must be valid as
7160 a structure member declaration. If @samp{type} is unknown, the result
7161 is 0. If no @var{includes} are specified, the default includes are used
7162 (@pxref{Default Includes}).
7164 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7165 variable, with @samp{*} mapped to @samp{p} and other characters not
7166 suitable for a variable name mapped to underscores.
7169 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7170 @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7171 @acindex{COMPUTE_INT}
7172 Store into the shell variable @var{var} the value of the integer
7173 @var{expression}. The
7174 value should fit in an initializer in a C variable of type @code{signed
7175 long}. To support cross compilation, it should be possible to evaluate
7176 the expression at compile-time. If no @var{includes} are specified, the
7177 default includes are used (@pxref{Default Includes}).
7179 Execute @var{action-if-fails} if the value cannot be determined correctly.
7182 @defmac AC_LANG_WERROR
7183 @acindex{LANG_WERROR}
7184 Normally Autoconf ignores warnings generated by the compiler, linker, and
7185 preprocessor. If this macro is used, warnings count as fatal
7186 errors for the current language. This macro is useful when the
7187 results of configuration are used where warnings are unacceptable; for
7188 instance, if parts of a program are built with the GCC
7190 option. If the whole program is built using @option{-Werror} it is
7191 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7198 @ovindex OPENMP_CFLAGS
7199 @ovindex OPENMP_CXXFLAGS
7200 @ovindex OPENMP_FFLAGS
7201 @ovindex OPENMP_FCFLAGS
7202 @caindex prog_c_openmp
7203 @caindex prog_cxx_openmp
7204 @caindex prog_f77_openmp
7205 @caindex prog_fc_openmp
7206 @uref{https://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7207 and Fortran that simplify optimization of shared memory parallelism,
7208 which is a common problem on multi-core CPUs.
7210 If the current language is C, the macro @code{AC_OPENMP} sets the
7211 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7212 supporting OpenMP@. @code{OPENMP_CFLAGS} is set to empty if the
7213 compiler already supports OpenMP, if it has no way to activate OpenMP
7214 support, or if the user rejects OpenMP support by invoking
7215 @samp{configure} with the @samp{--disable-openmp} option.
7217 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7218 preprocessing program source, and when linking programs. Therefore you
7219 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7220 that use OpenMP@. If you preprocess OpenMP-specific C code, you also
7221 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}. The presence of
7222 OpenMP support is revealed at compile time by the preprocessor macro
7225 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7226 shared library to the program's dependencies, so its use is recommended
7227 only on programs that actually require OpenMP.
7229 If the current language is C++, @code{AC_OPENMP} sets the variable
7230 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler. The same remarks
7233 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7234 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7235 respectively. Similar remarks as for C hold, except that
7236 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7237 signals OpenMP support.
7239 For portability, it is best to avoid spaces between @samp{#} and
7240 @samp{pragma omp}. That is, write @samp{#pragma omp}, not
7241 @samp{# pragma omp}. The Sun WorkShop 6.2 C compiler chokes on the
7244 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7245 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7246 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7248 @strong{Caution:} Some of the compiler options that @code{AC_OPENMP}
7249 tests, mean ``enable OpenMP'' to one compiler, but ``write output to a
7250 file named @file{mp} or @file{penmp}'' to other compilers. We cannot
7251 guarantee that the implementation of @code{AC_OPENMP} will not overwrite
7252 an existing file with either of these names.
7254 Therefore, as a defensive measure, a @command{configure} script that
7255 uses @code{AC_OPENMP} will issue an error and stop (before doing any of
7256 the operations that might overwrite these files) upon encountering
7257 either of these files in its working directory.
7258 @command{autoconf} will also issue an error if it finds either of
7259 these files in the same directory as a @file{configure.ac} that
7260 uses @code{AC_OPENMP}.
7262 If you have files with either of these names at the top level of your
7263 source tree, and you need to use @code{AC_OPENMP}, we recommend you
7264 either change their names or move them into a subdirectory.
7268 @subsection C Compiler Characteristics
7270 The following macros provide ways to find and exercise a C Compiler.
7271 There are a few constructs that ought to be avoided, but do not deserve
7272 being checked for, since they can easily be worked around.
7275 @item Don't use lines containing solitary backslashes
7276 They tickle a bug in the HP-UX C compiler (checked on
7278 11.00, and 11i). When given the following source:
7283 * A comment with backslash-newlines in it. %@{ %@} *\
7287 " A string with backslash-newlines in it %@{ %@} \\
7289 char apostrophe = '\\
7297 the compiler incorrectly fails with the diagnostics ``Non-terminating
7298 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7299 Removing the lines with solitary backslashes solves the problem.
7301 @item Don't compile several files at once if output matters to you
7302 Some compilers, such as HP's, report names of files being
7303 compiled when given more than one file operand. For instance:
7312 This can cause problems if you observe the output of the compiler to
7313 detect failures. Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7314 b.o} solves the issue.
7316 @item Don't rely on correct @code{#line} support
7317 On Solaris, @command{c89} (at least through Oracle Developer Studio 12.6)
7318 diagnoses @code{#line} directives whose line
7319 numbers are greater than 32767. Nothing in POSIX
7320 makes this invalid. That is why Autoconf stopped issuing
7321 @code{#line} directives.
7325 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7331 Determine a C compiler to use.
7333 If the environment variable @code{CC} is set, its value will be taken as
7334 the name of the C compiler to use. Otherwise, search for a C compiler
7335 under a series of likely names, trying @code{gcc} and @code{cc} first.
7336 Regardless, the output variable @code{CC} is set to the chosen compiler.
7338 If the optional first argument to the macro is used, it must be a
7339 whitespace-separated list of potential names for a C compiler,
7340 which overrides the built-in list.
7342 If no C compiler can be found, @command{configure} will error out.
7344 If the selected C compiler is found to be GNU C (regardless of
7345 its name), the shell variable @code{GCC} will be set to @samp{yes}.
7346 If the shell variable @code{CFLAGS} was not already set, it is set
7347 to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7348 where GCC does not accept @option{-g}), or @option{-g} for other
7349 compilers. @code{CFLAGS} is then made an output variable.
7350 You can override the default for @code{CFLAGS} by inserting a shell
7351 default assignment between @code{AC_INIT} and @code{AC_PROG_CC}:
7354 : $@{CFLAGS="@var{options}"@}
7357 where @var{options} are the appropriate set of options to use by
7358 default. (It is important to use this construct rather than a normal
7359 assignment, so that @code{CFLAGS} can still be overridden by the
7360 person building the package. @xref{Preset Output Variables}.)
7362 If necessary, options are added to @code{CC} to enable support for
7363 ISO Standard C features with extensions, preferring the newest edition
7364 of the C standard for which detection is supported. Currently the
7365 newest edition Autoconf knows how to detect support for is C23. After calling
7366 this macro you can check whether the C compiler has been set to accept
7367 standard C by inspecting the shell variable @code{ac_prog_cc_stdc}.
7368 Its value is @samp{c23}, @samp{c11}, @samp{c99}, or @samp{c89}, respectively,
7369 if the C compiler has been set to use the 2023, 2011, 1999, or 1990 edition of
7370 the C standard, and @samp{no} if the compiler does not support compiling
7372 (There is no special value for the 2017 edition of the C standard,
7373 as it is a minor revision that does not introduce new language features.)
7375 The tests for standard conformance are not comprehensive. They test the
7376 value of @code{__STDC_VERSION__}, and a
7377 representative sample of the language features added in each version of
7378 the C standard. They do not examine @code{__STDC__}
7379 because some compilers by default leave it undefined.
7380 They do not test for variable-length arrays,
7381 a C99 feature that was made optional in C11;
7382 if you need to use this feature when available, use @code{AC_C_VARARRAYS}.
7383 They do not test the C standard library, because the C
7384 compiler might be generating code for a ``freestanding environment''
7385 (in which most of the standard library is optional). If you need to know
7386 whether a particular C standard header exists, use @code{AC_CHECK_HEADER}.
7388 None of the options that may be added to @code{CC} by this macro
7389 enable @emph{strict} conformance to the C standard. In particular,
7390 system-specific extensions are not disabled. (For example, for GNU C,
7391 the @option{-std=gnu@var{nn}} options may be used, but not the
7392 @option{-std=c@var{nn}} options.)
7394 Many Autoconf macros use a compiler, and thus call
7395 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7396 determined before the body of the outermost @code{AC_DEFUN} macro.
7397 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7398 performs certain checks (such as the proper value of @env{EXEEXT}) only
7399 on the first invocation. Therefore, care must be used when invoking
7400 this macro from within another macro rather than at the top level
7401 (@pxref{Expanded Before Required}).
7404 @anchor{AC_PROG_CC_C_O}
7405 @defmac AC_PROG_CC_C_O
7406 @acindex{PROG_CC_C_O}
7407 @cvindex NO_MINUS_C_MINUS_O
7408 @caindex prog_cc_@var{compiler}_c_o
7409 If the C compiler does not accept the @option{-c} and @option{-o} options
7410 simultaneously, define @code{NO_MINUS_C_MINUS_O}. This macro actually
7411 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7412 the first @code{cc} in the path. The test fails if one fails. This
7413 macro was created for GNU Make to choose the default C compilation
7416 For the compiler @var{compiler}, this macro caches its result in the
7417 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7425 Set output variable @code{CPP} to a command that runs the
7426 C preprocessor. If @samp{$CC -E} doesn't work, tries @code{cpp} and
7427 @file{/lib/cpp}, in that order.
7429 It is only portable to run @code{CPP} on files with a @file{.c}
7432 Some preprocessors don't indicate missing include files by the error
7433 status. For such preprocessors an internal variable is set that causes
7434 other macros to check the standard error from the preprocessor and
7435 consider the test failed if any warnings have been reported.
7436 For most preprocessors, though, warnings do not cause include-file
7437 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7440 @defmac AC_PROG_CPP_WERROR
7441 @acindex{PROG_CPP_WERROR}
7443 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7444 preprocessor as errors even if the preprocessor exit status indicates
7445 success. This is useful for avoiding headers that generate mandatory
7446 warnings, such as deprecation notices.
7450 The following macros check for C compiler or machine architecture
7451 features. To check for characteristics not listed here, use
7452 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7453 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7455 @defmac AC_C_BACKSLASH_A
7456 @acindex{C_BACKSLASH_A}
7457 @cvindex HAVE_C_BACKSLASH_A
7458 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7461 This macro is obsolescent, as current C compilers understand @samp{\a}.
7462 New programs need not use this macro.
7465 @anchor{AC_C_BIGENDIAN}
7466 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7467 @ovar{action-if-unknown}, @ovar{action-if-universal})
7468 @acindex{C_BIGENDIAN}
7469 @cvindex WORDS_BIGENDIAN
7471 If words are stored with the most significant byte first (like Motorola
7472 and SPARC CPUs), execute @var{action-if-true}. If words are stored with
7473 the least significant byte first (like Intel and VAX CPUs), execute
7474 @var{action-if-false}.
7476 This macro runs a test-case if endianness cannot be determined from the
7477 system header files. When cross-compiling, the test-case is not run but
7478 grep'ed for some magic values. @var{action-if-unknown} is executed if
7479 the latter case fails to determine the byte sex of the host system.
7481 In some cases a single run of a compiler can generate code for multiple
7482 architectures. This can happen, for example, when generating Mac OS X
7483 universal binary files, which work on both PowerPC and Intel
7484 architectures. In this case, the different variants might be for
7485 architectures with differing endianness. If
7486 @command{configure} detects this, it executes @var{action-if-universal}
7487 instead of @var{action-if-unknown}.
7489 The default for @var{action-if-true} is to define
7490 @samp{WORDS_BIGENDIAN}. The default for @var{action-if-false} is to do
7491 nothing. The default for @var{action-if-unknown} is to
7492 abort configure and tell the installer how to bypass this test.
7493 And finally, the default for @var{action-if-universal} is to ensure that
7494 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7495 detected and the current code is big-endian; this default works only if
7496 @command{autoheader} is used (@pxref{autoheader Invocation}).
7498 If you use this macro without specifying @var{action-if-universal}, you
7499 should also use @code{AC_CONFIG_HEADERS}; otherwise
7500 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7509 If the C compiler does not fully support the @code{const} keyword,
7510 define @code{const} to be empty. Some C compilers that do
7511 not define @code{__STDC__} do support @code{const}; some compilers that
7512 define @code{__STDC__} do not completely support @code{const}. Programs
7513 can simply use @code{const} as if every C compiler supported it; for
7514 those that don't, the makefile or configuration header file
7515 defines it as empty.
7517 Occasionally installers use a C++ compiler to compile C code, typically
7518 because they lack a C compiler. This causes problems with @code{const},
7519 because C and C++ treat @code{const} differently. For example:
7526 is valid in C but not in C++. These differences unfortunately cannot be
7527 papered over by defining @code{const} to be empty.
7529 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7530 as this generally yields better results in practice. However, using a
7531 C++ compiler to compile C code is not recommended or supported, and
7532 installers who run into trouble in this area should get a C compiler
7533 like GCC to compile their C code.
7535 This macro caches its result in the @code{ac_cv_c_const} variable.
7537 This macro is obsolescent, as current C compilers support @code{const}.
7538 New programs need not use this macro.
7541 @defmac AC_C__GENERIC
7542 @acindex{C__GENERIC}
7544 If the C compiler supports C11-style generic selection using the
7545 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7548 @defmac AC_C_RESTRICT
7549 @acindex{C_RESTRICT}
7552 If the C compiler recognizes a variant spelling for the @code{restrict}
7553 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7554 then define @code{restrict} to that; this is more likely to do the right
7555 thing with compilers that support language variants where plain
7556 @code{restrict} is not a keyword. Otherwise, if the C compiler
7557 recognizes the @code{restrict} keyword, don't do anything.
7558 Otherwise, define @code{restrict} to be empty.
7559 Thus, programs may simply use @code{restrict} as if every C compiler
7560 supported it; for those that do not, the makefile
7561 or configuration header defines it away.
7563 Although support in C++ for the @code{restrict} keyword is not
7564 required, several C++ compilers do accept the keyword.
7565 This macro works for them, too.
7567 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7568 if @code{restrict} is not supported, and a supported spelling otherwise.
7571 @defmac AC_C_VOLATILE
7572 @acindex{C_VOLATILE}
7574 If the C compiler does not understand the keyword @code{volatile},
7575 define @code{volatile} to be empty. Programs can simply use
7576 @code{volatile} as if every C compiler supported it; for those that do
7577 not, the makefile or configuration header defines it as
7580 If the correctness of your program depends on the semantics of
7581 @code{volatile}, simply defining it to be empty does, in a sense, break
7582 your code. However, given that the compiler does not support
7583 @code{volatile}, you are at its mercy anyway. At least your
7584 program compiles, when it wouldn't before.
7585 @xref{Volatile Objects}, for more about @code{volatile}.
7587 This macro is obsolescent, as current C compilers support @code{volatile}.
7588 New programs need not use this macro.
7591 @anchor{AC_C_INLINE}
7595 If the C compiler supports the keyword @code{inline}, do nothing.
7596 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7597 if it accepts one of those, otherwise define @code{inline} to be empty.
7600 @anchor{AC_C_CHAR_UNSIGNED}
7601 @defmac AC_C_CHAR_UNSIGNED
7602 @acindex{C_CHAR_UNSIGNED}
7603 @cvindex __CHAR_UNSIGNED__
7604 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7605 unless the C compiler predefines it.
7607 These days, using this macro is not necessary. The same information can
7608 be determined by this portable alternative, thus avoiding the use of
7609 preprocessor macros in the namespace reserved for the implementation.
7614 # define CHAR_UNSIGNED 1
7619 @defmac AC_C_STRINGIZE
7620 @acindex{C_STRINGIZE}
7621 @cvindex HAVE_STRINGIZE
7622 If the C preprocessor supports the stringizing operator, define
7623 @code{HAVE_STRINGIZE}. The stringizing operator is @samp{#} and is
7624 found in macros such as this:
7630 This macro is obsolescent, as current C compilers support the
7631 stringizing operator. New programs need not use this macro.
7634 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7635 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7636 @cvindex FLEXIBLE_ARRAY_MEMBER
7637 If the C compiler supports flexible array members, define
7638 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7639 That way, a declaration like this:
7645 double val[FLEXIBLE_ARRAY_MEMBER];
7650 will let applications use the ``struct hack'' even with compilers that
7651 do not support flexible array members. To allocate and use such an
7652 object, you can use code like this:
7656 size_t n = compute_value_count ();
7658 malloc (offsetof (struct s, val)
7659 + n * sizeof (double));
7661 for (i = 0; i < n; i++)
7662 p->val[i] = compute_value (i);
7666 @defmac AC_C_VARARRAYS
7667 @acindex{C_VARARRAYS}
7668 @cvindex __STDC_NO_VLA__
7669 @cvindex HAVE_C_VARARRAYS
7670 If the C compiler does not support variable-length arrays, define the
7671 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined. A
7672 variable-length array is an array of automatic storage duration whose
7673 length is determined at run time, when the array is declared. For
7674 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7675 if the C compiler supports variable-length arrays, but this usage is
7676 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7681 @cvindex HAVE_TYPEOF
7683 If the C compiler supports GNU C's @code{typeof} syntax either
7685 through a different spelling of the keyword (e.g., @code{__typeof__}),
7686 define @code{HAVE_TYPEOF}. If the support is available only through a
7687 different spelling, define @code{typeof} to that spelling.
7690 @defmac AC_C_PROTOTYPES
7691 @acindex{C_PROTOTYPES}
7693 @cvindex __PROTOTYPES
7695 If function prototypes are understood by the compiler (as determined by
7696 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7697 Defining @code{__PROTOTYPES} is for the benefit of
7698 header files that cannot use macros that infringe on user name space.
7700 This macro is obsolescent, as current C compilers support prototypes.
7701 New programs need not use this macro.
7705 @subsection C++ Compiler Characteristics
7708 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7714 Determine a C++ compiler to use.
7716 If either the environment variable @code{CXX} or the environment
7717 variable @code{CCC} is set, its value will be taken as the name of a
7718 C++ compiler. If both are set, @code{CXX} is preferred. If neither
7719 are set, search for a C++ compiler under a series of likely names,
7720 trying @code{g++} and @code{c++} first. Regardless, the output
7721 variable @code{CXX} is set to the chosen compiler.
7723 If the optional first argument to the macro is used, it must be a
7724 whitespace-separated list of potential names for a C++ compiler,
7725 which overrides the built-in list.
7727 If no C++ compiler can be found, as a last resort @code{CXX} is set to
7728 @code{g++} (and subsequent tests will probably fail).
7730 If the selected C++ compiler is found to be GNU C++ (regardless of
7731 its name), the shell variable @code{GXX} will be set to @samp{yes}.
7732 If the shell variable @code{CXXFLAGS} was not already set, it is set
7733 to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on systems
7734 where G++ does not accept @option{-g}), or @option{-g} for other
7735 compilers. @code{CXXFLAGS} is then made an output variable.
7736 You can override the default for @code{CXXFLAGS} by inserting a shell
7737 default assignment between @code{AC_INIT} and @code{AC_PROG_CXX}:
7740 : $@{CXXFLAGS="@var{options}"@}
7743 where @var{options} are the appropriate set of options to use by
7744 default. (It is important to use this construct rather than a normal
7745 assignment, so that @code{CXXFLAGS} can still be overridden by the
7746 person building the package. @xref{Preset Output Variables}.)
7749 @defmac AC_PROG_CXXCPP
7750 @acindex{PROG_CXXCPP}
7753 Set output variable @code{CXXCPP} to a command that runs the C++
7754 preprocessor. If @samp{$CXX -E} doesn't work, tries @code{cpp} and
7755 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7756 may or may not set C++-specific predefined macros (such as @code{__cplusplus}).
7758 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7759 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7761 Some preprocessors don't indicate missing include files by the error
7762 status. For such preprocessors an internal variable is set that causes
7763 other macros to check the standard error from the preprocessor and
7764 consider the test failed if any warnings have been reported. However,
7765 it is not known whether such broken preprocessors exist for C++.
7768 @defmac AC_PROG_CXX_C_O
7769 @acindex{PROG_CXX_C_O}
7770 @cvindex CXX_NO_MINUS_C_MINUS_O
7771 Test whether the C++ compiler accepts the options @option{-c} and
7772 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7777 @node Objective C Compiler
7778 @subsection Objective C Compiler Characteristics
7781 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7787 Determine an Objective C compiler to use. If @code{OBJC} is not already
7788 set in the environment, check for Objective C compilers. Set output
7789 variable @code{OBJC} to the name of the compiler found.
7791 This macro may, however, be invoked with an optional first argument
7792 which, if specified, must be a blank-separated list of Objective C compilers to
7793 search for. This just gives the user an opportunity to specify an
7794 alternative search list for the Objective C compiler. For example, if you
7795 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7799 AC_PROG_OBJC([gcc objcc objc])
7802 If using a compiler that supports GNU Objective C, set shell variable
7803 @code{GOBJC} to @samp{yes}. If output variable @code{OBJCFLAGS} was not
7804 already set, set it to @option{-g -O2} for a GNU Objective C
7805 compiler (@option{-O2} on systems where the compiler does not accept
7806 @option{-g}), or @option{-g} for other compilers.
7809 @defmac AC_PROG_OBJCPP
7810 @acindex{PROG_OBJCPP}
7813 Set output variable @code{OBJCPP} to a command that runs the Objective C
7814 preprocessor. If @samp{$OBJC -E} doesn't work, tries @code{cpp} and
7815 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7816 may or may not set Objective-C-specific predefined macros (such as
7821 @node Objective C++ Compiler
7822 @subsection Objective C++ Compiler Characteristics
7825 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7826 @acindex{PROG_OBJCXX}
7828 @evindex OBJCXXFLAGS
7830 @ovindex OBJCXXFLAGS
7831 Determine an Objective C++ compiler to use. If @code{OBJCXX} is not already
7832 set in the environment, check for Objective C++ compilers. Set output
7833 variable @code{OBJCXX} to the name of the compiler found.
7835 This macro may, however, be invoked with an optional first argument
7836 which, if specified, must be a blank-separated list of Objective C++ compilers
7837 to search for. This just gives the user an opportunity to specify an
7838 alternative search list for the Objective C++ compiler. For example, if you
7839 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7843 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7846 If using a compiler that supports GNU Objective C++, set shell variable
7847 @code{GOBJCXX} to @samp{yes}. If output variable @code{OBJCXXFLAGS} was not
7848 already set, set it to @option{-g -O2} for a GNU Objective C++
7849 compiler (@option{-O2} on systems where the compiler does not accept
7850 @option{-g}), or @option{-g} for other compilers.
7853 @defmac AC_PROG_OBJCXXCPP
7854 @acindex{PROG_OBJCXXCPP}
7857 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7858 preprocessor. If @samp{$OBJCXX -E} doesn't work, tries @code{cpp} and
7859 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7860 may or may not set Objective-C++-specific predefined macros (such as
7861 @code{__cplusplus} and @code{__OBJC__}).
7865 @node Erlang Compiler and Interpreter
7866 @subsection Erlang Compiler and Interpreter Characteristics
7869 Autoconf defines the following macros for determining paths to the essential
7870 Erlang/OTP programs:
7872 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7873 @acindex{ERLANG_PATH_ERLC}
7878 Determine an Erlang compiler to use. If @code{ERLC} is not already set in the
7879 environment, check for @command{erlc}. Set output variable @code{ERLC} to the
7880 complete path of the compiler command found. In addition, if @code{ERLCFLAGS}
7881 is not set in the environment, set it to an empty value.
7883 The two optional arguments have the same meaning as the two last arguments of
7884 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program. For
7885 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7889 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7893 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7894 @acindex{ERLANG_NEED_ERLC}
7895 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7896 error message and exits the @command{configure} script if the @command{erlc}
7897 program is not found.
7900 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7901 @acindex{ERLANG_PATH_ERL}
7904 Determine an Erlang interpreter to use. If @code{ERL} is not already
7906 environment, check for @command{erl}. Set output variable @code{ERL} to the
7907 complete path of the interpreter command found.
7909 The two optional arguments have the same meaning as the two last arguments of
7910 macro @code{AC_PATH_PROG} for looking for the @command{erl} program. For
7911 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7915 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7919 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7920 @acindex{ERLANG_NEED_ERL}
7921 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7922 error message and exits the @command{configure} script if the @command{erl}
7923 program is not found.
7927 @node Fortran Compiler
7928 @subsection Fortran Compiler Characteristics
7932 The Autoconf Fortran support is divided into two categories: legacy
7933 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7934 The former are intended for traditional Fortran 77 code, and have output
7935 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}. The latter
7936 are for newer programs that can (or must) compile under the newer
7937 Fortran standards, and have output variables like @code{FC},
7938 @code{FCFLAGS}, and @code{FCLIBS}.
7940 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7941 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7942 @code{FC} and @code{F77} macros behave almost identically, and so they
7943 are documented together in this section.
7946 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7952 @caindex f77_compiler_gnu
7954 Determine a Fortran 77 compiler to use. If @code{F77} is not already
7955 set in the environment, then check for @code{g77} and @code{f77}, and
7956 then some other names. Set the output variable @code{F77} to the name
7957 of the compiler found.
7959 This macro may, however, be invoked with an optional first argument
7960 which, if specified, must be a blank-separated list of Fortran 77
7961 compilers to search for. This just gives the user an opportunity to
7962 specify an alternative search list for the Fortran 77 compiler. For
7963 example, if you didn't like the default order, then you could invoke
7964 @code{AC_PROG_F77} like this:
7967 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7970 If using a compiler that supports GNU Fortran 77,
7971 set the shell variable @code{G77} to @samp{yes}.
7972 If the output variable @code{FFLAGS} was not already set in the
7973 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
7974 where the GNU Fortran 77 compiler does not accept @option{-g}), or
7975 @option{-g} for other compilers.
7977 The result of the GNU test is cached in the
7978 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7979 @code{ac_cv_prog_f77_g} variable.
7982 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7988 @caindex fc_compiler_gnu
7990 Determine a Fortran compiler to use. If @code{FC} is not already set in
7991 the environment, then @code{dialect} is a hint to indicate what Fortran
7992 dialect to search for; the default is to search for the newest available
7993 dialect. Set the output variable @code{FC} to the name of the compiler
7996 By default, newer dialects are preferred over older dialects, but if
7997 @code{dialect} is specified then older dialects are preferred starting
7998 with the specified dialect. @code{dialect} can currently be one of
7999 Fortran 77, Fortran 90, or Fortran 95. However, this is only a hint of
8000 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
8001 and no attempt is made to guarantee that a particular language standard
8002 is actually supported. Thus, it is preferable that you avoid the
8003 @code{dialect} option, and use AC_PROG_FC only for code compatible with
8004 the latest Fortran standard.
8006 This macro may, alternatively, be invoked with an optional first argument
8007 which, if specified, must be a blank-separated list of Fortran
8008 compilers to search for, just as in @code{AC_PROG_F77}.
8010 If using a compiler that supports GNU Fortran,
8011 set the shell variable @code{GFC} to @samp{yes}.
8012 If the output variable @code{FCFLAGS} was not already set in the
8013 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
8014 @option{-O2} where the compiler does not accept @option{-g}), or
8015 @option{-g} for other compilers.
8017 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
8018 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
8022 @defmac AC_PROG_F77_C_O
8023 @defmacx AC_PROG_FC_C_O
8024 @acindex{PROG_F77_C_O}
8025 @acindex{PROG_FC_C_O}
8026 @cvindex F77_NO_MINUS_C_MINUS_O
8027 @cvindex FC_NO_MINUS_C_MINUS_O
8028 @caindex prog_f77_c_o
8029 @caindex prog_fc_c_o
8030 Test whether the Fortran compiler accepts the options @option{-c} and
8031 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
8032 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
8034 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
8035 @code{ac_cv_prog_fc_c_o} variable, respectively.
8038 The following macros check for Fortran compiler characteristics.
8039 To check for characteristics not listed here, use
8040 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
8041 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
8042 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
8043 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
8046 @defmac AC_F77_LIBRARY_LDFLAGS
8047 @defmacx AC_FC_LIBRARY_LDFLAGS
8048 @acindex{F77_LIBRARY_LDFLAGS}
8050 @acindex{FC_LIBRARY_LDFLAGS}
8056 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
8057 @dfn{Fortran intrinsic and runtime libraries} that are required to
8058 successfully link a Fortran program or shared library. The output
8059 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
8060 should be included after @code{LIBS} when linking).
8062 This macro is intended to be used in those situations when it is
8063 necessary to mix, e.g., C++ and Fortran source code in a single
8064 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
8065 automake, GNU Automake}).
8067 For example, if object files from a C++ and Fortran compiler must be
8068 linked together, then the C++ compiler/linker must be used for linking
8069 (since special C++-ish things need to happen at link time like calling
8070 global constructors, instantiating templates, enabling exception
8073 However, the Fortran intrinsic and runtime libraries must be linked in
8074 as well, but the C++ compiler/linker doesn't know by default how to add
8075 these Fortran 77 libraries. Hence, this macro was created to determine
8076 these Fortran libraries.
8078 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8079 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8080 link C/C++ with Fortran; see below. Further, it is highly recommended
8081 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8082 because the complex defines that the function wrapper macros create
8083 may not work with C/C++ compiler drivers.
8085 These macros internally compute the flag needed to verbose linking
8086 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8087 variables, respectively. The computed linker flags are cached in
8088 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8091 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8092 @dvar{action-if-not-found, AC_MSG_FAILURE})
8093 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8094 @dvar{action-if-not-found, AC_MSG_FAILURE})
8095 @acindex{F77_DUMMY_MAIN}
8096 @cvindex F77_DUMMY_MAIN
8097 @acindex{FC_DUMMY_MAIN}
8098 @cvindex FC_DUMMY_MAIN
8099 @caindex f77_dummy_main
8100 @caindex fc_dummy_main
8101 With many compilers, the Fortran libraries detected by
8102 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8103 their own @code{main} entry function that initializes things like
8104 Fortran I/O, and which then calls a user-provided entry function named
8105 (say) @code{MAIN__} to run the user's program. The
8106 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8107 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8110 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8111 one prefers to provide one's own @code{main} and skip the Fortran
8112 library initializations. In this case, however, one may still need to
8113 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8114 on some systems. @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8115 detects whether any such routine is @emph{required} for linking, and
8116 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8117 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8118 was found, and @code{none} when no such dummy main is needed.
8120 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8121 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8122 @emph{if} it is required. @var{action-if-not-found} defaults to
8123 exiting with an error.
8125 In order to link with Fortran routines, the user's C/C++ program should
8126 then include the following code to define the dummy main if it is
8130 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8131 #ifdef F77_DUMMY_MAIN
8135 int F77_DUMMY_MAIN (void) @{ return 1; @}
8139 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8141 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8142 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8143 explicitly unless one wants to change the default actions.
8145 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8146 @code{ac_cv_fc_dummy_main} variable, respectively.
8157 As discussed above, many Fortran libraries allow you to provide an entry
8158 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8159 is then called by a @code{main} function in the Fortran libraries that
8160 initializes things like Fortran I/O@. The
8161 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8162 @emph{possible} to utilize such an alternate main function, and defines
8163 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function. (If no
8164 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8165 simply defined to @code{main}.)
8167 Thus, when calling Fortran routines from C that perform things like I/O,
8168 one should use this macro and declare the "main" function like so:
8171 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8175 int F77_MAIN (int argc, char *argv[]);
8178 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8180 The result of this macro is cached in the @code{ac_cv_f77_main} or
8181 @code{ac_cv_fc_main} variable, respectively.
8184 @defmac AC_F77_WRAPPERS
8185 @defmacx AC_FC_WRAPPERS
8186 @acindex{F77_WRAPPERS}
8189 @acindex{FC_WRAPPERS}
8192 @caindex f77_mangling
8193 @caindex fc_mangling
8194 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8195 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8196 mangle the names of C/C++ identifiers, and identifiers with underscores,
8197 respectively, so that they match the name-mangling scheme used by the
8200 Fortran is case-insensitive, and in order to achieve this the Fortran
8201 compiler converts all identifiers into a canonical case and format. To
8202 call a Fortran subroutine from C or to write a C function that is
8203 callable from Fortran, the C program must explicitly use identifiers in
8204 the format expected by the Fortran compiler. In order to do this, one
8205 simply wraps all C identifiers in one of the macros provided by
8206 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}. For example, suppose
8207 you have the following Fortran 77 subroutine:
8210 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8211 subroutine foobar (x, y)
8212 double precision x, y
8218 You would then declare its prototype in C or C++ as:
8221 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8222 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8224 extern "C" /* prevent C++ name mangling */
8226 void FOOBAR_F77 (double *x, double *y);
8229 Note that we pass both the lowercase and uppercase versions of the
8230 function name to @code{F77_FUNC} so that it can select the right one.
8231 Note also that all parameters to Fortran 77 routines are passed as
8232 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8235 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8237 Although Autoconf tries to be intelligent about detecting the
8238 name-mangling scheme of the Fortran compiler, there may be Fortran
8239 compilers that it doesn't support yet. In this case, the above code
8240 generates a compile-time error, but some other behavior
8241 (e.g., disabling Fortran-related features) can be induced by checking
8242 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8244 Now, to call that routine from a C program, we would do something like:
8247 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8249 double x = 2.7183, y;
8250 FOOBAR_F77 (&x, &y);
8254 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8255 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8256 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments). This is
8257 because some Fortran compilers mangle names differently if they contain
8260 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8261 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8262 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8265 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8266 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8269 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8270 hold the mangled version @var{name} according to the rules of the
8271 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8272 @code{AC_FC_WRAPPERS}). @var{shellvar} is optional; if it is not
8273 supplied, the shell variable is simply @var{name}. The purpose of
8274 this macro is to give the caller a way to access the name-mangling
8275 information other than through the C preprocessor as above, for example,
8276 to call Fortran routines from some language other than C/C++.
8279 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8280 @dvar{action-if-failure, AC_MSG_FAILURE})
8281 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8282 @dvar{action-if-failure, AC_MSG_FAILURE})
8284 @acindex{FC_PP_SRCEXT}
8285 @caindex fc_srcext_@var{ext}
8286 @caindex fc_pp_srcext_@var{ext}
8287 By default, the @code{FC} macros perform their tests using a @file{.f}
8288 extension for source-code files. Some compilers, however, only enable
8289 newer language features for appropriately named files, e.g., Fortran 90
8290 features only for @file{.f90} files, or preprocessing only with
8291 @file{.F} files or maybe other upper-case extensions. On the other
8292 hand, some other compilers expect all source files to end in @file{.f}
8293 and require special flags to support other file name extensions. The
8294 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8297 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8298 accept files ending with the extension @file{.@var{ext}} (i.e.,
8299 @var{ext} does @emph{not} contain the dot). If any special compiler
8300 flags are needed for this, it stores them in the output variable
8301 @code{FCFLAGS_@var{ext}}. This extension and these flags are then used
8302 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8303 @code{AC_FC_PP_SRCEXT} is called another time).
8305 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8306 @file{.f90} extension in future tests, and it would set the
8307 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8308 to compile such files.
8310 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8311 compiler to preprocess and compile files with the extension
8312 @file{.@var{ext}}. When both @command{fpp} and @command{cpp} style
8313 preprocessing are provided, the former is preferred, as the latter may
8314 treat continuation lines, @code{//} tokens, and white space differently
8315 from what some Fortran dialects expect. Conversely, if you do not want
8316 files to be preprocessed, use only lower-case characters in the file
8317 name extension. Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8318 are stored in the @code{FCFLAGS_@var{ext}} variable.
8320 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8321 into @code{FCFLAGS}, for two reasons based on the limitations of some
8322 compilers. First, only one @code{FCFLAGS_@var{ext}} can be used at a
8323 time, so files with different extensions must be compiled separately.
8324 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8325 the source-code file name when compiling. So, continuing the example
8326 above, you might compile a @file{foo.f90} file in your makefile with the
8331 $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8334 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8335 files with the @var{ext} extension, it calls @var{action-if-success}
8336 (defaults to nothing). If it fails, and cannot find a way to make the
8337 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8338 (defaults to exiting with an error message).
8340 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8341 results in @code{ac_cv_fc_srcext_@var{ext}} and
8342 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8345 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8346 @dvar{action-if-failure, AC_MSG_FAILURE})
8347 @acindex{FC_PP_DEFINE}
8348 @caindex fc_pp_define
8350 Find a flag to specify defines for preprocessed Fortran. Not all
8351 Fortran compilers use @option{-D}. Substitute @code{FC_DEFINE} with
8352 the result and call @var{action-if-success} (defaults to nothing) if
8353 successful, and @var{action-if-failure} (defaults to failing with an
8354 error message) if not.
8356 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8357 preprocess a @file{conftest.F} file, but restores a previously used
8358 Fortran source file extension afterwards again.
8360 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8364 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8365 @dvar{action-if-failure, AC_MSG_FAILURE})
8366 @acindex{FC_FREEFORM}
8367 @caindex fc_freeform
8369 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8370 source code (as opposed to the older fixed-format style from Fortran
8371 77). If necessary, it may add some additional flags to @code{FCFLAGS}.
8373 This macro is most important if you are using the default @file{.f}
8374 extension, since many compilers interpret this extension as indicating
8375 fixed-format source unless an additional flag is supplied. If you
8376 specify a different extension with @code{AC_FC_SRCEXT}, such as
8377 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8378 modifying @code{FCFLAGS}. For extensions which the compiler does not
8379 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8380 the compiler assume Fortran 77 by default, however.
8382 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8383 calls @var{action-if-success} (defaults to nothing). If it fails, it
8384 calls @var{action-if-failure} (defaults to exiting with an error
8387 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8388 the @code{ac_cv_fc_freeform} variable.
8391 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8392 @dvar{action-if-failure, AC_MSG_FAILURE})
8393 @acindex{FC_FIXEDFORM}
8394 @caindex fc_fixedform
8396 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8397 fixed-format source code (as opposed to free-format style). If
8398 necessary, it may add some additional flags to @code{FCFLAGS}.
8400 This macro is needed for some compilers alias names like @command{xlf95}
8401 which assume free-form source code by default, and in case you want to
8402 use fixed-form source with an extension like @file{.f90} which many
8403 compilers interpret as free-form by default. If you specify a different
8404 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8405 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8408 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8409 calls @var{action-if-success} (defaults to nothing). If it fails, it
8410 calls @var{action-if-failure} (defaults to exiting with an error
8413 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8414 the @code{ac_cv_fc_fixedform} variable.
8417 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8418 @dvar{action-if-failure, AC_MSG_FAILURE})
8419 @acindex{FC_LINE_LENGTH}
8420 @caindex fc_line_length
8422 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8423 code lines. The @var{length} argument may be given as 80, 132, or
8424 unlimited, and defaults to 132. Note that line lengths above 250
8425 columns are not portable, and some compilers do not accept more than 132
8426 columns at least for fixed format source. If necessary, it may add some
8427 additional flags to @code{FCFLAGS}.
8429 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8430 calls @var{action-if-success} (defaults to nothing). If it fails, it
8431 calls @var{action-if-failure} (defaults to exiting with an error
8434 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8435 the @code{ac_cv_fc_line_length} variable.
8438 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8439 @dvar{action-if-failure, AC_MSG_FAILURE})
8440 @acindex{FC_CHECK_BOUNDS}
8441 @caindex fc_check_bounds
8443 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8444 in the Fortran compiler. If successful, the @var{action-if-success}
8445 is called and any needed flags are added to @code{FCFLAGS}. Otherwise,
8446 @var{action-if-failure} is called, which defaults to failing with an error
8447 message. The macro currently requires Fortran 90 or a newer dialect.
8449 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8453 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8454 @dvar{action-if-failure, AC_MSG_FAILURE})
8455 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8456 @dvar{action-if-failure, AC_MSG_FAILURE})
8457 @acindex{F77_IMPLICIT_NONE}
8458 @acindex{FC_IMPLICIT_NONE}
8459 @caindex f77_implicit_none
8460 @caindex fc_implicit_none
8462 Try to disallow implicit declarations in the Fortran compiler. If
8463 successful, @var{action-if-success} is called and any needed flags
8464 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively. Otherwise,
8465 @var{action-if-failure} is called, which defaults to failing with an error
8468 The result of these macros are cached in the
8469 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8470 variables, respectively.
8473 @defmac AC_FC_MODULE_EXTENSION
8474 @acindex{FC_MODULE_EXTENSION}
8475 @caindex fc_module_ext
8478 Find the Fortran 90 module file name extension. Most Fortran 90
8479 compilers store module information in files separate from the object
8480 files. The module files are usually named after the name of the module
8481 rather than the source file name, with characters possibly turned to
8482 upper case, plus an extension, often @file{.mod}.
8484 Not all compilers use module files at all, or by default. The Cray
8485 Fortran compiler requires @option{-e m} in order to store and search
8486 module information in @file{.mod} files rather than in object files.
8487 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8488 indicate how module information is stored.
8490 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8491 without the leading dot, and stores that in the @code{FC_MODEXT}
8492 variable. If the compiler does not produce module files, or the
8493 extension cannot be determined, @code{FC_MODEXT} is empty. Typically,
8494 the result of this macro may be used in cleanup @command{make} rules as
8499 -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8502 The extension, or @samp{unknown}, is cached in the
8503 @code{ac_cv_fc_module_ext} variable.
8506 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8507 @dvar{action-if-failure, AC_MSG_FAILURE})
8508 @acindex{FC_MODULE_FLAG}
8509 @caindex fc_module_flag
8513 Find the compiler flag to include Fortran 90 module information from
8514 another directory, and store that in the @code{FC_MODINC} variable.
8515 Call @var{action-if-success} (defaults to nothing) if successful, and
8516 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8517 to exiting with an error message) if not.
8519 Most Fortran 90 compilers provide a way to specify module directories.
8520 Some have separate flags for the directory to write module files to,
8521 and directories to search them in, whereas others only allow writing to
8522 the current directory or to the first directory specified in the include
8523 path. Further, with some compilers, the module search path and the
8524 preprocessor search path can only be modified with the same flag. Thus,
8525 for portability, write module files to the current directory only and
8526 list that as first directory in the search path.
8528 There may be no whitespace between @code{FC_MODINC} and the following
8529 directory name, but @code{FC_MODINC} may contain trailing white space.
8530 For example, if you use Automake and would like to search @file{../lib}
8531 for module files, you can use the following:
8534 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8537 Inside @command{configure} tests, you can use:
8540 if test -n "$FC_MODINC"; then
8541 FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8545 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8546 The substituted value of @code{FC_MODINC} may refer to the
8547 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8548 the significant trailing whitespace in a @file{Makefile}.
8551 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8552 @dvar{action-if-failure, AC_MSG_FAILURE})
8553 @acindex{FC_MODULE_OUTPUT_FLAG}
8554 @caindex fc_module_output_flag
8557 Find the compiler flag to write Fortran 90 module information to
8558 another directory, and store that in the @code{FC_MODOUT} variable.
8559 Call @var{action-if-success} (defaults to nothing) if successful, and
8560 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8561 to exiting with an error message) if not.
8563 Not all Fortran 90 compilers write module files, and of those that do,
8564 not all allow writing to a directory other than the current one, nor
8565 do all have separate flags for writing and reading; see the description
8566 of @code{AC_FC_MODULE_FLAG} above. If you need to be able to write to
8567 another directory, for maximum portability use @code{FC_MODOUT} before
8568 any @code{FC_MODINC} and include both the current directory and the one
8569 you write to in the search path:
8572 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8575 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8576 The substituted value of @code{FC_MODOUT} may refer to the
8577 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8578 the significant trailing whitespace in a @file{Makefile}.
8581 @defmac AC_F77_CRAY_POINTERS (@ovar{action-if-success}, @
8582 @dvar{action-if-failure, AC_MSG_FAILURE})
8583 @defmacx AC_FC_CRAY_POINTERS (@ovar{action-if-success}, @
8584 @dvar{action-if-failure, AC_MSG_FAILURE})
8585 @acindex{F77_CRAY_POINTERS}
8586 @acindex{FC_CRAY_POINTERS}
8587 @caindex fc_cray_pointer
8589 Try to ensure that the Fortran compiler (@code{$F77} or @code{$FC})
8590 accepts Cray pointers. If successful, the @var{action-if-success} is
8591 called and any needed flags are added to @code{FFLAGS} or
8592 @code{FCFLAGS}. Otherwise, @var{action-if-failure} is called, which
8593 defaults to failing with an error message.
8595 Cray pointers are a non-standard extension supported by many Fortran
8596 compilers which allow an integer to be declared as C-like pointer to
8599 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8600 the @code{ac_cv_f77_cray_ptr} or @code{ac_cv_fc_cray_ptr} variable.
8605 @subsection Go Compiler Characteristics
8608 Autoconf provides basic support for the Go programming language when
8609 using the @code{gccgo} compiler (there is currently no support for the
8610 @code{6g} and @code{8g} compilers).
8612 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8613 Find the Go compiler to use. Check whether the environment variable
8614 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8617 Otherwise, if the macro is invoked without an argument, then search for
8618 a Go compiler named @code{gccgo}. If it is not found, then as a last
8619 resort set @code{GOC} to @code{gccgo}.
8621 This macro may be invoked with an optional first argument which, if
8622 specified, must be a blank-separated list of Go compilers to search for.
8624 If output variable @code{GOFLAGS} was not already set, set it to
8625 @option{-g -O2}. If your package does not like this default,
8626 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8630 @node System Services
8631 @section System Services
8633 The following macros check for operating system services or capabilities.
8639 @cindex X Window System
8640 Try to locate the X Window System include files and libraries. If the
8641 user gave the command line options @option{--x-includes=@var{dir}} and
8642 @option{--x-libraries=@var{dir}}, use those directories.
8644 If either or both were not given, get the missing values by running
8645 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8646 environment variable) on a trivial @file{Imakefile} and examining the
8647 makefile that it produces. Setting @code{XMKMF} to @samp{false}
8648 disables this method.
8650 If this method fails to find the X Window System, @command{configure}
8651 looks for the files in several directories where they often reside.
8652 If either method is successful, set the shell variables
8653 @code{x_includes} and @code{x_libraries} to their locations, unless they
8654 are in directories the compiler searches by default.
8656 If both methods fail, or the user gave the command line option
8657 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8658 otherwise set it to the empty string.
8661 @anchor{AC_PATH_XTRA}
8662 @defmac AC_PATH_XTRA
8666 @ovindex X_EXTRA_LIBS
8668 @cvindex X_DISPLAY_MISSING
8669 An enhanced version of @code{AC_PATH_X}. It adds the C compiler flags
8670 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8671 to @code{X_LIBS}. Define @code{X_DISPLAY_MISSING} if X is not
8674 This macro also checks for special libraries that some systems need in
8675 order to compile X programs. It adds any that the system needs to
8676 output variable @code{X_EXTRA_LIBS}. And it checks for special X11R6
8677 libraries that need to be linked with before @option{-lX11}, and adds
8678 any found to the output variable @code{X_PRE_LIBS}.
8680 @c This is an incomplete kludge. Make a real way to do it.
8681 @c If you need to check for other X functions or libraries yourself, then
8682 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8683 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8686 @anchor{AC_SYS_INTERPRETER}
8687 @defmac AC_SYS_INTERPRETER
8688 @acindex{SYS_INTERPRETER}
8689 Check whether the system supports starting scripts with a line of the
8690 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8691 After running this macro, shell code in @file{configure.ac} can check
8692 the shell variable @code{interpval}; it is set to @samp{yes}
8693 if the system supports @samp{#!}, @samp{no} if not.
8696 @anchor{AC_SYS_LARGEFILE}
8697 @defmac AC_SYS_LARGEFILE
8698 @acindex{SYS_LARGEFILE}
8699 @cvindex _FILE_OFFSET_BITS
8702 @cindex Large file support
8704 If the default @code{off_t} type is a 32-bit integer,
8705 and therefore cannot be used with files 2 GiB or larger,
8706 make a wider @code{off_t} available if the system supports it.
8707 Similarly, widen other types related to sizes of files and file systems
8708 if possible. These types may include @code{blkcnt_t}, @code{dev_t},
8709 @code{ino_t}, @code{fsblkcnt_t}, @code{fsfilcnt_t}, and @code{rlim_t}.
8711 Also, arrange for a @command{configure} option @code{--enable-year2038}
8712 to request widening the type @code{time_t} as needed to represent file
8713 wand other timestamps after mid-January 2038. This widening is possible
8714 only on 32-bit GNU/Linux x86 and ARM systems with glibc 2.34 or later.
8715 If year-2038 support is requested but @command{configure} fails to find a way
8716 to widen @code{time_t} and inspection of the system suggests that
8717 this feature is available somehow, @command{configure} will error out.
8718 If you want the default to be @code{--enable-year2038}, you can use
8719 @code{AC_SYS_YEAR2038} or @code{AC_SYS_YEAR2038_RECOMMENDED}
8720 instead of @code{AC_SYS_LARGEFILE}.
8721 In other words, older packages that have long used @code{AC_SYS_LARGEFILE}
8722 can have year-2038 support on 32-bit GNU/Linux x86 and ARM systems either by
8723 regenerating @file{configure} with current Autoconf and configuring with
8724 @option{--enable-year2038}, or by using @code{AC_SYS_YEAR2038} or
8725 @code{AC_SYS_YEAR2038_RECOMMENDED} and configuring without
8726 @option{--disable-year2038}.
8727 A future version of Autoconf might change the @code{AC_SYS_LARGEFILE}
8728 default to @code{--enable-year2038}; if and when that happens,
8729 @code{AC_SYS_LARGEFILE} and @code{AC_SYS_YEAR2038} will become equivalent.
8730 @xref{AC_SYS_YEAR2038}.
8732 Set the shell variable @code{ac_have_largefile} to @samp{yes} or
8733 @code{no} depending on whether a wide @code{off_t} is available,
8734 regardless of whether arrangements were necessary.
8735 Similarly, set the shell variable @code{ac_have_year2038} to @code{yes}
8736 or @code{no} depending on whether a wide-enough @code{time_t} is available.
8738 Define preprocessor macros if necessary to make types wider;
8739 for example, on GNU/Linux systems the macros @code{_FILE_OFFSET_BITS}
8740 and @code{_TIME_BITS} can be defined. Some of these macros work only if
8741 defined before the first system header is included;
8742 therefore, when using this macro in concert with
8743 @code{AC_CONFIG_HEADERS}, make sure that @file{config.h} is included
8744 before any system headers.
8746 Large-file support can be disabled by configuring with the
8747 @option{--disable-largefile} option, and year-2038 support can
8748 be enabled and disabled via the @option{--enable-year2038} and
8749 @option{--disable-year2038} options. These options have no effect on
8750 systems where types are wide enough by default.
8751 Large-file support is required for year-2038 support: if you configure
8752 with @option{--disable-largefile} on a platform with 32-bit
8753 @code{time_t}, then year-2038 support is not available.
8755 Disabling large-file or year-2038 support can have surprising effects,
8756 such as causing functions like @code{readdir} and @code{stat} to fail
8757 even on a small file because its inode number or timestamp is out of range.
8759 Regardless of whether you use this macro, portable programs should not
8760 assume that any of the types listed above fit into a @code{long int}.
8761 For example, it is not portable to print an arbitrary @code{off_t} or
8762 @code{time_t} value @code{X} with @code{printf ("%ld", (long int) X)}.
8764 The standard C library functions @code{fseek} and @code{ftell}
8765 do not use @code{off_t}. If you need to use either of these functions,
8766 you should use @code{AC_FUNC_FSEEKO} as well as @code{AC_SYS_LARGEFILE},
8767 and then use their POSIX replacements @code{fseeko} and @code{ftello}.
8768 @xref{AC_FUNC_FSEEKO}.
8770 When using @code{AC_SYS_LARGEFILE} in different packages that are linked
8771 together and that have interfaces that depend on the width of @code{off_t},
8772 @code{time_t} or related types, the simplest thing is to configure all
8773 components the same way. For example, if an application uses
8774 @code{AC_SYS_LARGEFILE} and is configured with
8775 @option{--enable-year2038}, libraries it links to with an @code{off_t}-
8776 or @code{time_t}-dependent interface should be configured equivalently.
8777 Alternatively, you can modify libraries to support both 32- and 64-bit
8778 interfaces though this is more work and few libraries other than the C
8779 library itself are modified in this way.
8781 Applications and libraries should be configured compatibly.
8782 If @code{off_t}, @code{time_t} or related types appear in a library's
8783 public interface, enabling or disabling the library's large-file or
8784 year-2038 support may break binary compatibility with applications or
8785 with other libraries. Similarly, if an application links to a such a
8786 library, enabling or disabling the application's large-file support may
8787 break binary compatibility with that library.
8790 @anchor{AC_SYS_LONG_FILE_NAMES}
8791 @defmac AC_SYS_LONG_FILE_NAMES
8792 @acindex{SYS_LONG_FILE_NAMES}
8793 @cvindex HAVE_LONG_FILE_NAMES
8794 If the system supports file names longer than 14 characters, define
8795 @code{HAVE_LONG_FILE_NAMES}.
8798 @defmac AC_SYS_POSIX_TERMIOS
8799 @acindex{SYS_POSIX_TERMIOS}
8800 @cindex POSIX termios headers
8801 @cindex termios POSIX headers
8802 @caindex sys_posix_termios
8803 Check to see if the POSIX termios headers and functions are available on the
8804 system. If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8805 @samp{yes}. If not, set the variable to @samp{no}.
8808 @anchor{AC_SYS_YEAR2038}
8809 @defmac AC_SYS_YEAR2038
8810 @acindex{SYS_YEAR2038}
8812 This is like @code{AC_SYS_LARGEFILE} except it defaults to enabling
8813 instead of disabling year-2038 support. Year-2038 support for
8814 applications and libraries should be configured compatibly.
8815 @xref{AC_SYS_LARGEFILE}.
8818 @defmac AC_SYS_YEAR2038_RECOMMENDED
8819 @acindex{SYS_YEAR2038_RECOMMENDED}
8820 This macro has the same effect as @code{AC_SYS_YEAR2038},
8821 but also declares that the program being configured
8822 should support timestamps after mid-January 2038.
8823 If a large @code{time_t} is unavailable, @command{configure} will error
8824 out unless the @option{--disable-year2038} option is specified.
8826 Year-2038 support for applications and libraries should be configured
8827 compatibly. @xref{AC_SYS_YEAR2038}.
8830 @node C and POSIX Variants
8831 @section C and POSIX Variants
8833 The following macro makes it possible to use C language and library
8834 extensions defined by the C standards committee, features of POSIX that
8835 are extensions to C, and platform extensions not defined by POSIX.
8837 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8838 @defmac AC_USE_SYSTEM_EXTENSIONS
8839 @acindex{USE_SYSTEM_EXTENSIONS}
8840 If possible, enable extensions to C or POSIX on hosts that normally
8841 disable the extensions, typically due to standards-conformance namespace
8842 issues. This should be called before any macros that run the C
8843 compiler. Also, when using this macro in concert with
8844 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8845 before any system header.
8847 Define the following preprocessor macros unconditionally:
8851 @cvindex _ALL_SOURCE
8852 Enable extensions on AIX and z/OS.
8853 @item _DARWIN_C_SOURCE
8854 @cvindex _DARWIN_C_SOURCE
8855 Enable extensions on macOS.
8857 @cvindex _GNU_SOURCE
8858 Enable extensions on GNU systems.
8859 @item _NETBSD_SOURCE
8860 @cvindex _NETBSD_SOURCE
8861 Enable general extensions on NetBSD.
8862 Enable NetBSD compatibility extensions on Minix.
8863 @item _OPENBSD_SOURCE
8864 @cvindex _OPENBSD_SOURCE
8865 Enable OpenBSD compatibility extensions on NetBSD.
8866 Oddly enough, this does nothing on OpenBSD.
8867 @item _POSIX_PTHREAD_SEMANTICS
8868 @cvindex _POSIX_PTHREAD_SEMANTICS
8869 Enable POSIX-compatible threading on Solaris.
8870 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8871 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8872 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8873 @item __STDC_WANT_IEC_60559_BFP_EXT__
8874 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8875 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8876 @item __STDC_WANT_IEC_60559_DFP_EXT__
8877 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8878 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8879 @item __STDC_WANT_IEC_60559_EXT__
8880 @cvindex __STDC_WANT_IEC_60559_EXT__
8881 Enable extensions specified by C23 Annex F.
8882 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8883 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8884 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8885 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8886 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8887 Enable extensions specified by C23 Annex H and by ISO/IEC TS 18661-3:2015.
8888 @item __STDC_WANT_LIB_EXT2__
8889 @cvindex __STDC_WANT_LIB_EXT2__
8890 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8891 @item __STDC_WANT_MATH_SPEC_FUNCS__
8892 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8893 Enable extensions specified by ISO/IEC 24747:2009.
8894 @item _TANDEM_SOURCE
8895 @cvindex _TANDEM_SOURCE
8896 Enable extensions on HP NonStop systems.
8899 The following preprocessor macros are defined only when necessary;
8900 they enable access to extensions on some operating systems but
8901 @emph{disable} extensions on other operating systems.
8904 @item __EXTENSIONS__
8905 @cvindex __EXTENSIONS__
8906 Enable general extensions on Solaris. This macro is defined only if
8907 the headers included by @code{AC_INCLUDES_DEFAULT}
8908 (@pxref{Default Includes}) work correctly with it defined.
8911 @itemx _POSIX_SOURCE
8912 @itemx _POSIX_1_SOURCE
8914 @cvindex _POSIX_SOURCE
8915 @cvindex _POSIX_1_SOURCE
8916 Defined only on MINIX. @code{_POSIX_SOURCE} and @code{_POSIX_1_SOURCE}
8917 are needed to enable a number of POSIX features on this OS.
8918 @code{_MINIX} does not affect the system headers' behavior;
8919 future versions of Autoconf may stop defining it.
8920 Programs that need to recognize Minix should use @code{AC_CANONICAL_HOST}.
8923 @cvindex _XOPEN_SOURCE
8924 Defined (with value 500) only if needed to make @file{wchar.h} declare
8925 @code{mbstate_t}. This is known to be necessary on some versions of HP-UX.
8928 @cvindex __STDC_WANT_DEC_FP__
8929 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
8930 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
8932 @cvindex __STDC_WANT_LIB_EXT1__
8933 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
8934 as the C standard's Annex K is problematic. See: O'Donell C, Sebor M.
8935 @uref{https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8936 Experience With Annex K---Bounds Checking Interfaces}.
8938 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
8943 @node Erlang Libraries
8944 @section Erlang Libraries
8945 @cindex Erlang, Library, checking
8947 The following macros check for an installation of Erlang/OTP, and for the
8948 presence of certain Erlang libraries. All those macros require the
8949 configuration of an Erlang interpreter and an Erlang compiler
8950 (@pxref{Erlang Compiler and Interpreter}).
8952 @defmac AC_ERLANG_SUBST_ERTS_VER
8953 @acindex{ERLANG_SUBST_ERTS_VER}
8954 @ovindex ERLANG_ERTS_VER
8955 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8956 Erlang runtime system (as returned by Erlang's
8957 @code{erlang:system_info(version)} function). The result of this test
8958 is cached if caching is enabled when running @command{configure}. The
8959 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8960 for features of specific ERTS versions, but to be used for substituting
8961 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8962 files), as shown below.
8965 @defmac AC_ERLANG_SUBST_ROOT_DIR
8966 @acindex{ERLANG_SUBST_ROOT_DIR}
8967 @ovindex ERLANG_ROOT_DIR
8968 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8969 directory in which Erlang/OTP is installed (as returned by Erlang's
8970 @code{code:root_dir/0} function). The result of this test is cached if
8971 caching is enabled when running @command{configure}.
8974 @defmac AC_ERLANG_SUBST_LIB_DIR
8975 @acindex{ERLANG_SUBST_LIB_DIR}
8976 @ovindex ERLANG_LIB_DIR
8977 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8978 directory of Erlang/OTP (as returned by Erlang's
8979 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8980 Erlang/OTP library. The result of this test is cached if caching is enabled
8981 when running @command{configure}.
8984 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8985 @ovar{action-if-not-found})
8986 @acindex{ERLANG_CHECK_LIB}
8987 @ovindex ERLANG_LIB_DIR_@var{library}
8988 @ovindex ERLANG_LIB_VER_@var{library}
8989 Test whether the Erlang/OTP library @var{library} is installed by
8990 calling Erlang's @code{code:lib_dir/1} function. The result of this
8991 test is cached if caching is enabled when running @command{configure}.
8992 @var{action-if-found} is a list of shell commands to run if the library
8993 is installed; @var{action-if-not-found} is a list of shell commands to
8994 run if it is not. Additionally, if the library is installed, the output
8995 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8996 library installation directory, and the output variable
8997 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8998 part of the subdirectory name, if it is in the standard form
8999 (@code{@var{library}-@var{version}}). If the directory name does not
9000 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
9001 empty string. If the library is not installed,
9002 @samp{ERLANG_LIB_DIR_@var{library}} and
9003 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}. For
9004 example, to check if library @code{stdlib} is installed:
9007 AC_ERLANG_CHECK_LIB([stdlib],
9008 [AS_ECHO(["stdlib version \"$ERLANG_LIB_VER_stdlib\""])
9009 AS_ECHO(["is installed in \"$ERLANG_LIB_DIR_stdlib\""])],
9010 [AC_MSG_ERROR([stdlib was not found!])])
9013 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
9014 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
9015 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
9016 testing for features of specific versions of libraries or of the Erlang
9017 runtime system. Those variables are intended to be substituted in
9018 Erlang release resource files (@code{.rel} files). For instance, to
9019 generate a @file{example.rel} file for an application depending on the
9020 @code{stdlib} library, @file{configure.ac} could contain:
9023 AC_ERLANG_SUBST_ERTS_VER
9024 AC_ERLANG_CHECK_LIB([stdlib],
9026 [AC_MSG_ERROR([stdlib was not found!])])
9027 AC_CONFIG_FILES([example.rel])
9031 The @file{example.rel.in} file used to generate @file{example.rel}
9036 @{"@@PACKAGE@@", "@@VERSION@@"@},
9037 @{erts, "@@ERLANG_ERTS_VER@@"@},
9038 [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
9039 @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
9043 In addition to the above macros, which test installed Erlang libraries, the
9044 following macros determine the paths to the directories into which newly built
9045 Erlang libraries are to be installed:
9047 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
9048 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
9049 @ovindex ERLANG_INSTALL_LIB_DIR
9051 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
9052 which every built Erlang library should be installed in a separate
9054 If this variable is not set in the environment when @command{configure} runs,
9055 its default value is @code{$@{libdir@}/erlang/lib}.
9058 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
9059 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
9060 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
9062 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
9063 directory into which the built Erlang library @var{library} version
9064 @var{version} should be installed. If this variable is not set in the
9065 environment when @command{configure} runs, its default value is
9066 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
9067 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
9068 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
9075 @c ========================================================= Writing Tests
9078 @chapter Writing Tests
9080 If the existing feature tests don't do something you need, you have to
9081 write new ones. These macros are the building blocks. They provide
9082 ways for other macros to check whether various kinds of features are
9083 available and report the results.
9085 This chapter contains some suggestions and some of the reasons why the
9086 existing tests are written the way they are. You can also learn a lot
9087 about how to write Autoconf tests by looking at the existing ones. If
9088 something goes wrong in one or more of the Autoconf tests, this
9089 information can help you understand the assumptions behind them, which
9090 might help you figure out how to best solve the problem.
9092 These macros check the output of the compiler system of the current
9093 language (@pxref{Language Choice}). They do not cache the results of
9094 their tests for future use (@pxref{Caching Results}), because they don't
9095 know enough about the information they are checking for to generate a
9096 cache variable name. They also do not print any messages, for the same
9097 reason. The checks for particular kinds of features call these macros
9098 and do cache their results and print messages about what they're
9101 When you write a feature test that could be applicable to more than one
9102 software package, the best thing to do is encapsulate it in a new macro.
9103 @xref{Writing Autoconf Macros}, for how to do that.
9106 * Language Choice:: Selecting which language to use for testing
9107 * Writing Test Programs:: Forging source files for compilers
9108 * Running the Preprocessor:: Detecting preprocessor symbols
9109 * Running the Compiler:: Detecting language or header features
9110 * Running the Linker:: Detecting library features
9111 * Runtime:: Testing for runtime features
9112 * Multiple Cases:: Tests for several possible values
9115 @node Language Choice
9116 @section Language Choice
9119 Autoconf-generated @command{configure} scripts check for the C compiler and
9120 its features by default. Packages that use other programming languages
9121 (maybe more than one, e.g., C and C++) need to test features of the
9122 compilers for the respective languages. The following macros determine
9123 which programming language is used in the subsequent tests in
9124 @file{configure.ac}.
9127 @defmac AC_LANG (@var{language})
9129 Do compilation tests using the compiler, preprocessor, and file
9130 extensions for the specified @var{language}.
9132 Supported languages are:
9136 Do compilation tests using @code{CC} and @code{CPP} and use extension
9137 @file{.c} for test programs. Use compilation flags: @code{CPPFLAGS} with
9138 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
9141 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
9142 extension @file{.C} for test programs. Use compilation flags:
9143 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
9144 @code{CXXFLAGS} with @code{CXX}.
9147 Do compilation tests using @code{F77} and use extension @file{.f} for
9148 test programs. Use compilation flags: @code{FFLAGS}.
9151 Do compilation tests using @code{FC} and use extension @file{.f} (or
9152 whatever has been set by @code{AC_FC_SRCEXT}) for test programs. Use
9153 compilation flags: @code{FCFLAGS}.
9159 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
9160 @file{.erl} for test Erlang modules. Use compilation flags: @code{ERLCFLAGS}.
9163 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
9164 extension @file{.m} for test programs. Use compilation flags:
9165 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
9166 @code{OBJCFLAGS} with @code{OBJC}.
9169 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
9170 extension @file{.mm} for test programs. Use compilation flags:
9171 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
9172 @code{OBJCXXFLAGS} with @code{OBJCXX}.
9175 Do compilation tests using @code{GOC} and use extension @file{.go} for
9176 test programs. Use compilation flags @code{GOFLAGS}.
9180 @anchor{AC_LANG_PUSH}
9181 @defmac AC_LANG_PUSH (@var{language})
9183 Remember the current language (as set by @code{AC_LANG}) on a stack, and
9184 then select the @var{language}. Use this macro and @code{AC_LANG_POP}
9185 in macros that need to temporarily switch to a particular language.
9188 @defmac AC_LANG_POP (@ovar{language})
9190 Select the language that is saved on the top of the stack, as set by
9191 @code{AC_LANG_PUSH}, and remove it from the stack.
9193 If given, @var{language} specifies the language we just @emph{quit}. It
9194 is a good idea to specify it when it's known (which should be the
9195 case@dots{}), since Autoconf detects inconsistencies.
9198 AC_LANG_PUSH([Fortran 77])
9199 # Perform some tests on Fortran 77.
9201 AC_LANG_POP([Fortran 77])
9205 @defmac AC_LANG_ASSERT (@var{language})
9206 @acindex{LANG_ASSERT}
9207 Check statically that the current language is @var{language}.
9208 You should use this in your language specific macros
9209 to avoid that they be called with an inappropriate language.
9211 This macro runs only at @command{autoconf} time, and incurs no cost at
9212 @command{configure} time. Sadly enough and because Autoconf is a two
9213 layer language @footnote{Because M4 is not aware of Sh code,
9214 especially conditionals, some optimizations that look nice statically
9215 may produce incorrect results at runtime.}, the macros
9216 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
9217 therefore as much as possible you ought to avoid using them to wrap
9218 your code, rather, require from the user to run the macro with a
9219 correct current language, and check it with @code{AC_LANG_ASSERT}.
9220 And anyway, that may help the user understand she is running a Fortran
9221 macro while expecting a result about her Fortran 77 compiler@enddots{}
9225 @defmac AC_REQUIRE_CPP
9226 @acindex{REQUIRE_CPP}
9227 Ensure that whichever preprocessor would currently be used for tests has
9228 been found. Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9229 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9230 depending on which language is current.
9234 @node Writing Test Programs
9235 @section Writing Test Programs
9237 Autoconf tests follow a common scheme: feed some program with some
9238 input, and most of the time, feed a compiler with some source file.
9239 This section is dedicated to these source samples.
9242 * Guidelines:: General rules for writing test programs
9243 * Test Functions:: Avoiding pitfalls in test programs
9244 * Generating Sources:: Source program boilerplate
9248 @subsection Guidelines for Test Programs
9250 The most important rule to follow when writing testing samples is:
9252 @center @emph{Look for realism.}
9254 This motto means that testing samples must be written with the same
9255 strictness as real programs are written. In particular, you should
9256 avoid ``shortcuts'' and simplifications.
9258 Don't just play with the preprocessor if you want to prepare a
9259 compilation. For instance, using @command{cpp} to check whether a header is
9260 functional might let your @command{configure} accept a header which
9261 causes some @emph{compiler} error. Do not hesitate to check a header with
9262 other headers included before, especially required headers.
9264 Make sure the symbols you use are properly defined, i.e., refrain from
9265 simply declaring a function yourself instead of including the proper
9268 Test programs should not write to standard output. They
9269 should exit with status 0 if the test succeeds, and with status 1
9270 otherwise, so that success
9271 can be distinguished easily from a core dump or other failure;
9272 segmentation violations and other failures produce a nonzero exit
9273 status. Unless you arrange for @code{exit} to be declared, test
9274 programs should @code{return}, not @code{exit}, from @code{main},
9275 because on many systems @code{exit} is not declared by default.
9277 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9278 preprocessor macros defined by tests that have already run. For
9279 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9280 @file{configure.ac} you can have a test program that includes
9281 @file{stdbool.h} conditionally:
9285 #ifdef HAVE_STDBOOL_H
9286 # include <stdbool.h>
9291 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9292 work with any standard C compiler. Some developers prefer @code{#if}
9293 because it is easier to read, while others prefer @code{#ifdef} because
9294 it avoids diagnostics with picky compilers like GCC with the
9295 @option{-Wundef} option.
9297 If a test program needs to use or create a data file, give it a name
9298 that starts with @file{conftest}, such as @file{conftest.data}. The
9299 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9300 after running test programs and if the script is interrupted.
9302 @node Test Functions
9303 @subsection Test Functions
9305 Functions in test code should use function prototypes, introduced in C89
9306 and required in C23.
9308 Functions that test programs declare should also be conditionalized for
9309 C++, which requires @samp{extern "C"} prototypes. Make sure to not
9310 include any header files containing clashing prototypes.
9316 void *valloc (size_t);
9319 If a test program calls a function with invalid parameters (just to see
9320 whether it exists), organize the program to ensure that it never invokes
9321 that function. You can do this by calling it in another function that is
9322 never invoked. You can't do it by putting it after a call to
9323 @code{exit}, because GCC version 2 knows that @code{exit}
9325 and optimizes out any code that follows it in the same block.
9327 If you include any header files, be sure to call the functions
9328 relevant to them with the correct number of arguments, even if they are
9329 just 0, to avoid compilation errors due to prototypes. GCC
9331 has internal prototypes for several functions that it automatically
9332 inlines; for example, @code{memcpy}. To avoid errors when checking for
9333 them, either pass them the correct number of arguments or redeclare them
9334 with a different return type (such as @code{char}).
9337 @node Generating Sources
9338 @subsection Generating Sources
9340 Autoconf provides a set of macros that can be used to generate test
9341 source files. They are written to be language generic, i.e., they
9342 actually depend on the current language (@pxref{Language Choice}) to
9343 ``format'' the output properly.
9346 @defmac AC_LANG_CONFTEST (@var{source})
9347 @acindex{LANG_CONFTEST}
9348 Save the @var{source} text in the current test source file:
9349 @file{conftest.@var{extension}} where the @var{extension} depends on the
9350 current language. As of Autoconf 2.63b, the source file also contains
9351 the results of all of the @code{AC_DEFINE} performed so far.
9353 Note that the @var{source} is evaluated exactly once, like regular
9354 Autoconf macro arguments, and therefore (i) you may pass a macro
9355 invocation, (ii) if not, be sure to double quote if needed.
9357 The @var{source} text is expanded as an unquoted here-document, so
9358 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9359 @xref{Here-Documents}.
9361 This macro issues a warning during @command{autoconf} processing if
9362 @var{source} does not include an expansion of the macro
9363 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9364 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9366 This macro is seldom called directly, but is used under the hood by more
9367 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9370 @defmac AC_LANG_DEFINES_PROVIDED
9371 @acindex{LANG_DEFINES_PROVIDED}
9372 This macro is called as a witness that the file
9373 @file{conftest.@var{extension}} appropriate for the current language is
9374 complete, including all previously determined results from
9375 @code{AC_DEFINE}. This macro is seldom called directly, but exists if
9376 you have a compelling reason to write a conftest file without using
9377 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9378 @code{AC_LANG_CONFTEST}.
9381 @defmac AC_LANG_SOURCE (@var{source})
9382 @acindex{LANG_SOURCE}
9383 Expands into the @var{source}, with the definition of
9384 all the @code{AC_DEFINE} performed so far. This macro includes an
9385 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9387 In many cases, you may find it more convenient to use the wrapper
9388 @code{AC_LANG_PROGRAM}.
9391 For instance, executing (observe the double quotation!):
9394 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9395 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9396 [https://www.example.org/])
9397 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9398 [Greetings string.])
9401 [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9402 gcc -E -dD conftest.c
9406 on a system with @command{gcc} installed, results in:
9409 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9411 @asis{#} 1 "conftest.c"
9413 #define PACKAGE_NAME "Hello"
9414 #define PACKAGE_TARNAME "hello"
9415 #define PACKAGE_VERSION "1.0"
9416 #define PACKAGE_STRING "Hello 1.0"
9417 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9418 #define PACKAGE_URL "https://www.example.org/"
9419 #define HELLO_WORLD "Hello, World\n"
9421 const char hw[] = "Hello, World\n";
9424 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9425 definitions are not automatically translated into constants in the
9426 source code by this macro.
9428 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9429 @acindex{LANG_PROGRAM}
9430 Expands into a source file which consists of the @var{prologue}, and
9431 then @var{body} as body of the main function (e.g., @code{main} in
9432 C). Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9439 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9440 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9441 [https://www.example.org/])
9442 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9443 [Greetings string.])
9445 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9446 [[fputs (hw, stdout);]])])
9447 gcc -E -dD conftest.c
9451 on a system with @command{gcc} installed, results in:
9454 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9456 @asis{#} 1 "conftest.c"
9458 #define PACKAGE_NAME "Hello"
9459 #define PACKAGE_TARNAME "hello"
9460 #define PACKAGE_VERSION "1.0"
9461 #define PACKAGE_STRING "Hello 1.0"
9462 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9463 #define PACKAGE_URL "https://www.example.org/"
9464 #define HELLO_WORLD "Hello, World\n"
9466 const char hw[] = "Hello, World\n";
9476 In Erlang tests, the created source file is that of an Erlang module called
9477 @code{conftest} (@file{conftest.erl}). This module defines and exports
9479 one @code{start/0} function, which is called to perform the test. The
9480 @var{prologue} is optional code that is inserted between the module header and
9481 the @code{start/0} function definition. @var{body} is the body of the
9482 @code{start/0} function without the final period (@pxref{Runtime}, about
9483 constraints on this function's behavior).
9488 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9491 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9492 [[io:format("~s~n", [?HELLO_WORLD])]])])
9502 -define(HELLO_WORLD, "Hello, world!").
9504 io:format("~s~n", [?HELLO_WORLD])
9508 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9510 Expands into a source file which consists of the @var{prologue}, and
9511 then a call to the @var{function} as body of the main function (e.g.,
9512 @code{main} in C). Since it uses @code{AC_LANG_PROGRAM}, the feature
9513 of the latter are available.
9515 This function will probably be replaced in the future by a version
9516 which would enable specifying the arguments. The use of this macro is
9517 not encouraged, as it violates strongly the typing system.
9519 This macro cannot be used for Erlang tests.
9522 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9523 @acindex{LANG_FUNC_LINK_TRY}
9524 Expands into a source file which uses the @var{function} in the body of
9525 the main function (e.g., @code{main} in C). Since it uses
9526 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9528 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9529 It is considered to be severely broken, and in the future will be
9530 removed in favor of actual function calls (with properly typed
9533 This macro cannot be used for Erlang tests.
9536 @node Running the Preprocessor
9537 @section Running the Preprocessor
9539 Sometimes one might need to run the preprocessor on some source file.
9540 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9541 your project, not merely run the preprocessor on it; therefore you
9542 certainly want to run the compiler, not the preprocessor. Resist the
9543 temptation of following the easiest path.
9545 Nevertheless, if you need to run the preprocessor, then use
9546 @code{AC_PREPROC_IFELSE}.
9548 The macros described in this section cannot be used for tests in Erlang,
9549 Fortran, or Go, since those languages require no preprocessor.
9551 @anchor{AC_PREPROC_IFELSE}
9552 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9553 @ovar{action-if-false})
9554 @acindex{PREPROC_IFELSE}
9555 Run the preprocessor of the current language (@pxref{Language Choice})
9556 on the @var{input}, run the shell commands @var{action-if-true} on
9557 success, @var{action-if-false} otherwise.
9559 If @var{input} is nonempty use the equivalent of
9560 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9561 file; otherwise reuse the already-existing test source file.
9562 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9563 The @var{input} text is expanded as an unquoted here-document, so
9564 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9565 @xref{Here-Documents}.
9567 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9568 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9571 It is customary to report unexpected failures with
9572 @code{AC_MSG_FAILURE}. If needed, @var{action-if-true} can further access
9573 the preprocessed output in the file @file{conftest.i}.
9579 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9580 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9581 [Greetings string.])
9583 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9584 [[fputs (hw, stdout);]])],
9585 [AC_MSG_RESULT([OK])],
9586 [AC_MSG_FAILURE([unexpected preprocessor failure])])
9593 checking for gcc... gcc
9594 checking whether the C compiler works... yes
9595 checking for C compiler default output file name... a.out
9596 checking for suffix of executables...
9597 checking whether we are cross compiling... no
9598 checking for suffix of object files... o
9599 checking whether the compiler supports GNU C... yes
9600 checking whether gcc accepts -g... yes
9601 checking for gcc option to enable C23 features... -std=gnu23
9602 checking how to run the C preprocessor... gcc -std=gnu23 -E
9608 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9609 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9610 it impossible to use it to elaborate sources. You are encouraged to
9611 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9612 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9613 to run the @emph{preprocessor} and not the compiler?
9615 @anchor{AC_EGREP_HEADER}
9616 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9617 @var{action-if-found}, @ovar{action-if-not-found})
9618 @acindex{EGREP_HEADER}
9619 @var{pattern}, after being expanded as if in a double-quoted shell string,
9620 is an extended regular expression.
9621 If the output of running the preprocessor on the system header file
9622 @var{header-file} contains a line matching
9623 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9624 execute @var{action-if-not-found}.
9626 See below for some problems involving this macro.
9629 @anchor{AC_EGREP_CPP}
9630 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9631 @ovar{action-if-found}, @ovar{action-if-not-found})
9633 @var{pattern}, after being expanded as if in a double-quoted shell string,
9634 is an extended regular expression.
9635 @var{program} is the text of a C or C++ program, which is expanded as an
9636 unquoted here-document (@pxref{Here-Documents}). If the
9637 output of running the preprocessor on @var{program} contains a line
9638 matching @var{pattern}, execute shell commands
9639 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9641 See below for some problems involving this macro.
9644 @code{AC_EGREP_CPP} and @code{AC_EGREP_HEADER} should be used with care,
9645 as preprocessors can insert line breaks between output tokens. For
9646 example, the preprocessor might transform this:
9651 Version MAJOR . MINOR
9665 Because preprocessors are allowed to insert white space, change escapes
9666 in string constants, insert backlash-newline pairs, or do any of a number
9667 of things that do not change the meaning of the preprocessed program, it
9668 is better to rely on @code{AC_PREPROC_IFELSE} than to resort to
9669 @code{AC_EGREP_CPP} or @code{AC_EGREP_HEADER}.
9671 For more information about what can appear in portable extended regular
9672 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
9674 @node Running the Compiler
9675 @section Running the Compiler
9677 To check for a syntax feature of the current language's (@pxref{Language
9678 Choice}) compiler, such as whether it recognizes a certain keyword, or
9679 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9680 to compile a small program that uses that feature.
9682 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9683 @ovar{action-if-false})
9684 @acindex{COMPILE_IFELSE}
9685 Run the compiler and compilation flags of the current language
9686 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9687 @var{action-if-true} on success, @var{action-if-false} otherwise.
9689 If @var{input} is nonempty use the equivalent of
9690 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9691 file; otherwise reuse the already-existing test source file.
9692 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9693 The @var{input} text is expanded as an unquoted here-document, so
9694 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9695 @xref{Here-Documents}.
9697 It is customary to report unexpected failures with
9698 @code{AC_MSG_FAILURE}. This macro does not try to link; use
9699 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9700 Linker}). If needed, @var{action-if-true} can further access the
9701 just-compiled object file @file{conftest.$OBJEXT}.
9703 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9704 current language, which means that if the compiler has not yet been
9705 determined, the compiler determination will be made prior to the body of
9706 the outermost @code{AC_DEFUN} macro that triggered this macro to
9707 expand (@pxref{Expanded Before Required}).
9711 For tests in Erlang, the @var{input} must be the source code of a module named
9712 @code{conftest}. @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9713 file that can be interpreted by the Erlang virtual machine (@code{ERL}). It is
9714 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9715 to ensure that the Erlang module has the right name.
9717 @node Running the Linker
9718 @section Running the Linker
9720 To check for a library, a function, or a global variable, Autoconf
9721 @command{configure} scripts try to compile and link a small program that
9722 uses it. This is unlike Metaconfig, which by default uses @code{nm} or
9723 @code{ar} on the C library to try to figure out which functions are
9724 available. Trying to link with the function is usually a more reliable
9725 approach because it avoids dealing with the variations in the options
9726 and output formats of @code{nm} and @code{ar} and in the location of the
9727 standard libraries. It also allows configuring for cross-compilation or
9728 checking a function's runtime behavior if needed. On the other hand,
9729 it can be slower than scanning the libraries once, but accuracy is more
9730 important than speed.
9732 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9733 functions and global variables. It is also used by @code{AC_CHECK_LIB}
9734 to check for libraries (@pxref{Libraries}), by adding the library being
9735 checked for to @code{LIBS} temporarily and trying to link a small
9738 @anchor{AC_LINK_IFELSE}
9739 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9740 @ovar{action-if-false})
9741 @acindex{LINK_IFELSE}
9742 Run the compiler (and compilation flags) and the linker of the current
9743 language (@pxref{Language Choice}) on the @var{input}, run the shell
9744 commands @var{action-if-true} on success, @var{action-if-false}
9745 otherwise. If needed, @var{action-if-true} can further access the
9746 just-linked program file @file{conftest$EXEEXT}.
9748 If @var{input} is nonempty use the equivalent of
9749 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9750 file; otherwise reuse the already-existing test source file.
9751 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9752 The @var{input} text is expanded as an unquoted here-document, so
9753 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9754 @xref{Here-Documents}.
9756 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9757 current compilation flags.
9759 It is customary to report unexpected failures with
9760 @code{AC_MSG_FAILURE}. This macro does not try to execute the program;
9761 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9764 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9765 programs are interpreted and do not require linking.
9770 @section Checking Runtime Behavior
9772 Sometimes you need to find out how a system performs at runtime, such
9773 as whether a given function has a certain capability or bug. If you
9774 can, make such checks when your program runs instead of when it is
9775 configured. You can check for things like the machine's endianness when
9776 your program initializes itself.
9778 If you really need to test for a runtime behavior while configuring,
9779 you can write a test program to determine the result, and compile and
9780 run it using @code{AC_RUN_IFELSE}. Avoid running test programs if
9781 possible, because this prevents people from configuring your package for
9784 @anchor{AC_RUN_IFELSE}
9785 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9786 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9787 @acindex{RUN_IFELSE}
9788 Run the compiler (and compilation flags) and the linker of the current
9789 language (@pxref{Language Choice}) on the @var{input}, then execute the
9790 resulting program. If the program returns an exit
9791 status of 0 when executed, run shell commands @var{action-if-true}.
9792 Otherwise, run shell commands @var{action-if-false}.
9794 If @var{input} is nonempty use the equivalent of
9795 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9796 file; otherwise reuse the already-existing test source file.
9797 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9798 The @var{input} text is expanded as an unquoted here-document, so
9799 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9800 @xref{Here-Documents}.
9802 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9803 compilation flags of the current language (@pxref{Language Choice}).
9804 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9805 for further testing.
9807 In the @var{action-if-false} section, the failing exit status is
9808 available in the shell variable @samp{$?}. This exit status might be
9809 that of a failed compilation, or it might be that of a failed program
9812 If cross-compilation mode is enabled (this is the case if either the
9813 compiler being used does not produce executables that run on the system
9814 where @command{configure} is being run, or if the options @code{--build}
9815 and @code{--host} were both specified and their values are different),
9816 then the test program is
9817 not run. If the optional shell commands @var{action-if-cross-compiling}
9818 are given, those commands are run instead; typically these commands
9819 provide pessimistic defaults that allow cross-compilation to work even
9820 if the guess was wrong. If the fourth argument is empty or omitted, but
9821 cross-compilation is detected, then @command{configure} prints an error
9822 message and exits. If you want your package to be useful in a
9823 cross-compilation scenario, you @emph{should} provide a non-empty
9824 @var{action-if-cross-compiling} clause, as well as wrap the
9825 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9826 (@pxref{Caching Results}) which allows the user to override the
9827 pessimistic default if needed.
9829 It is customary to report unexpected failures with
9830 @code{AC_MSG_FAILURE}.
9833 @command{autoconf} prints a warning message when creating
9834 @command{configure} each time it encounters a call to
9835 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9836 given. If you are not concerned about users configuring your package
9837 for cross-compilation, you may ignore the warning. A few of the macros
9838 distributed with Autoconf produce this warning message; but if this is a
9839 problem for you, please report it as a bug, along with an appropriate
9840 pessimistic guess to use instead.
9842 To configure for cross-compiling you can also choose a value for those
9843 parameters based on the canonical system name (@pxref{Manual
9844 Configuration}). Alternatively, set up a test results cache file with
9845 the correct values for the host system (@pxref{Caching Results}).
9847 @ovindex cross_compiling
9848 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9849 in other macros, including a few of the ones that come with Autoconf,
9850 you can test whether the shell variable @code{cross_compiling} is set to
9851 @samp{yes}, and then use an alternate method to get the results instead
9852 of calling the macros.
9854 It is also permissible to temporarily assign to @code{cross_compiling}
9855 in order to force tests to behave as though they are in a
9856 cross-compilation environment, particularly since this provides a way to
9857 test your @var{action-if-cross-compiling} even when you are not using a
9861 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9862 # to use the slow link-only method
9863 save_cross_compiling=$cross_compiling
9865 AC_COMPUTE_INT([@dots{}])
9866 cross_compiling=$save_cross_compiling
9869 A C or C++ runtime test should be portable.
9870 @xref{Portable C and C++}.
9872 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9873 function: the given status code is used to determine the success of the test
9874 (status is @code{0}) or its failure (status is different than @code{0}), as
9875 explained above. It must be noted that data output through the standard output
9876 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9877 Therefore, if a test must output configuration information, it is recommended
9878 to create and to output data into the temporary file named @file{conftest.out},
9879 using the functions of module @code{file}. The @code{conftest.out} file is
9880 automatically deleted by the @code{AC_RUN_IFELSE} macro. For instance, a
9881 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9885 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9889 [AC_LANG_PROGRAM([], [dnl
9890 file:write_file("conftest.out", code:lib_dir()),
9892 [AS_ECHO(["code:lib_dir() returned: `cat conftest.out`"])],
9893 [AC_MSG_FAILURE([test Erlang program execution failed])])
9897 @node Multiple Cases
9898 @section Multiple Cases
9900 Some operations are accomplished in several possible ways, depending on
9901 the OS variant. Checking for them essentially requires a ``case
9902 statement''. Autoconf does not directly provide one; however, it is
9903 easy to simulate by using a shell variable to keep track of whether a
9904 way to perform the operation has been found yet.
9906 Here is an example that uses the shell variable @code{fstype} to keep
9907 track of whether the remaining cases need to be checked. Note that
9908 since the value of @code{fstype} is under our control, we don't have to
9909 use the longer @samp{test "x$fstype" = xno}.
9913 AC_MSG_CHECKING([how to get file system type])
9915 # The order of these tests is important.
9916 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9917 #include <sys/fstyp.h>
9919 [AC_DEFINE([FSTYPE_STATVFS], [1],
9920 [Define if statvfs exists.])
9922 AS_IF([test $fstype = no],
9923 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9924 #include <sys/fstyp.h>
9926 [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9927 [Define if USG statfs.])
9929 AS_IF([test $fstype = no],
9930 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9931 #include <sys/vmount.h>
9933 [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9934 [Define if AIX statfs.])
9936 # (more cases omitted here)
9937 AC_MSG_RESULT([$fstype])
9941 @c ====================================================== Results of Tests.
9944 @chapter Results of Tests
9946 Once @command{configure} has determined whether a feature exists, what can
9947 it do to record that information? There are four sorts of things it can
9948 do: define a C preprocessor symbol, set a variable in the output files,
9949 save the result in a cache file for future @command{configure} runs, and
9950 print a message letting the user know the result of the test.
9953 * Defining Symbols:: Defining C preprocessor symbols
9954 * Setting Output Variables:: Replacing variables in output files
9955 * Special Chars in Variables:: Characters to beware of in variables
9956 * Caching Results:: Speeding up subsequent @command{configure} runs
9957 * Printing Messages:: Notifying @command{configure} users
9960 @node Defining Symbols
9961 @section Defining C Preprocessor Symbols
9963 A common action to take in response to a feature test is to define a C
9964 preprocessor symbol indicating the results of the test. That is done by
9965 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9967 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9968 into the output variable @code{DEFS}, which contains an option
9969 @option{-D@var{symbol}=@var{value}} for each symbol defined. Unlike in
9970 Autoconf version 1, there is no variable @code{DEFS} defined while
9971 @command{configure} is running. To check whether Autoconf macros have
9972 already defined a certain C preprocessor symbol, test the value of the
9973 appropriate cache variable, as in this example:
9976 AC_CHECK_FUNC([vprintf],
9977 [AC_DEFINE([HAVE_VPRINTF], [1],
9978 [Define if vprintf exists.])])
9979 AS_IF([test "x$ac_cv_func_vprintf" != xyes],
9980 [AC_CHECK_FUNC([_doprnt],
9981 [AC_DEFINE([HAVE_DOPRNT], [1],
9982 [Define if _doprnt exists.])])])
9985 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9986 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9987 correct values into @code{#define} statements in a template file.
9988 @xref{Configuration Headers}, for more information about this kind of
9991 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9992 @defmacx AC_DEFINE (@var{variable})
9993 @cvindex @var{variable}
9995 Define @var{variable} to @var{value} (verbatim), by defining a C
9996 preprocessor macro for @var{variable}. @var{variable} should be a C
9997 identifier, optionally suffixed by a parenthesized argument list to
9998 define a C preprocessor macro with arguments. The macro argument list,
9999 if present, should be a comma-separated list of C identifiers, possibly
10000 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
10001 @var{variable} should not contain comments, white space, trigraphs,
10002 backslash-newlines, universal character names, or non-ASCII
10005 @var{value} may contain backslash-escaped newlines, which will be
10006 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
10007 via @code{@@DEFS@@} (with no effect on the compilation, since the
10008 preprocessor sees only one line in the first place). @var{value} should
10009 not contain raw newlines. If you are not using
10010 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
10011 characters, as @command{make} tends to eat them. To use a shell
10012 variable, use @code{AC_DEFINE_UNQUOTED} instead.
10014 @var{description} is only useful if you are using
10015 @code{AC_CONFIG_HEADERS}. In this case, @var{description} is put into
10016 the generated @file{config.h.in} as the comment before the macro define.
10017 The following example defines the C preprocessor variable
10018 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
10021 AC_DEFINE([EQUATION], ["$a > $b"],
10022 [Equation string.])
10025 If neither @var{value} nor @var{description} are given, then
10026 @var{value} defaults to 1 instead of to the empty string. This is for
10027 backwards compatibility with older versions of Autoconf, but this usage
10028 is obsolescent and may be withdrawn in future versions of Autoconf.
10030 If the @var{variable} is a literal string, it is passed to
10031 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
10033 If multiple @code{AC_DEFINE} statements are executed for the same
10034 @var{variable} name (not counting any parenthesized argument list),
10038 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
10039 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
10040 @acindex{DEFINE_UNQUOTED}
10041 @cvindex @var{variable}
10042 Like @code{AC_DEFINE}, but three shell expansions are
10043 performed---once---on @var{variable} and @var{value}: variable expansion
10044 (@samp{$}), command substitution (@samp{`}), and backslash escaping
10045 (@samp{\}), as if in an unquoted here-document. Single and double quote
10046 characters in the value have no
10047 special meaning. Use this macro instead of @code{AC_DEFINE} when
10048 @var{variable} or @var{value} is a shell variable. Examples:
10051 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
10052 [Configuration machine file.])
10053 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
10054 [getgroups return type.])
10055 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
10056 [Translated header name.])
10060 Due to a syntactical oddity of the Bourne shell, do not use
10061 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
10062 calls from other macro calls or shell code; that can cause syntax errors
10063 in the resulting @command{configure} script. Use either blanks or
10064 newlines. That is, do this:
10067 AC_CHECK_HEADER([elf.h],
10068 [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
10075 AC_CHECK_HEADER([elf.h],
10076 [AC_DEFINE([SVR4], [1], [System V Release 4])
10077 LIBS="-lelf $LIBS"])
10084 AC_CHECK_HEADER([elf.h],
10085 [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
10088 @node Setting Output Variables
10089 @section Setting Output Variables
10090 @cindex Output variables
10092 Another way to record the results of tests is to set @dfn{output
10093 variables}, which are shell variables whose values are substituted into
10094 files that @command{configure} outputs. The two macros below create new
10095 output variables. @xref{Preset Output Variables}, for a list of output
10096 variables that are always available.
10098 @defmac AC_SUBST (@var{variable}, @ovar{value})
10100 Create an output variable from a shell variable. Make @code{AC_OUTPUT}
10101 substitute the variable @var{variable} into output files (typically one
10102 or more makefiles). This means that @code{AC_OUTPUT}
10103 replaces instances of @samp{@@@var{variable}@@} in input files with the
10104 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
10105 is called. The value can contain any non-@code{NUL} character, including
10106 newline. If you are using Automake 1.11 or newer, for newlines in values
10107 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
10108 @command{automake} from adding a line @code{@var{variable} =
10109 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
10110 Automake, automake, Other things Automake recognizes}).
10112 Variable occurrences should not overlap: e.g., an input file should
10113 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
10114 are variable names.
10115 The substituted value is not rescanned for more output variables;
10116 occurrences of @samp{@@@var{variable}@@} in the value are inserted
10117 literally into the output file. (The algorithm uses the special marker
10118 @code{|#_!!_#|} internally, so neither the substituted value nor the
10119 output file may contain @code{|#_!!_#|}.)
10121 If @var{value} is given, in addition assign it to @var{variable}.
10123 The string @var{variable} is passed to @code{m4_pattern_allow}
10124 (@pxref{Forbidden Patterns}). @var{variable} is not further expanded,
10125 even if there is another macro by the same name.
10128 @defmac AC_SUBST_FILE (@var{variable})
10129 @acindex{SUBST_FILE}
10130 Another way to create an output variable from a shell variable. Make
10131 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
10132 named by shell variable @var{variable} into output files. This means
10133 that @code{AC_OUTPUT} replaces instances of
10134 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
10135 with the contents of the file that the shell variable @var{variable}
10136 names when @code{AC_OUTPUT} is called. Set the variable to
10137 @file{/dev/null} for cases that do not have a file to insert.
10138 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
10139 line by itself, optionally surrounded by spaces and tabs. The
10140 substitution replaces the whole line, including the spaces, tabs, and
10141 the terminating newline.
10143 This macro is useful for inserting makefile fragments containing
10144 special dependencies or other @command{make} directives for particular host
10145 or target types into makefiles. For example, @file{configure.ac}
10149 AC_SUBST_FILE([host_frag])
10150 host_frag=$srcdir/conf/sun4.mh
10154 and then a @file{Makefile.in} could contain:
10160 The string @var{variable} is passed to @code{m4_pattern_allow}
10161 (@pxref{Forbidden Patterns}).
10164 @cindex Precious Variable
10165 @cindex Variable, Precious
10166 Running @command{configure} in varying environments can be extremely
10167 dangerous. If for instance the user runs @samp{CC=bizarre-cc
10168 ./configure}, then the cache, @file{config.h}, and many other output
10169 files depend upon @command{bizarre-cc} being the C compiler. If
10170 for some reason the user runs @command{./configure} again, or if it is
10171 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
10172 and @pxref{config.status Invocation}), then the configuration can be
10173 inconsistent, composed of results depending upon two different
10176 Environment variables that affect this situation, such as @samp{CC}
10177 above, are called @dfn{precious variables}, and can be declared as such
10178 by @code{AC_ARG_VAR}.
10180 @defmac AC_ARG_VAR (@var{variable}, @var{description})
10182 Declare @var{variable} is a precious variable, and include its
10183 @var{description} in the variable section of @samp{./configure --help}.
10185 Being precious means that
10188 @var{variable} is substituted via @code{AC_SUBST}.
10191 The value of @var{variable} when @command{configure} was launched is
10192 saved in the cache, including if it was not specified on the command
10193 line but via the environment. Indeed, while @command{configure} can
10194 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
10195 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
10196 which, unfortunately, is what most users do.
10198 We emphasize that it is the @emph{initial} value of @var{variable} which
10199 is saved, not that found during the execution of @command{configure}.
10200 Indeed, specifying @samp{./configure FOO=foo} and letting
10201 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
10205 @var{variable} is checked for consistency between two
10206 @command{configure} runs. For instance:
10209 $ @kbd{./configure --silent --config-cache}
10210 $ @kbd{CC=cc ./configure --silent --config-cache}
10211 configure: error: 'CC' was not set in the previous run
10212 configure: error: changes in the environment can compromise \
10214 configure: error: run 'make distclean' and/or \
10215 'rm config.cache' and start over
10219 and similarly if the variable is unset, or if its content is changed.
10220 If the content has white space changes only, then the error is degraded
10221 to a warning only, but the old value is reused.
10224 @var{variable} is kept during automatic reconfiguration
10225 (@pxref{config.status Invocation}) as if it had been passed as a command
10226 line argument, including when no cache is used:
10229 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10230 $ @kbd{./config.status --recheck}
10231 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10232 CC=/usr/bin/cc --no-create --no-recursion
10237 @node Special Chars in Variables
10238 @section Special Characters in Output Variables
10239 @cindex Output variables, special characters in
10241 Many output variables are intended to be evaluated both by
10242 @command{make} and by the shell. Some characters are expanded
10243 differently in these two contexts, so to avoid confusion these
10244 variables' values should not contain any of the following characters:
10247 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10250 Also, these variables' values should neither contain newlines, nor start
10251 with @samp{~}, nor contain white space or @samp{:} immediately followed
10252 by @samp{~}. The values can contain nonempty sequences of white space
10253 characters like tabs and spaces, but each such sequence might
10254 arbitrarily be replaced by a single space during substitution.
10256 These restrictions apply both to the values that @command{configure}
10257 computes, and to the values set directly by the user. For example, the
10258 following invocations of @command{configure} are problematic, since they
10259 attempt to use special characters within @code{CPPFLAGS} and white space
10260 within @code{$(srcdir)}:
10263 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10265 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10268 @node Caching Results
10269 @section Caching Results
10272 To avoid checking for the same features repeatedly in various
10273 @command{configure} scripts (or in repeated runs of one script),
10274 @command{configure} can optionally save the results of many checks in a
10275 @dfn{cache file} (@pxref{Cache Files}). If a @command{configure} script
10276 runs with caching enabled and finds a cache file, it reads the results
10277 of previous runs from the cache and avoids rerunning those checks. As a
10278 result, @command{configure} can then run much faster than if it had to
10279 perform all of the checks every time.
10281 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10282 @acindex{CACHE_VAL}
10283 Ensure that the results of the check identified by @var{cache-id} are
10284 available. If the results of the check were in the cache file that was
10285 read, and @command{configure} was not given the @option{--quiet} or
10286 @option{--silent} option, print a message saying that the result was
10287 cached; otherwise, run the shell commands @var{commands-to-set-it}. If
10288 the shell commands are run to determine the value, the value is
10289 saved in the cache file just before @command{configure} creates its output
10290 files. @xref{Cache Variable Names}, for how to choose the name of the
10291 @var{cache-id} variable.
10293 The @var{commands-to-set-it} @emph{must have no side effects} except for
10294 setting the variable @var{cache-id}, see below.
10297 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10298 @var{commands-to-set-it})
10299 @acindex{CACHE_CHECK}
10300 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10301 messages. This macro provides a convenient shorthand for the most
10302 common way to use these macros. It calls @code{AC_MSG_CHECKING} for
10303 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10304 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10306 The @var{commands-to-set-it} @emph{must have no side effects} except for
10307 setting the variable @var{cache-id}, see below.
10310 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10311 @code{AC_CACHE_CHECK}, because people are tempted to call
10312 @code{AC_DEFINE} in the @var{commands-to-set-it}. Instead, the code that
10313 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10314 @code{AC_DEFINE}, by examining the value of the cache variable. For
10315 instance, the following macro is broken:
10318 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10320 AC_DEFUN([AC_SHELL_TRUE],
10321 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10322 [my_cv_shell_true_works=no
10323 (true) 2>/dev/null && my_cv_shell_true_works=yes
10324 if test "x$my_cv_shell_true_works" = xyes; then
10325 AC_DEFINE([TRUE_WORKS], [1],
10326 [Define if 'true(1)' works properly.])
10333 This fails if the cache is enabled: the second time this macro is run,
10334 @code{TRUE_WORKS} @emph{will not be defined}. The proper implementation
10338 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10340 AC_DEFUN([AC_SHELL_TRUE],
10341 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10342 [my_cv_shell_true_works=no
10343 (true) 2>/dev/null && my_cv_shell_true_works=yes])
10344 if test "x$my_cv_shell_true_works" = xyes; then
10345 AC_DEFINE([TRUE_WORKS], [1],
10346 [Define if 'true(1)' works properly.])
10352 Also, @var{commands-to-set-it} should not print any messages, for
10353 example with @code{AC_MSG_CHECKING}; do that before calling
10354 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10355 the results of the check are retrieved from the cache or determined by
10356 running the shell commands.
10359 * Cache Variable Names:: Shell variables used in caches
10360 * Cache Files:: Files @command{configure} uses for caching
10361 * Cache Checkpointing:: Loading and saving the cache file
10364 @node Cache Variable Names
10365 @subsection Cache Variable Names
10366 @cindex Cache variable
10368 The names of cache variables should have the following format:
10371 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10375 for example, @samp{ac_cv_header_stat_broken} or
10376 @samp{ac_cv_prog_gcc_traditional}. The parts of the variable name are:
10379 @item @var{package-prefix}
10380 An abbreviation for your package or organization; the same prefix you
10381 begin local Autoconf macros with, except lowercase by convention.
10382 For cache values used by the distributed Autoconf macros, this value is
10386 Indicates that this shell variable is a cache value. This string
10387 @emph{must} be present in the variable name, including the leading
10390 @item @var{value-type}
10391 A convention for classifying cache values, to produce a rational naming
10392 system. The values used in Autoconf are listed in @ref{Macro Names}.
10394 @item @var{specific-value}
10395 Which member of the class of cache values this test applies to.
10396 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10397 output variable (@samp{INSTALL}).
10399 @item @var{additional-options}
10400 Any particular behavior of the specific member that this test applies to.
10401 For example, @samp{broken} or @samp{set}. This part of the name may
10402 be omitted if it does not apply.
10405 The values assigned to cache variables may not contain newlines.
10406 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10407 names of files or functions; so this is not an important restriction.
10408 @ref{Cache Variable Index} for an index of cache variables with
10409 documented semantics.
10413 @subsection Cache Files
10415 A cache file is a shell script that caches the results of configure
10416 tests run on one system so they can be shared between configure scripts
10417 and configure runs. It is not useful on other systems. If its contents
10418 are invalid for some reason, the user may delete or edit it, or override
10419 documented cache variables on the @command{configure} command line.
10421 By default, @command{configure} uses no cache file,
10422 to avoid problems caused by accidental
10423 use of stale cache files.
10425 To enable caching, @command{configure} accepts @option{--config-cache} (or
10426 @option{-C}) to cache results in the file @file{config.cache}.
10427 Alternatively, @option{--cache-file=@var{file}} specifies that
10428 @var{file} be the cache file. The cache file is created if it does not
10429 exist already. When @command{configure} calls @command{configure} scripts in
10430 subdirectories, it uses the @option{--cache-file} argument so that they
10431 share the same cache. @xref{Subdirectories}, for information on
10432 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10434 @file{config.status} only pays attention to the cache file if it is
10435 given the @option{--recheck} option, which makes it rerun
10436 @command{configure}.
10438 It is wrong to try to distribute cache files for particular system types.
10439 There is too much room for error in doing that, and too much
10440 administrative overhead in maintaining them. For any features that
10441 can't be guessed automatically, use the standard method of the canonical
10442 system type and linking files (@pxref{Manual Configuration}).
10444 The site initialization script can specify a site-wide cache file to
10445 use, instead of the usual per-program cache. In this case, the cache
10446 file gradually accumulates information whenever someone runs a new
10447 @command{configure} script. (Running @command{configure} merges the new cache
10448 results with the existing cache file.) This may cause problems,
10449 however, if the system configuration (e.g., the installed libraries or
10450 compilers) changes and the stale cache file is not deleted.
10452 If @command{configure} is interrupted at the right time when it updates
10453 a cache file outside of the build directory where the @command{configure}
10454 script is run, it may leave behind a temporary file named after the
10455 cache file with digits following it. You may safely delete such a file.
10458 @node Cache Checkpointing
10459 @subsection Cache Checkpointing
10461 If your configure script, or a macro called from @file{configure.ac}, happens
10462 to abort the configure process, it may be useful to checkpoint the cache
10463 a few times at key points using @code{AC_CACHE_SAVE}. Doing so
10464 reduces the amount of time it takes to rerun the configure script with
10465 (hopefully) the error that caused the previous abort corrected.
10467 @c FIXME: Do we really want to document this guy?
10468 @defmac AC_CACHE_LOAD
10469 @acindex{CACHE_LOAD}
10470 Loads values from existing cache file, or creates a new cache file if a
10471 cache file is not found. Called automatically from @code{AC_INIT}.
10474 @defmac AC_CACHE_SAVE
10475 @acindex{CACHE_SAVE}
10476 Flushes all cached values to the cache file. Called automatically from
10477 @code{AC_OUTPUT}, but it can be quite useful to call
10478 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10484 @r{ @dots{} AC_INIT, etc. @dots{}}
10486 # Checks for programs.
10489 @r{ @dots{} more program checks @dots{}}
10494 # Checks for libraries.
10495 AC_CHECK_LIB([nsl], [gethostbyname])
10496 AC_CHECK_LIB([socket], [connect])
10497 @r{ @dots{} more lib checks @dots{}}
10502 # Might abort@dots{}
10503 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10504 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10506 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10509 @node Printing Messages
10510 @section Printing Messages
10511 @cindex Messages, from @command{configure}
10513 @command{configure} scripts need to give users running them several kinds
10514 of information. The following macros print messages in ways appropriate
10515 for each kind. The arguments to all of them get enclosed in shell
10516 double quotes, so the shell performs variable and back-quote
10517 substitution on them.
10519 These macros are all wrappers around the @command{printf} shell command.
10520 They direct output to the appropriate file descriptor (@pxref{File
10521 Descriptor Macros}).
10522 @command{configure} scripts should rarely need to run @command{printf} directly
10523 to print messages for the user. Using these macros makes it easy to
10524 change how and when each kind of message is printed; such changes need
10525 only be made to the macro definitions and all the callers change
10528 To diagnose static issues, i.e., when @command{autoconf} is run, see
10529 @ref{Diagnostic Macros}.
10531 @defmac AC_MSG_CHECKING (@var{feature-description})
10532 @acindex{MSG_CHECKING}
10533 Notify the user that @command{configure} is checking for a particular
10534 feature. This macro prints a message that starts with @samp{checking }
10535 and ends with @samp{...} and no newline. It must be followed by a call
10536 to @code{AC_MSG_RESULT} to print the result of the check and the
10537 newline. The @var{feature-description} should be something like
10538 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10541 This macro prints nothing if @command{configure} is run with the
10542 @option{--quiet} or @option{--silent} option.
10545 @anchor{AC_MSG_RESULT}
10546 @defmac AC_MSG_RESULT (@var{result-description})
10547 @acindex{MSG_RESULT}
10548 Notify the user of the results of a check. @var{result-description} is
10549 almost always the value of the cache variable for the check, typically
10550 @samp{yes}, @samp{no}, or a file name. This macro should follow a call
10551 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10552 the completion of the message printed by the call to
10553 @code{AC_MSG_CHECKING}.
10555 This macro prints nothing if @command{configure} is run with the
10556 @option{--quiet} or @option{--silent} option.
10559 @anchor{AC_MSG_NOTICE}
10560 @defmac AC_MSG_NOTICE (@var{message})
10561 @acindex{MSG_NOTICE}
10562 Deliver the @var{message} to the user. It is useful mainly to print a
10563 general description of the overall purpose of a group of feature checks,
10567 AC_MSG_NOTICE([checking if stack overflow is detectable])
10570 This macro prints nothing if @command{configure} is run with the
10571 @option{--quiet} or @option{--silent} option.
10574 @anchor{AC_MSG_ERROR}
10575 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10576 @acindex{MSG_ERROR}
10577 Notify the user of an error that prevents @command{configure} from
10578 completing. This macro prints an error message to the standard error
10579 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10580 by default, except that @samp{0} is converted to @samp{1}).
10581 @var{error-description} should be something like @samp{invalid value
10584 The @var{error-description} should start with a lower-case letter, and
10585 ``cannot'' is preferred to ``can't''.
10588 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10589 @acindex{MSG_FAILURE}
10590 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10591 prevents @command{configure} from completing @emph{and} that additional
10592 details are provided in @file{config.log}. This is typically used when
10593 abnormal results are found during a compilation.
10596 @anchor{AC_MSG_WARN}
10597 @defmac AC_MSG_WARN (@var{problem-description})
10599 Notify the @command{configure} user of a possible problem. This macro
10600 prints the message to the standard error output; @command{configure}
10601 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10602 provide a default (back-up) behavior for the situations they warn about.
10603 @var{problem-description} should be something like @samp{ln -s seems to
10609 @c ====================================================== Programming in M4.
10611 @node Programming in M4
10612 @chapter Programming in M4
10615 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10616 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10617 provides macros dedicated to shell script generation.
10619 As of this version of Autoconf, these two layers still contain
10620 experimental macros, whose interface might change in the future. As a
10621 matter of fact, @emph{anything that is not documented must not be used}.
10624 * M4 Quotation:: Protecting macros from unwanted expansion
10625 * Using autom4te:: The Autoconf executables backbone
10626 * Programming in M4sugar:: Convenient pure M4 macros
10627 * Debugging via autom4te:: Figuring out what M4 was doing
10631 @section M4 Quotation
10632 @cindex M4 quotation
10635 The most common problem with existing macros is an improper quotation.
10636 This section, which users of Autoconf can skip, but which macro writers
10637 @emph{must} read, first justifies the quotation scheme that was chosen
10638 for Autoconf and then ends with a rule of thumb. Understanding the
10639 former helps one to follow the latter.
10642 * Active Characters:: Characters that change the behavior of M4
10643 * One Macro Call:: Quotation and one macro call
10644 * Quoting and Parameters:: M4 vs. shell parameters
10645 * Quotation and Nested Macros:: Macros calling macros
10646 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
10647 * Quadrigraphs:: Another way to escape special characters
10648 * Balancing Parentheses:: Dealing with unbalanced parentheses
10649 * Quotation Rule Of Thumb:: One parenthesis, one quote
10652 @node Active Characters
10653 @subsection Active Characters
10655 To fully understand where proper quotation is important, you first need
10656 to know what the special characters are in Autoconf: @samp{#} introduces
10657 a comment inside which no macro expansion is performed, @samp{,}
10658 separates arguments, @samp{[} and @samp{]} are the quotes
10659 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10660 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10661 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10662 @samp{$} inside a macro definition.
10664 In order to understand the delicate case of macro calls, we first have
10665 to present some obvious failures. Below they are ``obvious-ified'',
10666 but when you find them in real life, they are usually in disguise.
10668 Comments, introduced by a hash and running up to the newline, are opaque
10669 tokens to the top level: active characters are turned off, and there is
10670 no macro expansion:
10673 # define([def], ine)
10674 @result{}# define([def], ine)
10677 Each time there can be a macro expansion, there is a quotation
10678 expansion, i.e., one level of quotes is stripped:
10682 @result{}int tab10;
10684 @result{}int tab[10];
10687 Without this in mind, the reader might try hopelessly to use her macro
10691 define([array], [int tab[10];])
10693 @result{}int tab10;
10699 How can you correctly output the intended results@footnote{Using
10703 @node One Macro Call
10704 @subsection One Macro Call
10706 Let's proceed on the interaction between active characters and macros
10707 with this small macro, which just returns its first argument:
10710 define([car], [$1])
10714 The two pairs of quotes above are not part of the arguments of
10715 @code{define}; rather, they are understood by the top level when it
10716 tries to find the arguments of @code{define}. Therefore, assuming
10717 @code{car} is not already defined, it is equivalent to write:
10724 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10725 quotes, it is bad practice for Autoconf macros which must both be more
10726 robust and also advocate perfect style.
10728 At the top level, there are only two possibilities: either you
10729 quote or you don't:
10734 [car(foo, bar, baz)]
10735 @result{}car(foo, bar, baz)
10738 Let's pay attention to the special characters:
10742 @error{}EOF in argument list
10745 The closing parenthesis is hidden in the comment; with a hypothetical
10746 quoting, the top level understood it this way:
10753 Proper quotation, of course, fixes the problem:
10760 Here are more examples:
10768 @result{}(foo, bar)
10769 car([(foo], [bar)])
10783 @node Quoting and Parameters
10784 @subsection Quoting and Parameters
10786 When M4 encounters @samp{$} within a macro definition, followed
10787 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10788 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10789 expansion. This happens regardless of how many layers of quotes the
10790 parameter expansion is nested within, or even if it occurs in text that
10791 will be rescanned as a comment.
10794 define([none], [$1])
10796 define([one], [[$1]])
10798 define([two], [[[$1]]])
10800 define([comment], [# $1])
10802 define([active], [ACTIVE])
10814 On the other hand, since autoconf generates shell code, you often want
10815 to output shell variable expansion, rather than performing M4 parameter
10816 expansion. To do this, you must use M4 quoting to separate the @samp{$}
10817 from the next character in the definition of your macro. If the macro
10818 definition occurs in single-quoted text, then insert another level of
10819 quoting; if the usage is already inside a double-quoted string, then
10820 split it into concatenated strings.
10823 define([foo], [a single-quoted $[]1 definition])
10825 define([bar], [[a double-quoted $][1 definition]])
10828 @result{}a single-quoted $1 definition
10830 @result{}a double-quoted $1 definition
10833 POSIX states that M4 implementations are free to provide implementation
10834 extensions when @samp{$@{} is encountered in a macro definition.
10835 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10836 extensions that will be available in the future GNU M4 2.0,
10837 but guarantees that all other instances of @samp{$@{} will be output
10838 literally. Therefore, this idiom can also be used to output shell code
10839 parameter references:
10842 define([first], [$@{1@}])first
10846 POSIX also states that @samp{$11} should expand to the first parameter
10847 concatenated with a literal @samp{1}, although some versions of
10848 GNU M4 expand the eleventh parameter instead. For
10849 portability, you should only use single-digit M4 parameter expansion.
10851 With this in mind, we can explore the cases where macros invoke
10854 @node Quotation and Nested Macros
10855 @subsection Quotation and Nested Macros
10857 The examples below use the following macros:
10860 define([car], [$1])
10861 define([active], [ACT, IVE])
10862 define([array], [int tab[10]])
10865 Each additional embedded macro call introduces other possible
10866 interesting quotations:
10877 In the first case, the top level looks for the arguments of @code{car},
10878 and finds @samp{active}. Because M4 evaluates its arguments
10879 before applying the macro, @samp{active} is expanded, which results in:
10887 In the second case, the top level gives @samp{active} as first and only
10888 argument of @code{car}, which results in:
10896 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10897 In the third case, @code{car} receives @samp{[active]}, which results in:
10905 exactly as we already saw above.
10907 The example above, applied to a more realistic example, gives:
10911 @result{}int tab10;
10912 car([int tab[10];])
10913 @result{}int tab10;
10914 car([[int tab[10];]])
10915 @result{}int tab[10];
10919 Huh? The first case is easily understood, but why is the second wrong,
10920 and the third right? To understand that, you must know that after
10921 M4 expands a macro, the resulting text is immediately subjected
10922 to macro expansion and quote removal. This means that the quote removal
10923 occurs twice---first before the argument is passed to the @code{car}
10924 macro, and second after the @code{car} macro expands to the first
10927 As the author of the Autoconf macro @code{car}, you then consider it to
10928 be incorrect that your users have to double-quote the arguments of
10929 @code{car}, so you ``fix'' your macro. Let's call it @code{qar} for
10933 define([qar], [[$1]])
10937 and check that @code{qar} is properly fixed:
10940 qar([int tab[10];])
10941 @result{}int tab[10];
10945 Ahhh! That's much better.
10947 But note what you've done: now that the result of @code{qar} is always
10948 a literal string, the only time a user can use nested macros is if she
10949 relies on an @emph{unquoted} macro call:
10959 leaving no way for her to reproduce what she used to do with @code{car}:
10967 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10971 define([my_includes], [#include <stdio.h>])
10973 @result{}#include <stdio.h>
10975 @error{}EOF in argument list
10978 This macro, @code{qar}, because it double quotes its arguments, forces
10979 its users to leave their macro calls unquoted, which is dangerous.
10980 Commas and other active symbols are interpreted by M4 before
10981 they are given to the macro, often not in the way the users expect.
10982 Also, because @code{qar} behaves differently from the other macros,
10983 it's an exception that should be avoided in Autoconf.
10985 @node Changequote is Evil
10986 @subsection @code{changequote} is Evil
10987 @cindex @code{changequote}
10989 The temptation is often high to bypass proper quotation, in particular
10990 when it's late at night. Then, many experienced Autoconf hackers
10991 finally surrender to the dark side of the force and use the ultimate
10992 weapon: @code{changequote}.
10994 The M4 builtin @code{changequote} belongs to a set of primitives that
10995 allow one to adjust the syntax of the language to adjust it to one's
10996 needs. For instance, by default M4 uses @samp{`} and @samp{'} as
10997 quotes, but in the context of shell programming (and actually of most
10998 programming languages), that's about the worst choice one can make:
10999 because of strings and back-quoted expressions in shell code (such as
11000 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
11001 programming languages (as in @samp{'0'}), there are many unbalanced
11002 @samp{`} and @samp{'}. Proper M4 quotation then becomes a nightmare, if
11003 not impossible. In order to make M4 useful in such a context, its
11004 designers have equipped it with @code{changequote}, which makes it
11005 possible to choose another pair of quotes. M4sugar, M4sh, Autoconf, and
11006 Autotest all have chosen to use @samp{[} and @samp{]}. Not especially
11007 because they are unlikely characters, but @emph{because they are
11008 characters unlikely to be unbalanced}.
11010 There are other magic primitives, such as @code{changecom} to specify
11011 what syntactic forms are comments (it is common to see
11012 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
11013 @code{changeword} and @code{changesyntax} to change other syntactic
11014 details (such as the character to denote the @var{n}th argument, @samp{$} by
11015 default, the parentheses around arguments, etc.).
11017 These primitives are really meant to make M4 more useful for specific
11018 domains: they should be considered like command line options:
11019 @option{--quotes}, @option{--comments}, @option{--words}, and
11020 @option{--syntax}. Nevertheless, they are implemented as M4 builtins, as
11021 it makes M4 libraries self contained (no need for additional options).
11023 There lies the problem@enddots{}
11027 The problem is that it is then tempting to use them in the middle of an
11028 M4 script, as opposed to its initialization. This, if not carefully
11029 thought out, can lead to disastrous effects: @emph{you are changing the
11030 language in the middle of the execution}. Changing and restoring the
11031 syntax is often not enough: if you happened to invoke macros in between,
11032 these macros are lost, as the current syntax is probably not
11033 the one they were implemented with.
11035 @c FIXME: I've been looking for a short, real case example, but I
11036 @c lost them all :(
11040 @subsection Quadrigraphs
11041 @cindex quadrigraphs
11042 @cindex @samp{@@S|@@}
11043 @cindex @samp{@@&t@@}
11044 @c Info cannot handle ':' in index entries.
11046 @cindex @samp{@@<:@@}
11047 @cindex @samp{@@:>@@}
11048 @cindex @samp{@@%:@@}
11049 @cindex @samp{@@@{:@@}
11050 @cindex @samp{@@:@}@@}
11053 When writing an Autoconf macro you may occasionally need to generate
11054 special characters that are difficult to express with the standard
11055 Autoconf quoting rules. For example, you may need to output the regular
11056 expression @samp{[^[]}, which matches any character other than @samp{[}.
11057 This expression contains unbalanced brackets so it cannot be put easily
11060 Additionally, there are a few m4sugar macros (such as @code{m4_split}
11061 and @code{m4_expand}) which internally use special markers in addition
11062 to the regular quoting characters. If the arguments to these macros
11063 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
11064 might behave incorrectly.
11066 You can work around these problems by using one of the following
11067 @dfn{quadrigraphs}:
11083 Expands to nothing.
11086 Quadrigraphs are replaced at a late stage of the translation process,
11087 after @command{m4} is run, so they do not get in the way of M4 quoting.
11088 For example, the string @samp{^@@<:@@}, independently of its quotation,
11089 appears as @samp{^[} in the output.
11091 The empty quadrigraph can be used:
11094 @item to mark trailing spaces explicitly
11096 Trailing spaces are smashed by @command{autom4te}. This is a feature.
11098 @item to produce quadrigraphs and other strings reserved by m4sugar
11100 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}. For a more
11104 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
11105 m4_split([a )@}>=- b -=<@{( c])
11106 @result{}[a], [], [B], [], [c]
11107 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
11108 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
11111 @item to escape @emph{occurrences} of forbidden patterns
11113 For instance you might want to mention @code{AC_FOO} in a comment, while
11114 still being sure that @command{autom4te} still catches unexpanded
11115 @samp{AC_*}. Then write @samp{AC@@&t@@_FOO}.
11118 The name @samp{@@&t@@} was suggested by Paul Eggert:
11121 I should give some credit to the @samp{@@&t@@} pun. The @samp{&} is my
11122 own invention, but the @samp{t} came from the source code of the
11123 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
11124 and which used @samp{mt} to denote the empty string. In C, it would
11125 have looked like something like:
11128 char const mt[] = "";
11132 but of course the source code was written in Algol 68.
11134 I don't know where he got @samp{mt} from: it could have been his own
11135 invention, and I suppose it could have been a common pun around the
11136 Cambridge University computer lab at the time.
11140 @node Balancing Parentheses
11141 @subsection Dealing with unbalanced parentheses
11142 @cindex balancing parentheses
11143 @cindex parentheses, balancing
11144 @cindex unbalanced parentheses, managing
11146 One of the pitfalls of portable shell programming is that
11147 if you intend your script to run with obsolescent shells,
11148 @command{case} statements require unbalanced parentheses.
11149 @xref{case, , Limitations of Shell Builtins}.
11150 With syntax highlighting
11151 editors, the presence of unbalanced @samp{)} can interfere with editors
11152 that perform syntax highlighting of macro contents based on finding the
11153 matching @samp{(}. Another concern is how much editing must be done
11154 when transferring code snippets between shell scripts and macro
11155 definitions. But most importantly, the presence of unbalanced
11156 parentheses can introduce expansion bugs.
11158 For an example, here is an underquoted attempt to use the macro
11159 @code{my_case}, which happens to expand to a portable @command{case}
11163 AC_DEFUN([my_case],
11164 [case $file_name in
11165 *.c) file_type='C source code';;
11171 In the above example, the @code{AS_IF} call under-quotes its arguments.
11172 As a result, the unbalanced @samp{)} generated by the premature
11173 expansion of @code{my_case} results in expanding @code{AS_IF} with a
11174 truncated parameter, and the expansion is syntactically invalid:
11181 fi file_type='C source code';;
11185 If nothing else, this should emphasize the importance of the quoting
11186 arguments to macro calls. On the other hand, there are several
11187 variations for defining @code{my_case} to be more robust, even when used
11188 without proper quoting, each with some benefits and some drawbacks.
11191 @item Use left parenthesis before pattern
11193 AC_DEFUN([my_case],
11194 [case $file_name in
11195 (*.c) file_type='C source code';;
11199 This is simple and provides balanced parentheses. Although this is not
11200 portable to obsolescent shells (notably Solaris 10 @command{/bin/sh}),
11201 platforms with these shells invariably have a more-modern shell
11202 available somewhere so this approach typically suffices nowadays.
11204 @item Creative literal shell comment
11206 AC_DEFUN([my_case],
11207 [case $file_name in #(
11208 *.c) file_type='C source code';;
11212 This version provides balanced parentheses to several editors, and can
11213 be copied and pasted into a terminal as is. Unfortunately, it is still
11214 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
11215 that masks the normal properties of @samp{(}.
11217 @item Quadrigraph shell comment
11219 AC_DEFUN([my_case],
11220 [case $file_name in @@%:@@(
11221 *.c) file_type='C source code';;
11225 This version provides balanced parentheses to even more editors, and can
11226 be used as a balanced Autoconf argument. Unfortunately, it requires
11227 some editing before it can be copied and pasted into a terminal, and the
11228 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
11230 @item Quoting just the parenthesis
11232 AC_DEFUN([my_case],
11233 [case $file_name in
11234 *.c[)] file_type='C source code';;
11238 This version quotes the @samp{)}, so that it can be used as a balanced
11239 Autoconf argument. As written, this is not balanced to an editor, but
11240 it can be coupled with @samp{[#(]} to meet that need, too. However, it
11241 still requires some edits before it can be copied and pasted into a
11244 @item Double-quoting the entire statement
11246 AC_DEFUN([my_case],
11247 [[case $file_name in #(
11248 *.c) file_type='C source code';;
11252 Since the entire macro is double-quoted, there is no problem with using
11253 this as an Autoconf argument; and since the double-quoting is over the
11254 entire statement, this code can be easily copied and pasted into a
11255 terminal. However, the double quoting prevents the expansion of any
11256 macros inside the case statement, which may cause its own set of
11259 @item Using @code{AS_CASE}
11261 AC_DEFUN([my_case],
11262 [AS_CASE([$file_name],
11263 [*.c], [file_type='C source code'])])
11266 This version avoids the balancing issue altogether, by relying on
11267 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11268 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11269 statement, rather than within a branch of the case statement that might
11270 not be taken. However, the abstraction comes with a penalty that it is
11271 no longer a quick copy, paste, and edit to get back to shell code.
11275 @node Quotation Rule Of Thumb
11276 @subsection Quotation Rule Of Thumb
11278 To conclude, the quotation rule of thumb is:
11280 @center @emph{One pair of quotes per pair of parentheses.}
11282 Never over-quote, never under-quote, in particular in the definition of
11283 macros. In the few places where the macros need to use brackets
11284 (usually in C program text or regular expressions), properly quote
11285 @emph{the arguments}!
11287 It is common to read Autoconf programs with snippets like:
11291 changequote(<<, >>)dnl
11292 <<#include <time.h>
11293 #ifndef tzname /* For SGI. */
11294 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11296 changequote([, ])dnl
11297 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11301 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11302 double quoting, so you just need:
11307 #ifndef tzname /* For SGI. */
11308 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11311 [ac_cv_var_tzname=yes],
11312 [ac_cv_var_tzname=no])
11316 The M4-fluent reader might note that these two examples are rigorously
11317 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11318 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11319 quotes are not part of the arguments!
11321 Simplified, the example above is just doing this:
11324 changequote(<<, >>)dnl
11326 changequote([, ])dnl
11336 With macros that do not double quote their arguments (which is the
11337 rule), double-quote the (risky) literals:
11340 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11341 [[#include <time.h>
11342 #ifndef tzname /* For SGI. */
11343 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11345 [atoi (*tzname);])],
11346 [ac_cv_var_tzname=yes],
11347 [ac_cv_var_tzname=no])
11350 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11351 should be using @code{AC_LINK_IFELSE} instead.
11353 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11354 where quoting does not suffice.
11356 When you create a @command{configure} script using newly written macros,
11357 examine it carefully to check whether you need to add more quotes in
11358 your macros. If one or more words have disappeared in the M4
11359 output, you need more quotes. When in doubt, quote.
11361 However, it's also possible to put on too many layers of quotes. If
11362 this happens, the resulting @command{configure} script may contain
11363 unexpanded macros. The @command{autoconf} program checks for this problem
11364 by looking for the string @samp{AC_} in @file{configure}. However, this
11365 heuristic does not work in general: for example, it does not catch
11366 overquoting in @code{AC_DEFINE} descriptions.
11369 @c ---------------------------------------- Using autom4te
11371 @node Using autom4te
11372 @section Using @command{autom4te}
11374 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11375 to Autoconf per se, heavily rely on M4. All these different uses
11376 revealed common needs factored into a layer over M4:
11377 @command{autom4te}@footnote{
11379 Yet another great name from Lars J. Aas.
11383 @command{autom4te} is a preprocessor that is like @command{m4}.
11384 It supports M4 extensions designed for use in tools like Autoconf.
11387 * autom4te Invocation:: A GNU M4 wrapper
11388 * Customizing autom4te:: Customizing the Autoconf package
11391 @node autom4te Invocation
11392 @subsection Invoking @command{autom4te}
11394 The command line arguments are modeled after M4's:
11397 autom4te @var{options} @var{files}
11402 where the @var{files} are directly passed to @command{m4}. By default,
11403 GNU M4 is found during configuration, but the environment
11405 @env{M4} can be set to tell @command{autom4te} where to look. In addition
11406 to the regular expansion, it handles the replacement of the quadrigraphs
11407 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11408 output. It supports an extended syntax for the @var{files}:
11411 @item @var{file}.m4f
11412 This file is an M4 frozen file. Note that @emph{all the previous files
11413 are ignored}. See the @option{--melt} option for the rationale.
11416 If found in the library path, the @var{file} is included for expansion,
11417 otherwise it is ignored instead of triggering a failure.
11422 Of course, it supports the Autoconf common subset of options:
11427 Print a summary of the command line options and exit.
11431 Print the version number of Autoconf and exit.
11435 Report processing steps.
11439 Don't remove the temporary files and be even more verbose.
11441 @item --include=@var{dir}
11442 @itemx -I @var{dir}
11443 Also look for input files in @var{dir}. Multiple invocations
11446 @item --output=@var{file}
11447 @itemx -o @var{file}
11448 Save output (script or trace) to @var{file}. The file @option{-} stands
11449 for the standard output.
11454 As an extension of @command{m4}, it includes the following options:
11458 @item --warnings=@var{category}[,@var{category}...]
11459 @itemx -W@var{category}[,@var{category}...]
11461 Enable or disable warnings related to each @var{category}.
11462 @xref{m4_warn}, for a comprehensive list of categories.
11463 Special values include:
11467 Enable all categories of warnings.
11470 Disable all categories of warnings.
11473 Treat all warnings as errors.
11475 @item no-@var{category}
11476 Disable warnings falling into @var{category}.
11479 The environment variable @env{WARNINGS} may also be set to a
11480 comma-separated list of warning categories to enable or disable.
11481 It is interpreted exactly the same way as the argument of
11482 @option{--warnings}, but unknown categories are silently ignored.
11483 The command line takes precedence; for instance, if @env{WARNINGS}
11484 is set to @code{obsolete}, but @option{-Wnone} is given on the
11485 command line, no warnings will be issued.
11487 Some categories of warnings are on by default.
11488 Again, for details see @ref{m4_warn}.
11492 Do not use frozen files. Any argument @code{@var{file}.m4f} is
11493 replaced by @code{@var{file}.m4}. This helps tracing the macros which
11494 are executed only when the files are frozen, typically
11495 @code{m4_define}. For instance, running:
11498 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11502 is roughly equivalent to running:
11505 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11512 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11519 m4 --reload-state=4.m4f input.m4
11524 Produce a frozen state file. @command{autom4te} freezing is stricter
11525 than M4's: it must produce no warnings, and no output other than empty
11526 lines (a line with white space is @emph{not} empty) and comments
11527 (starting with @samp{#}). Unlike @command{m4}'s similarly-named option,
11528 this option takes no argument:
11531 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11538 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11541 @item --mode=@var{octal-mode}
11542 @itemx -m @var{octal-mode}
11543 Set the mode of the non-traces output to @var{octal-mode}; by default
11549 @cindex @file{autom4te.cache}
11550 As another additional feature over @command{m4}, @command{autom4te}
11551 caches its results. GNU M4 is able to produce a regular
11552 output and traces at the same time. Traces are heavily used in the
11553 GNU Build System: @command{autoheader} uses them to build
11554 @file{config.h.in}, @command{autoreconf} to determine what
11555 GNU Build System components are used, @command{automake} to
11556 ``parse'' @file{configure.ac} etc. To avoid recomputation,
11557 traces are cached while performing regular expansion,
11558 and conversely. This cache is (actually, the caches are) stored in
11559 the directory @file{autom4te.cache}. @emph{It can safely be removed}
11560 at any moment (especially if for some reason @command{autom4te}
11561 considers it trashed).
11564 @item --cache=@var{directory}
11565 @itemx -C @var{directory}
11566 Specify the name of the directory where the result should be cached.
11567 Passing an empty value disables caching. Be sure to pass a relative
11568 file name, as for the time being, global caches are not supported.
11571 Don't cache the results.
11575 If a cache is used, consider it obsolete (but update it anyway).
11580 Because traces are so important to the GNU Build System,
11581 @command{autom4te} provides high level tracing features as compared to
11582 M4, and helps exploiting the cache:
11585 @item --trace=@var{macro}[:@var{format}]
11586 @itemx -t @var{macro}[:@var{format}]
11587 Trace the invocations of @var{macro} according to the @var{format}.
11588 Multiple @option{--trace} arguments can be used to list several macros.
11589 Multiple @option{--trace} arguments for a single macro are not
11590 cumulative; instead, you should just make @var{format} as long as
11593 The @var{format} is a regular string, with newlines if desired, and
11594 several special escape codes. It defaults to @samp{$f:$l:$n:$%}. It can
11595 use the following special escapes:
11599 @c $$ restore font-lock
11600 The character @samp{$}.
11603 The file name from which @var{macro} is called.
11606 The line number from which @var{macro} is called.
11609 The depth of the @var{macro} call. This is an M4 technical detail that
11610 you probably don't want to know about.
11613 The name of the @var{macro}.
11616 The @var{num}th argument of the call to @var{macro}.
11619 @itemx $@var{sep}@@
11620 @itemx $@{@var{separator}@}@@
11621 All the arguments passed to @var{macro}, separated by the character
11622 @var{sep} or the string @var{separator} (@samp{,} by default). Each
11623 argument is quoted, i.e., enclosed in a pair of square brackets.
11627 @itemx $@{@var{separator}@}*
11628 As above, but the arguments are not quoted.
11632 @itemx $@{@var{separator}@}%
11633 As above, but the arguments are not quoted, all new line characters in
11634 the arguments are smashed, and the default separator is @samp{:}.
11636 The escape @samp{$%} produces single-line trace outputs (unless you put
11637 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11641 @xref{autoconf Invocation}, for examples of trace uses.
11643 @item --preselect=@var{macro}
11644 @itemx -p @var{macro}
11645 Cache the traces of @var{macro}, but do not enable traces. This is
11646 especially important to save CPU cycles in the future. For instance,
11647 when invoked, @command{autoconf} pre-selects all the macros that
11648 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11649 trace, so that running @command{m4} is not needed to trace them: the
11650 cache suffices. This results in a huge speed-up.
11655 @cindex Autom4te Library
11656 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11657 libraries}. They consists in a powerful yet extremely simple feature:
11658 sets of combined command line arguments:
11661 @item --language=@var{language}
11662 @itemx -l @var{language}
11663 Use the @var{language} Autom4te library. Current languages include:
11667 create M4sugar output.
11670 create M4sh executable shell scripts.
11673 create Autotest executable test suites.
11675 @item Autoconf-without-aclocal-m4
11676 create Autoconf executable configure scripts without
11677 reading @file{aclocal.m4}.
11680 create Autoconf executable configure scripts. This language inherits
11681 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11682 additionally reads @file{aclocal.m4}.
11685 @item --prepend-include=@var{dir}
11686 @itemx -B @var{dir}
11687 Prepend directory @var{dir} to the search path. This is used to include
11688 the language-specific files before any third-party macros.
11692 @cindex @file{autom4te.cfg}
11693 As an example, if Autoconf is installed in its default location,
11694 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11695 strictly equivalent to the command:
11698 autom4te --prepend-include /usr/local/share/autoconf \
11699 m4sugar/m4sugar.m4f foo.m4
11703 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11704 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11708 autom4te --prepend-include /usr/local/share/autoconf \
11709 m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11713 The definition of the languages is stored in @file{autom4te.cfg}.
11715 @node Customizing autom4te
11716 @subsection Customizing @command{autom4te}
11718 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11719 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11720 as found in the directory from which @command{autom4te} is run). The
11721 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11722 then @file{./.autom4te.cfg}, and finally the command line arguments.
11724 In these text files, comments are introduced with @code{#}, and empty
11725 lines are ignored. Customization is performed on a per-language basis,
11726 wrapped in between a @samp{begin-language: "@var{language}"},
11727 @samp{end-language: "@var{language}"} pair.
11729 Customizing a language stands for appending options (@pxref{autom4te
11730 Invocation}) to the current definition of the language. Options, and
11731 more generally arguments, are introduced by @samp{args:
11732 @var{arguments}}. You may use the traditional shell syntax to quote the
11735 As an example, to disable Autoconf caches (@file{autom4te.cache})
11736 globally, include the following lines in @file{~/.autom4te.cfg}:
11739 ## ------------------ ##
11740 ## User Preferences. ##
11741 ## ------------------ ##
11743 begin-language: "Autoconf-without-aclocal-m4"
11745 end-language: "Autoconf-without-aclocal-m4"
11749 @node Programming in M4sugar
11750 @section Programming in M4sugar
11753 M4 by itself provides only a small, but sufficient, set of all-purpose
11754 macros. M4sugar introduces additional generic macros. Its name was
11755 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11758 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11759 the macro namespace @samp{^m4_} for M4sugar macros. You should not
11760 define your own macros into these namespaces.
11763 * Redefined M4 Macros:: M4 builtins changed in M4sugar
11764 * Diagnostic Macros:: Diagnostic messages from M4sugar
11765 * Diversion support:: Diversions in M4sugar
11766 * Conditional constructs:: Conditions in M4
11767 * Looping constructs:: Iteration in M4
11768 * Evaluation Macros:: More quotation and evaluation control
11769 * Text processing Macros:: String manipulation in M4
11770 * Number processing Macros:: Arithmetic computation in M4
11771 * Set manipulation Macros:: Set manipulation in M4
11772 * Forbidden Patterns:: Catching unexpanded macros
11775 @node Redefined M4 Macros
11776 @subsection Redefined M4 Macros
11779 @msindex{changecom}
11780 @msindex{changequote}
11781 @msindex{debugfile}
11782 @msindex{debugmode}
11803 With a few exceptions, all the M4 native macros are moved in the
11804 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11805 @code{m4_define} etc.
11807 The list of macros unchanged from M4, except for their name, is:
11811 @item m4_changequote
11836 Some M4 macros are redefined, and are slightly incompatible with their
11843 All M4 macros starting with @samp{__} retain their original name: for
11844 example, no @code{m4__file__} is defined.
11849 This is not technically a macro, but a feature of Autom4te. The
11850 sequence @code{__oline__} can be used similarly to the other m4sugar
11851 location macros, but rather than expanding to the location of the input
11852 file, it is translated to the line number where it appears in the output
11853 file after all other M4 expansions.
11858 This macro kept its original name: no @code{m4_dnl} is defined.
11861 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11862 @msindex{bpatsubst}
11863 This macro corresponds to @code{patsubst}. The name @code{m4_patsubst}
11864 is kept for future versions of M4sugar, once GNU M4 2.0 is
11865 released and supports extended regular expression syntax.
11868 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11870 This macro corresponds to @code{regexp}. The name @code{m4_regexp}
11871 is kept for future versions of M4sugar, once GNU M4 2.0 is
11872 released and supports extended regular expression syntax.
11875 @defmac m4_copy (@var{source}, @var{dest})
11876 @defmacx m4_copy_force (@var{source}, @var{dest})
11877 @defmacx m4_rename (@var{source}, @var{dest})
11878 @defmacx m4_rename_force (@var{source}, @var{dest})
11880 @msindex{copy_force}
11882 @msindex{rename_force}
11883 These macros aren't directly builtins, but are closely related to
11884 @code{m4_pushdef} and @code{m4_defn}. @code{m4_copy} and
11885 @code{m4_rename} ensure that @var{dest} is undefined, while
11886 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11887 definition. All four macros then proceed to copy the entire pushdef
11888 stack of definitions of @var{source} over to @var{dest}. @code{m4_copy}
11889 and @code{m4_copy_force} preserve the source (including in the special
11890 case where @var{source} is undefined), while @code{m4_rename} and
11891 @code{m4_rename_force} undefine the original macro name (making it an
11892 error to rename an undefined @var{source}).
11894 Note that attempting to invoke a renamed macro might not work, since the
11895 macro may have a dependence on helper macros accessed via composition of
11896 @samp{$0} but that were not also renamed; likewise, other macros may
11897 have a hard-coded dependence on @var{source} and could break if
11898 @var{source} has been deleted. On the other hand, it is always safe to
11899 rename a macro to temporarily move it out of the way, then rename it
11900 back later to restore original semantics.
11903 @defmac m4_defn (@var{macro}@dots{})
11905 This macro fails if @var{macro} is not defined, even when using older
11906 versions of M4 that did not warn. See @code{m4_undefine}.
11907 Unfortunately, in order to support these older versions of M4, there are
11908 some situations involving unbalanced quotes where concatenating multiple
11909 macros together will work in newer M4 but not in m4sugar; use
11910 quadrigraphs to work around this.
11913 @defmac m4_divert (@var{diversion})
11915 M4sugar relies heavily on diversions, so rather than behaving as a
11916 primitive, @code{m4_divert} behaves like:
11918 m4_divert_pop()m4_divert_push([@var{diversion}])
11921 @xref{Diversion support}, for more details about the use of the
11922 diversion stack. In particular, this implies that @var{diversion}
11923 should be a named diversion rather than a raw number. But be aware that
11924 it is seldom necessary to explicitly change the diversion stack, and
11925 that when done incorrectly, it can lead to syntactically invalid
11929 @defmac m4_dumpdef (@var{name}@dots{})
11930 @defmacx m4_dumpdefs (@var{name}@dots{})
11933 @code{m4_dumpdef} is like the M4 builtin, except that this version
11934 requires at least one argument, output always goes to standard error
11935 rather than the current debug file, no sorting is done on multiple
11936 arguments, and an error is issued if any
11937 @var{name} is undefined. @code{m4_dumpdefs} is a convenience macro that
11938 calls @code{m4_dumpdef} for all of the
11939 @code{m4_pushdef} stack of definitions, starting with the current, and
11940 silently does nothing if @var{name} is undefined.
11942 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11943 builtin is output as the empty string. This behavior is rectified by
11944 using M4 1.6 or newer. However, this behavior difference means that
11945 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11946 and never in the final published form of a macro.
11949 @defmac m4_esyscmd_s (@var{command})
11950 @msindex{esyscmd_s}
11951 Like @code{m4_esyscmd}, this macro expands to the result of running
11952 @var{command} in a shell. The difference is that any trailing newlines
11953 are removed, so that the output behaves more like shell command
11957 @defmac m4_exit (@var{exit-status})
11959 This macro corresponds to @code{m4exit}.
11962 @defmac m4_if (@var{comment})
11963 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11964 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11965 @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11967 This macro corresponds to @code{ifelse}. @var{string-1} and
11968 @var{string-2} are compared literally, so usually one of the two
11969 arguments is passed unquoted. @xref{Conditional constructs}, for more
11970 conditional idioms.
11973 @defmac m4_include (@var{file})
11974 @defmacx m4_sinclude (@var{file})
11977 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11980 @defmac m4_mkstemp (@var{template})
11981 @defmacx m4_maketemp (@var{template})
11984 POSIX requires @code{maketemp} to replace the trailing @samp{X}
11985 characters in @var{template} with the process id, without regards to the
11986 existence of a file by that name, but this a security hole. When this
11987 was pointed out to the POSIX folks, they agreed to invent a new macro
11988 @code{mkstemp} that always creates a uniquely named file, but not all
11989 versions of GNU M4 support the new macro. In M4sugar,
11990 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11991 and both have the secure semantics regardless of which macro the
11992 underlying M4 provides.
11995 @defmac m4_popdef (@var{macro}@dots{})
11997 This macro fails if @var{macro} is not defined, even when using older
11998 versions of M4 that did not warn. See @code{m4_undefine}.
12001 @defmac m4_undefine (@var{macro}@dots{})
12003 This macro fails if @var{macro} is not defined, even when using older
12004 versions of M4 that did not warn. Use
12007 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
12011 if you are not sure whether @var{macro} is defined.
12014 @defmac m4_undivert (@var{diversion}@dots{})
12016 Unlike the M4 builtin, at least one @var{diversion} must be specified.
12017 Also, since the M4sugar diversion stack prefers named
12018 diversions, the use of @code{m4_undivert} to include files is risky.
12019 @xref{Diversion support}, for more details about the use of the
12020 diversion stack. But be aware that it is seldom necessary to explicitly
12021 change the diversion stack, and that when done incorrectly, it can lead
12022 to syntactically invalid scripts.
12025 @defmac m4_wrap (@var{text})
12026 @defmacx m4_wrap_lifo (@var{text})
12028 @msindex{wrap_lifo}
12029 These macros correspond to @code{m4wrap}. POSIX requires arguments of
12030 multiple wrap calls to be reprocessed at EOF in the same order
12031 as the original calls (first-in, first-out). GNU M4 versions
12032 through 1.4.10, however, reprocess them in reverse order (last-in,
12033 first-out). Both orders are useful, therefore, you can rely on
12034 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
12035 LIFO semantics, regardless of the underlying GNU M4 version.
12037 Unlike the GNU M4 builtin, these macros only recognize one
12038 argument, and avoid token pasting between consecutive invocations. On
12039 the other hand, nested calls to @code{m4_wrap} from within wrapped text
12040 work just as in the builtin.
12044 @node Diagnostic Macros
12045 @subsection Diagnostic messages from M4sugar
12046 @cindex Messages, from @command{M4sugar}
12048 When macros statically diagnose abnormal situations, benign or fatal,
12049 they should report them using these macros. For issuing dynamic issues,
12050 i.e., when @command{configure} is run, see @ref{Printing Messages}.
12052 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
12054 Assert that the arithmetic @var{expression} evaluates to non-zero.
12055 Otherwise, issue a fatal error, and exit @command{autom4te} with
12059 @defmac m4_errprintn (@var{message})
12060 @msindex{errprintn}
12061 Similar to the builtin @code{m4_errprint}, except that a newline is
12062 guaranteed after @var{message}.
12066 @defmac m4_fatal (@var{message})
12068 Report a severe error @var{message} prefixed with the current location,
12069 and have @command{autom4te} die.
12072 @defmac m4_location
12074 Useful as a prefix in a message line. Short for:
12081 @defmac m4_warn (@var{category}, @var{message})
12083 Report @var{message} as a warning (or as an error if requested by the
12084 user) if warnings of the @var{category} are turned on. If the message
12085 is emitted, it is prefixed with the current location, and followed by a
12086 call trace of all macros defined via @code{AC_DEFUN} used to get to the
12089 The @var{category} must be one of:
12093 Warnings about constructs that may interfere with cross-compilation,
12094 such as using @code{AC_RUN_IFELSE} without a default.
12097 Warnings related to the GNU Coding Standards
12098 (@pxref{Top,,, standards, The GNU Coding Standards}).
12102 Warnings about obsolete features. On by default.
12105 Warnings about redefinitions of Autoconf internals.
12108 Warnings about non-portable constructs.
12110 @item portability-recursive
12111 Warnings about recursive Make variable expansions (@code{$(foo$(x))}).
12113 @item extra-portability
12114 Extra warnings about non-portable constructs, covering rarely-used
12118 Warnings about questionable syntactic constructs, incorrectly ordered
12119 macro calls, typos, etc. On by default.
12122 Warnings about unsupported features. On by default.
12125 @strong{Hacking Note:} The set of categories is defined by code in
12126 @command{autom4te}, not by M4sugar itself. Additions should be
12127 coordinated with Automake, so that both sets of tools accept the same
12131 @node Diversion support
12132 @subsection Diversion support
12134 M4sugar makes heavy use of diversions under the hood, because it is
12135 often the case that
12136 text that must appear early in the output is not discovered until late
12137 in the input. Additionally, some of the topological sorting algorithms
12138 used in resolving macro dependencies use diversions. However, most
12139 macros should not need to change diversions directly, but rather rely on
12140 higher-level M4sugar macros to manage diversions transparently. If you
12141 change diversions improperly, you risk generating a syntactically
12142 invalid script, because an incorrect diversion will violate assumptions
12143 made by many macros about whether prerequisite text has been previously
12144 output. In short, if you manually change the diversion, you should not
12145 expect any macros provided by the Autoconf package to work until you
12146 have restored the diversion stack back to its original state.
12148 In the rare case that it is necessary to write a macro that explicitly
12149 outputs text to a different diversion, it is important to be aware of an
12150 M4 limitation regarding diversions: text only goes to a diversion if it
12151 is not part of argument collection. Therefore, any macro that changes
12152 the current diversion cannot be used as an unquoted argument to another
12153 macro, but must be expanded at the top level. The macro
12154 @code{m4_expand} will diagnose any attempt to change diversions, since
12155 it is generally useful only as an argument to another macro. The
12156 following example shows what happens when diversion manipulation is
12157 attempted within macro arguments:
12160 m4_do([normal text]
12161 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
12162 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
12163 @result{}normal text
12168 Notice that the unquoted text @code{unwanted} is output, even though it
12169 was processed while the current diversion was @code{KILL}, because it
12170 was collected as part of the argument to @code{m4_do}. However, the
12171 text @code{discarded} disappeared as desired, because the diversion
12172 changes were single-quoted, and were not expanded until the top-level
12173 rescan of the output of @code{m4_do}.
12175 To make diversion management easier, M4sugar uses the concept of named
12176 diversions. Rather than using diversion numbers directly, it is nicer
12177 to associate a name with each diversion. The diversion number associated
12178 with a particular diversion name is an implementation detail, and a
12179 syntax warning is issued if a diversion number is used instead of a
12180 name. In general, you should not output text
12181 to a named diversion until after calling the appropriate initialization
12182 routine for your language (@code{m4_init}, @code{AS_INIT},
12183 @code{AT_INIT}, @dots{}), although there are some exceptions documented
12186 M4sugar defines two named diversions.
12189 Text written to this diversion is discarded. This is the default
12190 diversion once M4sugar is initialized.
12192 This diversion is used behind the scenes by topological sorting macros,
12193 such as @code{AC_REQUIRE}.
12196 M4sh adds several more named diversions.
12199 This diversion is reserved for the @samp{#!} interpreter line.
12200 @item HEADER-REVISION
12201 This diversion holds text from @code{AC_REVISION}.
12202 @item HEADER-COMMENT
12203 This diversion holds comments about the purpose of a file.
12204 @item HEADER-COPYRIGHT
12205 This diversion is managed by @code{AC_COPYRIGHT}.
12206 @item M4SH-SANITIZE
12207 This diversion contains M4sh sanitization code, used to ensure M4sh is
12208 executing in a reasonable shell environment.
12210 This diversion contains M4sh initialization code, initializing variables
12211 that are required by other M4sh macros.
12213 This diversion contains the body of the shell code, and is the default
12214 diversion once M4sh is initialized.
12217 Autotest inherits diversions from M4sh, and changes the default
12218 diversion from @code{BODY} back to @code{KILL}. It also adds several
12219 more named diversions, with the following subset designed for developer
12222 @item PREPARE_TESTS
12223 This diversion contains initialization sequences which are executed
12224 after @file{atconfig} and @file{atlocal}, and after all command line
12225 arguments have been parsed, but prior to running any tests. It can be
12226 used to set up state that is required across all tests. This diversion
12227 will work even before @code{AT_INIT}.
12230 Autoconf inherits diversions from M4sh, and adds the following named
12231 diversions which developers can utilize.
12234 This diversion contains shell variable assignments to set defaults that
12235 must be in place before arguments are parsed. This diversion is placed
12236 early enough in @file{configure} that it is unsafe to expand any
12237 autoconf macros into this diversion.
12239 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
12240 diversion will be included as part of a quoted here-doc providing all of
12241 the @option{--help} output of @file{configure} related to options
12242 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
12244 This diversion occurs after all command line options have been parsed,
12245 but prior to the main body of the @file{configure} script. This
12246 diversion is the last chance to insert shell code such as variable
12247 assignments or shell function declarations that will used by the
12248 expansion of other macros.
12251 For now, the remaining named diversions of Autoconf, Autoheader, and
12252 Autotest are not documented. In other words,
12253 intentionally outputting text into an undocumented diversion is subject
12254 to breakage in a future release of Autoconf.
12256 @defmac m4_cleardivert (@var{diversion}@dots{})
12257 @msindex{cleardivert}
12258 Permanently discard any text that has been diverted into
12262 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12263 @msindex{divert_once}
12264 Similar to @code{m4_divert_text}, except that @var{content} is only
12265 output to @var{diversion} if this is the first time that
12266 @code{m4_divert_once} has been called with its particular arguments.
12269 @defmac m4_divert_pop (@ovar{diversion})
12270 @msindex{divert_pop}
12271 If provided, check that the current diversion is indeed @var{diversion}.
12272 Then change to the diversion located earlier on the stack, giving an
12273 error if an attempt is made to pop beyond the initial m4sugar diversion
12277 @defmac m4_divert_push (@var{diversion})
12278 @msindex{divert_push}
12279 Remember the former diversion on the diversion stack, and output
12280 subsequent text into @var{diversion}. M4sugar maintains a diversion
12281 stack, and issues an error if there is not a matching pop for every
12285 @anchor{m4_divert_text}
12286 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12287 @msindex{divert_text}
12288 Output @var{content} and a newline into @var{diversion}, without
12289 affecting the current diversion. Shorthand for:
12291 m4_divert_push([@var{diversion}])@var{content}
12292 m4_divert_pop([@var{diversion}])dnl
12295 One use of @code{m4_divert_text} is to develop two related macros, where
12296 macro @samp{MY_A} does the work, but adjusts what work is performed
12297 based on whether the optional macro @samp{MY_B} has also been expanded.
12298 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12299 require that @samp{MY_B} occurs first, if it occurs at all. But this
12300 imposes an ordering restriction on the user; it would be nicer if macros
12301 @samp{MY_A} and @samp{MY_B} can be invoked in either order. The trick
12302 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12303 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12309 if test -n "$b_was_used"; then
12313 [AC_REQUIRE([MY_A])dnl
12314 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12321 Initialize the M4sugar environment, setting up the default named
12322 diversion to be @code{KILL}.
12325 @node Conditional constructs
12326 @subsection Conditional constructs
12328 The following macros provide additional conditional constructs as
12329 convenience wrappers around @code{m4_if}.
12331 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12332 @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12334 The string @var{string} is repeatedly compared against a series of
12335 @var{regex} arguments; if a match is found, the expansion is the
12336 corresponding @var{value}, otherwise, the macro moves on to the next
12337 @var{regex}. If no @var{regex} match, then the result is the optional
12338 @var{default}, or nothing.
12341 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12342 @ovar{regex-2}, @ovar{subst-2}, @dots{})
12343 @msindex{bpatsubsts}
12344 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12347 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12351 The result of the substitution is then passed through the next set of
12352 @var{regex} and @var{subst}, and so forth. An empty @var{subst} implies
12353 deletion of any matched portions in the current string. Note that this
12354 macro over-quotes @var{string}; this behavior is intentional, so that
12355 the result of each step of the recursion remains as a quoted string.
12356 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12357 will line up with the extra quotations, and not the characters of the
12358 original string. The overquoting is removed after the final
12362 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12363 @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12365 Test @var{string} against multiple @var{value} possibilities, resulting
12366 in the first @var{if-value} for a match, or in the optional
12367 @var{default}. This is shorthand for:
12369 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12370 [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12375 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12376 @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12378 This macro was introduced in Autoconf 2.62. Similar to @code{m4_if},
12379 except that each @var{test} is expanded only when it is encountered.
12380 This is useful for short-circuiting expensive tests; while @code{m4_if}
12381 requires all its strings to be expanded up front before doing
12382 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12385 For an example, these two sequences give the same result, but in the
12386 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12387 version only expands @code{m4_index} once, instead of five times, for
12388 faster computation if this is a common case for @samp{$1}. Notice that
12389 every third argument is unquoted for @code{m4_if}, and quoted for
12393 m4_if(m4_index([$1], [\]), [-1], [$2],
12394 m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12395 m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12396 m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12397 m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12399 m4_cond([m4_index([$1], [\])], [-1], [$2],
12400 [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12401 [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12402 [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12403 [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12408 @defmac m4_default (@var{expr-1}, @var{expr-2})
12409 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12410 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12411 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12413 @msindex{default_quoted}
12414 @msindex{default_nblank}
12415 @msindex{default_nblank_quoted}
12416 If @var{expr-1} contains text, use it. Otherwise, select @var{expr-2}.
12417 @code{m4_default} expands the result, while @code{m4_default_quoted}
12418 does not. Useful for providing a fixed default if the expression that
12419 results in @var{expr-1} would otherwise be empty. The difference
12420 between @code{m4_default} and @code{m4_default_nblank} is whether an
12421 argument consisting of just blanks (space, tab, newline) is
12422 significant. When using the expanding versions, note that an argument
12423 may contain text but still expand to an empty string.
12426 m4_define([active], [ACTIVE])dnl
12427 m4_define([empty], [])dnl
12428 m4_define([demo1], [m4_default([$1], [$2])])dnl
12429 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12430 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12431 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12432 demo1([active], [default])
12434 demo1([], [active])
12436 demo1([empty], [text])
12438 -demo1([ ], [active])-
12440 demo2([active], [default])
12442 demo2([], [active])
12444 demo2([empty], [text])
12446 -demo2([ ], [active])-
12448 demo3([active], [default])
12450 demo3([], [active])
12452 demo3([empty], [text])
12454 -demo3([ ], [active])-
12456 demo4([active], [default])
12458 demo4([], [active])
12460 demo4([empty], [text])
12462 -demo4([ ], [active])-
12467 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12468 @msindex{define_default}
12469 If @var{macro} does not already have a definition, then define it to
12470 @var{default-definition}.
12473 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12474 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12477 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12478 then expand @var{if-blank}; otherwise, expand @var{if-text}. Two
12479 variants exist, in order to make it easier to select the correct logical
12480 sense when using only two parameters. Note that this is more efficient
12481 than the equivalent behavior of:
12483 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12487 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12489 This is shorthand for:
12491 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12495 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12497 If @var{macro} is undefined, or is defined as the empty string, expand
12498 to @var{if-false}. Otherwise, expands to @var{if-true}. Similar to:
12500 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12503 except that it is not an error if @var{macro} is undefined.
12506 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12508 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12509 @var{if-false}. This is shorthand for:
12511 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12515 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12517 Similar to @code{m4_ifval}, except guarantee that a newline is present
12518 after any non-empty expansion. Often followed by @code{dnl}.
12521 @defmac m4_n (@var{text})
12523 Expand to @var{text}, and add a newline if @var{text} is not empty.
12524 Often followed by @code{dnl}.
12528 @node Looping constructs
12529 @subsection Looping constructs
12531 The following macros are useful in implementing recursive algorithms in
12532 M4, including loop operations. An M4 list is formed by quoting a list
12533 of quoted elements; generally the lists are comma-separated, although
12534 @code{m4_foreach_w} is whitespace-separated. For example, the list
12535 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12536 It is common to see lists with unquoted elements when those elements are
12537 not likely to be macro names, as in @samp{[fputc_unlocked,
12540 Although not generally recommended, it is possible for quoted lists to
12541 have side effects; all side effects are expanded only once, and prior to
12542 visiting any list element. On the other hand, the fact that unquoted
12543 macros are expanded exactly once means that macros without side effects
12544 can be used to generate lists. For example,
12547 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12550 m4_define([list], [[1], [2], [3]])
12552 m4_foreach([i], [list], [i])
12556 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12558 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12559 If there are too few arguments, the empty string is used. For any
12560 @var{n} besides 1, this is more efficient than the similar
12561 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12564 @defmac m4_car (@var{arg}@dots{})
12566 Expands to the quoted first @var{arg}. Can be used with @code{m4_cdr}
12567 to recursively iterate
12568 through a list. Generally, when using quoted lists of quoted elements,
12569 @code{m4_car} should be called without any extra quotes.
12572 @defmac m4_cdr (@var{arg}@dots{})
12574 Expands to a quoted list of all but the first @var{arg}, or the empty
12575 string if there was only one argument. Generally, when using quoted
12576 lists of quoted elements, @code{m4_cdr} should be called without any
12579 For example, this is a simple implementation of @code{m4_map}; note how
12580 each iteration checks for the end of recursion, then merely applies the
12581 first argument to the first element of the list, then repeats with the
12582 rest of the list. (The actual implementation in M4sugar is a bit more
12583 involved, to gain some speed and share code with @code{m4_map_sep}, and
12584 also to avoid expanding side effects in @samp{$2} twice).
12586 m4_define([m4_map], [m4_ifval([$2],
12587 [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12588 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12593 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12596 Loop over the numeric values between @var{first} and @var{last}
12597 including bounds by increments of @var{step}. For each iteration,
12598 expand @var{expression} with the numeric value assigned to @var{var}.
12599 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12600 on the order of the limits. If given, @var{step} has to match this
12601 order. The number of iterations is determined independently from
12602 definition of @var{var}; iteration cannot be short-circuited or
12603 lengthened by modifying @var{var} from within @var{expression}.
12606 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12608 Loop over the comma-separated M4 list @var{list}, assigning each value
12609 to @var{var}, and expand @var{expression}. The following example
12613 m4_foreach([myvar], [[foo], [bar, baz]],
12617 @result{}echo bar, baz
12620 Note that for some forms of @var{expression}, it may be faster to use
12621 @code{m4_map_args}.
12624 @anchor{m4_foreach_w}
12625 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12626 @msindex{foreach_w}
12627 Loop over the white-space-separated list @var{list}, assigning each value
12628 to @var{var}, and expand @var{expression}. If @var{var} is only
12629 referenced once in @var{expression}, it is more efficient to use
12630 @code{m4_map_args_w}.
12632 The deprecated macro @code{AC_FOREACH} is an alias of
12633 @code{m4_foreach_w}.
12636 @defmac m4_map (@var{macro}, @var{list})
12637 @defmacx m4_mapall (@var{macro}, @var{list})
12638 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12639 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12643 @msindex{mapall_sep}
12644 Loop over the comma separated quoted list of argument descriptions in
12645 @var{list}, and invoke @var{macro} with the arguments. An argument
12646 description is in turn a comma-separated quoted list of quoted elements,
12647 suitable for @code{m4_apply}. The macros @code{m4_map} and
12648 @code{m4_map_sep} ignore empty argument descriptions, while
12649 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12650 arguments. The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12651 additionally expand @var{separator} between invocations of @var{macro}.
12653 Note that @var{separator} is expanded, unlike in @code{m4_join}. When
12654 separating output with commas, this means that the map result can be
12655 used as a series of arguments, by using a single-quoted comma as
12656 @var{separator}, or as a single string, by using a double-quoted comma.
12659 m4_map([m4_count], [])
12661 m4_map([ m4_count], [[],
12665 m4_mapall([ m4_count], [[],
12669 m4_map_sep([m4_eval], [,], [[[1+2]],
12672 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12674 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12676 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12678 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12683 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12685 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12686 argument. In the following example, three solutions are presented with
12687 the same expansion; the solution using @code{m4_map_args} is the most
12690 m4_define([active], [ACTIVE])dnl
12691 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12692 @result{} plain active
12693 m4_map([ m4_echo], [[[plain]], [[active]]])
12694 @result{} plain active
12695 m4_map_args([ m4_echo], [plain], [active])
12696 @result{} plain active
12699 In cases where it is useful to operate on additional parameters besides
12700 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12701 to supply the argument currying necessary to generate the desired
12702 argument list. In the following example, @code{list_add_n} is more
12703 efficient than @code{list_add_x}. On the other hand, using
12704 @code{m4_map_args_sep} can be even more efficient.
12707 m4_define([list], [[1], [2], [3]])dnl
12708 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12709 dnl list_add_n(N, ARG...)
12710 dnl Output a list consisting of each ARG added to N
12711 m4_define([list_add_n],
12712 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12713 list_add_n([1], list)
12715 list_add_n([2], list)
12717 m4_define([list_add_x],
12718 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12719 [,add([$1],m4_defn([var]))]))])dnl
12720 list_add_x([1], list)
12725 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12727 @msindex{map_args_pair}
12728 For every pair of arguments @var{arg}, invoke @var{macro} with two
12729 arguments. If there is an odd number of arguments, invoke
12730 @var{macro-end}, which defaults to @var{macro}, with the remaining
12734 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12736 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12737 @result{}, 2, 1, [3]
12738 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12739 @result{}, 2, 1, 4, 3
12743 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12744 @msindex{map_args_sep}
12745 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12746 argument, additionally expanding @var{sep} between arguments. One
12747 common use of this macro is constructing a macro call, where the opening
12748 and closing parentheses are split between @var{pre} and @var{post}; in
12749 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12750 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}. This
12751 macro provides the most efficient means for iterating over an arbitrary
12752 list of arguments, particularly when repeatedly constructing a macro
12753 call with more arguments than @var{arg}.
12756 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12757 @msindex{map_args_w}
12758 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12759 the whitespace-separated @var{string}, additionally expanding @var{sep}
12760 between words. This macro provides the most efficient means for
12761 iterating over a whitespace-separated string. In particular,
12762 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12763 efficient than @code{m4_foreach_w([var], [@var{string}],
12764 [@var{action}(m4_defn([var]))])}.
12767 @defmac m4_shiftn (@var{count}, @dots{})
12768 @defmacx m4_shift2 (@dots{})
12769 @defmacx m4_shift3 (@dots{})
12773 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12774 along with validation that enough arguments were passed in to match the
12775 shift count, and that the count is positive. @code{m4_shift2} and
12776 @code{m4_shift3} are specializations
12777 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12778 for two and three shifts, respectively.
12781 @defmac m4_stack_foreach (@var{macro}, @var{action})
12782 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12783 @msindex{stack_foreach}
12784 @msindex{stack_foreach_lifo}
12785 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12786 @var{action} with the single argument of a definition of @var{macro}.
12787 @code{m4_stack_foreach} starts with the oldest definition, while
12788 @code{m4_stack_foreach_lifo} starts with the current definition.
12789 @var{action} should not push or pop definitions of @var{macro}, nor is
12790 there any guarantee that the current definition of @var{macro} matches
12791 the argument that was passed to @var{action}. The macro @code{m4_curry}
12792 can be used if @var{action} needs more than one argument, although in
12793 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12795 Due to technical limitations, there are a few low-level m4sugar
12796 functions, such as @code{m4_pushdef}, that cannot be used as the
12797 @var{macro} argument.
12800 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12801 m4_stack_foreach([a], [ m4_incr])
12803 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12808 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12809 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12811 @msindex{stack_foreach_sep}
12812 @msindex{stack_foreach_sep_lifo}
12813 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12814 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12815 @var{sep} between definitions. @code{m4_stack_foreach_sep} visits the
12816 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12817 the current definition first. This macro provides the most efficient
12818 means for iterating over a pushdef stack. In particular,
12819 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12820 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12823 @node Evaluation Macros
12824 @subsection Evaluation Macros
12826 The following macros give some control over the order of the evaluation
12827 by adding or removing levels of quotes.
12829 @defmac m4_apply (@var{macro}, @var{list})
12831 Apply the elements of the quoted, comma-separated @var{list} as the
12832 arguments to @var{macro}. If @var{list} is empty, invoke @var{macro}
12833 without arguments. Note the difference between @code{m4_indir}, which
12834 expects its first argument to be a macro name but can use names that are
12835 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12836 other text, but must end in a valid macro name.
12838 m4_apply([m4_count], [])
12840 m4_apply([m4_count], [[]])
12842 m4_apply([m4_count], [[1], [2]])
12844 m4_apply([m4_join], [[|], [1], [2]])
12849 @defmac m4_count (@var{arg}, @dots{})
12851 This macro returns the number of arguments it was passed.
12854 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12856 This macro performs argument currying. The expansion of this macro is
12857 another macro name that expects exactly one argument; that argument is
12858 then appended to the @var{arg} list, and then @var{macro} is expanded
12859 with the resulting argument list.
12862 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12866 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12867 pass the definition of a builtin macro as the argument to the output of
12868 @code{m4_curry}; the empty string is used instead of the builtin token.
12869 This behavior is rectified by using M4 1.6 or newer.
12872 @defmac m4_do (@var{arg}, @dots{})
12874 This macro loops over its arguments and expands each @var{arg} in
12875 sequence. Its main use is for readability; it allows the use of
12876 indentation and fewer @code{dnl} to result in the same expansion. This
12877 macro guarantees that no expansion will be concatenated with subsequent
12878 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12879 @var{arg@dots{}}))}.
12882 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12885 m4_unquote(m4_join([],[a],[b]))c
12887 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12888 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12891 m4_unquote(m4_join([],[a],[b]))c
12896 @defmac m4_dquote (@var{arg}, @dots{})
12898 Return the arguments as a quoted list of quoted arguments.
12899 Conveniently, if there is just one @var{arg}, this effectively adds a
12903 @defmac m4_dquote_elt (@var{arg}, @dots{})
12904 @msindex{dquote_elt}
12905 Return the arguments as a series of double-quoted arguments. Whereas
12906 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12907 as many arguments as it was passed.
12910 @defmac m4_echo (@var{arg}, @dots{})
12912 Return the arguments, with the same level of quoting. Other than
12913 discarding whitespace after unquoted commas, this macro is a no-op.
12916 @defmac m4_expand (@var{arg})
12918 Return the expansion of @var{arg} as a quoted string. Whereas
12919 @code{m4_quote} is designed to collect expanded text into a single
12920 argument, @code{m4_expand} is designed to perform one level of expansion
12921 on quoted text. One distinction is in the treatment of whitespace
12922 following a comma in the original @var{arg}. Any time multiple
12923 arguments are collected into one with @code{m4_quote}, the M4 argument
12924 collection rules discard the whitespace. However, with @code{m4_expand},
12925 whitespace is preserved, even after the expansion of macros contained in
12926 @var{arg}. Additionally, @code{m4_expand} is able to expand text that
12927 would involve an unterminated comment, whereas expanding that same text
12928 as the argument to @code{m4_quote} runs into difficulty in finding the
12929 end of the argument. Since manipulating diversions during argument
12930 collection is inherently unsafe, @code{m4_expand} issues an error if
12931 @var{arg} attempts to change the current diversion (@pxref{Diversion
12935 m4_define([active], [ACT, IVE])dnl
12936 m4_define([active2], [[ACT, IVE]])dnl
12937 m4_quote(active, active)
12938 @result{}ACT,IVE,ACT,IVE
12939 m4_expand([active, active])
12940 @result{}ACT, IVE, ACT, IVE
12941 m4_quote(active2, active2)
12942 @result{}ACT, IVE,ACT, IVE
12943 m4_expand([active2, active2])
12944 @result{}ACT, IVE, ACT, IVE
12945 m4_expand([# m4_echo])
12947 m4_quote(# m4_echo)
12949 @result{}# m4_echo)
12953 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12954 literal unbalanced quotes, but that quadrigraphs can be used when
12955 unbalanced output is necessary. Likewise, unbalanced parentheses should
12956 be supplied with double quoting or a quadrigraph.
12959 m4_define([pattern], [[!@@<:@@]])dnl
12960 m4_define([bar], [BAR])dnl
12961 m4_expand([case $foo in
12962 m4_defn([pattern])@@:@}@@ bar ;;
12965 @result{}case $foo in
12966 @result{} [![]) BAR ;;
12967 @result{} *) blah ;;
12972 @defmac m4_ignore (@dots{})
12974 This macro was introduced in Autoconf 2.62. Expands to nothing,
12975 ignoring all of its arguments. By itself, this isn't very useful.
12976 However, it can be used to conditionally ignore an arbitrary number of
12977 arguments, by deciding which macro name to apply to a list of arguments.
12979 dnl foo outputs a message only if [debug] is defined.
12981 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12984 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12985 serve the same purpose, although it is less readable.
12988 @defmac m4_make_list (@var{arg}, @dots{})
12989 @msindex{make_list}
12990 This macro exists to aid debugging of M4sugar algorithms. Its net
12991 effect is similar to @code{m4_dquote}---it produces a quoted list of
12992 quoted arguments, for each @var{arg}. The difference is that this
12993 version uses a comma-newline separator instead of just comma, to improve
12994 readability of the list; with the result that it is less efficient than
12997 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12998 m4_dquote(zero, [one], [[two]])
12999 @result{}[0],[one],[[two]]
13000 m4_make_list(zero, [one], [[two]])
13004 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
13006 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
13011 @c m4_noquote is too dangerous to document - it invokes macros that
13012 @c probably rely on @samp{[]} nested quoting for proper operation. The
13013 @c user should generally prefer m4_unquote instead.
13015 @defmac m4_quote (@var{arg}, @dots{})
13017 Return the arguments as a single entity, i.e., wrap them into a pair of
13018 quotes. This effectively collapses multiple arguments into one,
13019 although it loses whitespace after unquoted commas in the process.
13022 @defmac m4_reverse (@var{arg}, @dots{})
13024 Outputs each argument with the same level of quoting, but in reverse
13025 order, and with space following each comma for readability.
13028 m4_define([active], [ACT,IVE])
13030 m4_reverse(active, [active])
13031 @result{}active, IVE, ACT
13035 @defmac m4_unquote (@var{arg}, @dots{})
13037 This macro was introduced in Autoconf 2.62. Expand each argument,
13038 separated by commas. For a single @var{arg}, this effectively removes a
13039 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
13040 than the equivalent @code{m4_do([@var{arg}])}. For multiple arguments,
13041 this results in an unquoted list of expansions. This is commonly used
13042 with @code{m4_split}, in order to convert a single quoted list into a
13043 series of quoted elements.
13046 The following example aims at emphasizing the difference between several
13047 scenarios: not using these macros, using @code{m4_defn}, using
13048 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
13051 $ @kbd{cat example.m4}
13052 dnl Overquote, so that quotes are visible.
13053 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
13054 m4_define([a], [A])
13055 m4_define([mkargs], [1, 2[,] 3])
13056 m4_define([arg1], [[$1]])
13060 show(m4_quote(a, b))
13061 show(m4_dquote(a, b))
13062 show(m4_expand([a, b]))
13066 arg1(m4_defn([mkargs]))
13067 arg1(m4_quote(mkargs))
13068 arg1(m4_dquote(mkargs))
13069 arg1(m4_expand([mkargs]))
13070 $ @kbd{autom4te -l m4sugar example.m4}
13071 $1 = A, $@@ = [A],[b]
13072 $1 = a, b, $@@ = [a, b]
13073 $1 = A,b, $@@ = [A,b]
13074 $1 = [A],[b], $@@ = [[A],[b]]
13075 $1 = A, b, $@@ = [A, b]
13086 @node Text processing Macros
13087 @subsection String manipulation in M4
13089 The following macros may be used to manipulate strings in M4. Many of
13090 the macros in this section intentionally result in quoted strings as
13091 output, rather than subjecting the arguments to further expansions. As
13092 a result, if you are manipulating text that contains active M4
13093 characters, the arguments are passed with single quoting rather than
13096 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
13097 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
13098 @ovar{if-uniq}, @ovar{if-duplicate})
13100 @msindex{append_uniq}
13101 Redefine @var{macro-name} to its former contents with @var{separator}
13102 and @var{string} added at the end. If @var{macro-name} was undefined
13103 before (but not if it was defined but empty), then no @var{separator} is
13104 added. As of Autoconf 2.62, neither @var{string} nor @var{separator}
13105 are expanded during this macro; instead, they are expanded when
13106 @var{macro-name} is invoked.
13108 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
13109 to grow strings without duplicating substrings. Additionally,
13110 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
13111 @var{if-uniq} is expanded if @var{string} was appended, and
13112 @var{if-duplicate} is expanded if @var{string} was already present.
13113 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
13114 occurs within @var{string}, since that can lead to duplicates.
13116 Note that @code{m4_append} can scale linearly in the length of the final
13117 string, depending on the quality of the underlying M4 implementation,
13118 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
13119 If an algorithm can tolerate duplicates in the final string, use the
13120 former for speed. If duplicates must be avoided, consider using
13121 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
13124 m4_define([active], [ACTIVE])dnl
13125 m4_append([sentence], [This is an])dnl
13126 m4_append([sentence], [ active ])dnl
13127 m4_append([sentence], [symbol.])dnl
13129 @result{}This is an ACTIVE symbol.
13130 m4_undefine([active])dnl
13131 @result{}This is an active symbol.
13132 m4_append_uniq([list], [one], [, ], [new], [existing])
13134 m4_append_uniq([list], [one], [, ], [new], [existing])
13136 m4_append_uniq([list], [two], [, ], [new], [existing])
13138 m4_append_uniq([list], [three], [, ], [new], [existing])
13140 m4_append_uniq([list], [two], [, ], [new], [existing])
13143 @result{}one, two, three
13145 @result{}[one],[two],[three]
13146 m4_append([list2], [one], [[, ]])dnl
13147 m4_append_uniq([list2], [two], [[, ]])dnl
13148 m4_append([list2], [three], [[, ]])dnl
13150 @result{}one, two, three
13152 @result{}[one, two, three]
13156 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
13157 @msindex{append_uniq_w}
13158 This macro was introduced in Autoconf 2.62. It is similar to
13159 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
13160 separated list of words to append, and only appends unique words.
13161 @var{macro-name} is updated with a single space between new words.
13163 m4_append_uniq_w([numbers], [1 1 2])dnl
13164 m4_append_uniq_w([numbers], [ 2 3 ])dnl
13170 @defmac m4_chomp (@var{string})
13171 @defmacx m4_chomp_all (@var{string})
13173 @msindex{chomp_all}
13174 Output @var{string} in quotes, but without a trailing newline. The
13175 macro @code{m4_chomp} is slightly faster, and removes at most one
13176 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
13177 newlines. Unlike @code{m4_flatten}, embedded newlines are left intact,
13178 and backslash does not influence the result.
13181 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
13182 @var{suffix-1}, @ovar{suffix-2}, @dots{})
13184 This macro produces a quoted string containing the pairwise combination
13185 of every element of the quoted, comma-separated @var{prefix-list}, and
13186 every element from the @var{suffix} arguments. Each pairwise
13187 combination is joined with @var{infix} in the middle, and successive
13188 pairs are joined by @var{separator}. No expansion occurs on any of the
13189 arguments. No output occurs if either the @var{prefix} or @var{suffix}
13190 list is empty, but the lists can contain empty elements.
13192 m4_define([a], [oops])dnl
13193 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
13194 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
13195 m4_combine([, ], [[a], [b]], [-])
13197 m4_combine([, ], [[a], [b]], [-], [])
13199 m4_combine([, ], [], [-], [1], [2])
13201 m4_combine([, ], [[]], [-], [1], [2])
13206 @defmac m4_escape (@var{string})
13208 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
13209 within @var{string} into their respective quadrigraphs. The result is
13210 still a quoted string.
13213 @defmac m4_flatten (@var{string})
13215 Flatten @var{string} into a single line. Delete all backslash-newline
13216 pairs, and replace all remaining newlines with a space. The result is
13217 still a quoted string.
13220 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
13221 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
13224 Concatenate each @var{arg}, separated by @var{separator}.
13225 @code{joinall} uses every argument, while @code{join} omits empty
13226 arguments so that there are no back-to-back separators in the output.
13227 The result is a quoted string.
13229 m4_define([active], [ACTIVE])dnl
13230 m4_join([|], [one], [], [active], [two])
13231 @result{}one|active|two
13232 m4_joinall([|], [one], [], [active], [two])
13233 @result{}one||active|two
13236 Note that if all you intend to do is join @var{args} with commas between
13237 them, to form a quoted list suitable for @code{m4_foreach}, it is more
13238 efficient to use @code{m4_dquote}.
13241 @defmac m4_newline (@ovar{text})
13243 This macro was introduced in Autoconf 2.62, and expands to a newline,
13244 followed by any @var{text}.
13245 It is primarily useful for maintaining macro formatting, and ensuring
13246 that M4 does not discard leading whitespace during argument collection.
13249 @defmac m4_normalize (@var{string})
13250 @msindex{normalize}
13251 Remove leading and trailing spaces and tabs, sequences of
13252 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13253 with a single space. This is a combination of @code{m4_flatten} and
13254 @code{m4_strip}. To determine if @var{string} consists only of bytes
13255 that would be removed by @code{m4_normalize}, you can use
13259 @defmac m4_re_escape (@var{string})
13260 @msindex{re_escape}
13261 Backslash-escape all characters in @var{string} that are active in
13265 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13266 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13268 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13269 @samp{]}, while keeping white space at the beginning and at the end.
13270 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13271 If @var{string} is empty, the result is an empty list.
13274 @defmac m4_strip (@var{string})
13276 Strip whitespace from @var{string}. Sequences of spaces and tabs are
13277 reduced to a single space, then leading and trailing spaces are removed.
13278 The result is still a quoted string. Note that this does not interfere
13279 with newlines; if you want newlines stripped as well, consider
13280 @code{m4_flatten}, or do it all at once with @code{m4_normalize}. To
13281 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13284 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13286 Add a text box around @var{message}, using @var{frame} as the border
13287 character above and below the message. The @var{frame} argument must be
13288 a single byte, and does not support quadrigraphs.
13289 The frame correctly accounts for
13290 the subsequent expansion of @var{message}. For example:
13292 m4_define([macro], [abc])dnl
13293 m4_text_box([macro])
13299 The @var{message} must contain balanced quotes and parentheses, although
13300 quadrigraphs can be used to work around this.
13303 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13304 @dvarv{prefix1, prefix}, @dvar{width, 79})
13305 @msindex{text_wrap}
13306 Break @var{string} into a series of whitespace-separated words, then
13307 output those words separated by spaces, and wrapping lines any time the
13308 output would exceed @var{width} columns. If given, @var{prefix1} begins
13309 the first line, and @var{prefix} begins all wrapped lines. If
13310 @var{prefix1} is longer than @var{prefix}, then the first line consists
13311 of just @var{prefix1}. If @var{prefix} is longer than @var{prefix1},
13312 padding is inserted so that the first word of @var{string} begins at the
13313 same indentation as all wrapped lines. Note that using literal tab
13314 characters in any of the arguments will interfere with the calculation
13315 of width. No expansions occur on @var{prefix}, @var{prefix1}, or the
13316 words of @var{string}, although quadrigraphs are recognized.
13320 m4_text_wrap([Short string */], [ ], [/* ], [20])
13321 @result{}/* Short string */
13322 m4_text_wrap([Much longer string */], [ ], [/* ], [20])
13323 @result{}/* Much longer
13324 @result{} string */
13325 m4_text_wrap([Short doc.], [ ], [ --short ], [30])
13326 @result{} --short Short doc.
13327 m4_text_wrap([Short doc.], [ ], [ --too-wide ], [30])
13328 @result{} --too-wide
13329 @result{} Short doc.
13330 m4_text_wrap([Super long documentation.], [ ],
13331 [ --too-wide ], 30)
13332 @result{} --too-wide
13333 @result{} Super long
13334 @result{} documentation.
13338 @defmac m4_tolower (@var{string})
13339 @defmacx m4_toupper (@var{string})
13342 Return @var{string} with letters converted to upper or lower case,
13346 @node Number processing Macros
13347 @subsection Arithmetic computation in M4
13349 The following macros facilitate integer arithmetic operations.
13351 Where a parameter is documented as taking an arithmetic expression, you
13352 can use anything that can be parsed by @code{m4_eval}.
13353 Any other numeric parameter should consist of an optional sign followed
13354 by one or more decimal digits; it is treated as a decimal integer.
13356 Macros that expand to a number do so as either @samp{0}, or an optional
13357 @samp{-} followed by a nonzero decimal digit followed by zero or more
13360 Due to @command{m4} limitations, arithmetic expressions and numeric
13361 parameters should use only numbers that fit into a 32-bit signed
13364 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13366 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13367 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13368 equal, and @samp{1} if @var{expr-1} is larger.
13371 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13373 Compare the two M4 lists consisting of comma-separated arithmetic
13374 expressions, left to right. Expand to @samp{-1} for the first element
13375 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13376 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13377 same values. If one list is shorter than the other, the remaining
13378 elements of the longer list are compared against zero.
13380 m4_list_cmp([1, 0], [1])
13382 m4_list_cmp([1, [1 * 0]], [1, 0])
13384 m4_list_cmp([1, 2], [1, 0])
13386 m4_list_cmp([1, [1+1], 3],[1, 2])
13388 m4_list_cmp([1, 2, -3], [1, 2])
13390 m4_list_cmp([1, 0], [1, 2])
13392 m4_list_cmp([1], [1, 2])
13397 @defmac m4_max (@var{arg}, @dots{})
13399 This macro was introduced in Autoconf 2.62. Expand to the value
13400 of the maximum arithmetic expression among all the arguments.
13403 @defmac m4_min (@var{arg}, @dots{})
13405 This macro was introduced in Autoconf 2.62. Expand to the value
13406 of the minimum arithmetic expression among all the arguments.
13409 @defmac m4_sign (@var{expr})
13411 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13412 @samp{1} if it is positive, and @samp{0} if it is zero.
13415 @anchor{m4_version_compare}
13416 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13417 @msindex{version_compare}
13418 This macro was introduced in Autoconf 2.53, but had a number of
13419 usability limitations that were not lifted until Autoconf 2.62. Compare
13420 the version strings @var{version-1} and @var{version-2}, and expand to
13421 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13422 or @samp{1} @var{version-2} is smaller. Version strings must be a list
13423 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13424 element is a number along with optional case-insensitive letters
13425 designating beta releases. The comparison stops at the leftmost element
13426 that contains a difference, although a 0 element compares equal to a
13429 It is permissible to include commit identifiers in @var{version}, such
13430 as an abbreviated SHA1 of the commit, provided there is still a
13431 monotonically increasing prefix to allow for accurate version-based
13432 comparisons. For example, this paragraph was written when the
13433 development snapshot of autoconf claimed to be at version
13434 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13435 abbreviated commit identification of @samp{dc51}.
13438 m4_version_compare([1.1], [2.0])
13440 m4_version_compare([2.0b], [2.0a])
13442 m4_version_compare([1.1.1], [1.1.1a])
13444 m4_version_compare([1.2], [1.1.1a])
13446 m4_version_compare([1.0], [1])
13448 m4_version_compare([1.1pre], [1.1PRE])
13450 m4_version_compare([1.1a], [1,10])
13452 m4_version_compare([2.61a], [2.61a-248-dc51])
13454 m4_version_compare([2.61b], [2.61a-248-dc51])
13459 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13460 @dvar{if-old, m4_fatal})
13461 @msindex{version_prereq}
13462 Compares @var{version} against the version of Autoconf currently
13463 running. If the running version is at @var{version} or newer, expand
13464 @var{if-new-enough}, but if @var{version} is larger than the version
13465 currently executing, expand @var{if-old}, which defaults to printing an
13466 error message and exiting m4sugar with status 63. When given only one
13467 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13468 Remember that the autoconf philosophy favors feature checks over version
13472 @node Set manipulation Macros
13473 @subsection Set manipulation in M4
13474 @cindex Set manipulation
13475 @cindex Data structure, set
13476 @cindex Unordered set manipulation
13478 Sometimes, it is necessary to track a set of data, where the order does
13479 not matter and where there are no duplicates in the set. The following
13480 macros facilitate set manipulations. Each set is an opaque object,
13481 which can only be accessed via these basic operations. The underlying
13482 implementation guarantees linear scaling for set creation, which is more
13483 efficient than using the quadratic @code{m4_append_uniq}. Both set
13484 names and values can be arbitrary strings, except for unbalanced quotes.
13485 This implementation ties up memory for removed elements until the next
13486 operation that must traverse all the elements of a set; and although
13487 that may slow down some operations until the memory for removed elements
13488 is pruned, it still guarantees linear performance.
13490 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13492 Adds the string @var{value} as a member of set @var{set}. Expand
13493 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13494 previously in the set. Operates in amortized constant time, so that set
13495 creation scales linearly.
13498 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13499 @msindex{set_add_all}
13500 Adds each @var{value} to the set @var{set}. This is slightly more
13501 efficient than repeatedly invoking @code{m4_set_add}.
13504 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13506 @msindex{set_contains}
13507 Expands @var{if-present} if the string @var{value} is a member of
13508 @var{set}, otherwise @var{if-absent}.
13511 m4_set_contains([a], [1], [yes], [no])
13513 m4_set_add([a], [1], [added], [dup])
13515 m4_set_add([a], [1], [added], [dup])
13517 m4_set_contains([a], [1], [yes], [no])
13519 m4_set_remove([a], [1], [removed], [missing])
13521 m4_set_contains([a], [1], [yes], [no])
13523 m4_set_remove([a], [1], [removed], [missing])
13528 @defmac m4_set_contents (@var{set}, @ovar{sep})
13529 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13530 @msindex{set_contents}
13532 Expands to a single string consisting of all the members of the set
13533 @var{set}, each separated by @var{sep}, which is not expanded.
13534 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13535 memory occupied by removed elements, while @code{m4_set_dump} is a
13536 faster one-shot action that also deletes the set. No provision is made
13537 for disambiguating members that contain a non-empty @var{sep} as a
13538 substring; use @code{m4_set_empty} to distinguish between an empty set
13539 and the set containing only the empty string. The order of the output
13540 is unspecified; in the current implementation, part of the speed of
13541 @code{m4_set_dump} results from using a different output order than
13542 @code{m4_set_contents}. These macros scale linearly in the size of the
13543 set before memory pruning, and @code{m4_set_contents([@var{set}],
13544 [@var{sep}])} is faster than
13545 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13548 m4_set_add_all([a], [1], [2], [3])
13550 m4_set_contents([a], [-])
13552 m4_joinall([-]m4_set_listc([a]))
13554 m4_set_dump([a], [-])
13556 m4_set_contents([a])
13558 m4_set_add([a], [])
13560 m4_set_contents([a], [-])
13565 @defmac m4_set_delete (@var{set})
13566 @msindex{set_delete}
13567 Delete all elements and memory associated with @var{set}. This is
13568 linear in the set size, and faster than removing one element at a time.
13571 @defmac m4_set_difference (@var{seta}, @var{setb})
13572 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13573 @defmacx m4_set_union (@var{seta}, @var{setb})
13574 @msindex{set_difference}
13575 @msindex{set_intersection}
13576 @msindex{set_union}
13577 Compute the relation between @var{seta} and @var{setb}, and output the
13578 result as a list of quoted arguments without duplicates and with a
13579 leading comma. Set difference selects the elements in @var{seta} but
13580 not @var{setb}, intersection selects only elements in both sets, and
13581 union selects elements in either set. These actions are linear in the
13582 sum of the set sizes. The leading comma is necessary to distinguish
13583 between no elements and the empty string as the only element.
13586 m4_set_add_all([a], [1], [2], [3])
13588 m4_set_add_all([b], [3], [], [4])
13590 m4_set_difference([a], [b])
13592 m4_set_difference([b], [a])
13594 m4_set_intersection([a], [b])
13596 m4_set_union([a], [b])
13601 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13602 @msindex{set_empty}
13603 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13604 expand @var{if-elements}. This macro operates in constant time. Using
13605 this macro can help disambiguate output from @code{m4_set_contents} or
13606 @code{m4_set_list}.
13609 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13610 @msindex{set_foreach}
13611 For each element in the set @var{set}, expand @var{action} with the
13612 macro @var{variable} defined as the set element. Behavior is
13613 unspecified if @var{action} recursively lists the contents of @var{set}
13614 (although listing other sets is acceptable), or if it modifies the set
13615 in any way other than removing the element currently contained in
13616 @var{variable}. This macro is faster than the corresponding
13617 @code{m4_foreach([@var{variable}],
13618 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13619 although @code{m4_set_map} might be faster still.
13622 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13624 m4_set_contents([a])
13626 m4_set_foreach([a], [i],
13627 [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13629 m4_set_contents([a])
13634 @defmac m4_set_list (@var{set})
13635 @defmacx m4_set_listc (@var{set})
13637 @msindex{set_listc}
13638 Produce a list of arguments, where each argument is a quoted element
13639 from the set @var{set}. The variant @code{m4_set_listc} is unambiguous,
13640 by adding a leading comma if there are any set elements, whereas the
13641 variant @code{m4_set_list} cannot distinguish between an empty set and a
13642 set containing only the empty string. These can be directly used in
13643 macros that take multiple arguments, such as @code{m4_join} or
13644 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13645 take a quoted list, such as @code{m4_map} or @code{m4_foreach}. Any
13646 memory occupied by removed elements is reclaimed during these macros.
13649 m4_set_add_all([a], [1], [2], [3])
13657 m4_count(m4_set_list([b]))
13659 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13661 m4_set_add([b], [])
13667 m4_count(m4_set_list([b]))
13669 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13674 @defmac m4_set_map (@var{set}, @var{action})
13676 For each element in the set @var{set}, expand @var{action} with a single
13677 argument of the set element. Behavior is unspecified if @var{action}
13678 recursively lists the contents of @var{set} (although listing other sets
13679 is acceptable), or if it modifies the set in any way other than removing
13680 the element passed as an argument. This macro is faster than either
13681 corresponding counterpart of
13682 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13683 @code{m4_set_foreach([@var{set}], [var],
13684 [@var{action}(m4_defn([var]))])}. It is possible to use @code{m4_curry}
13685 if more than one argument is needed for @var{action}, although it is
13686 more efficient to use @code{m4_set_map_sep} in that case.
13689 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13690 @msindex{set_map_sep}
13691 For each element in the set @var{set}, expand
13692 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13693 between elements. Behavior is unspecified if the expansion recursively
13694 lists the contents of @var{set} (although listing other sets
13695 is acceptable), or if it modifies the set in any way other than removing
13696 the element visited by the expansion. This macro provides the most
13697 efficient means for non-destructively visiting the elements of a set; in
13698 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13699 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13702 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13704 @msindex{set_remove}
13705 If @var{value} is an element in the set @var{set}, then remove it and
13706 expand @var{if-present}. Otherwise expand @var{if-absent}. This macro
13707 operates in constant time so that multiple removals will scale linearly
13708 rather than quadratically; but when used outside of
13709 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13710 until the set is later
13711 compacted by @code{m4_set_contents} or @code{m4_set_list}. Several
13712 other set operations are then less efficient between the time of element
13713 removal and subsequent memory compaction, but still maintain their
13714 guaranteed scaling performance.
13717 @defmac m4_set_size (@var{set})
13719 Expand to the size of the set @var{set}. This implementation operates
13720 in constant time, and is thus more efficient than
13721 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13725 @node Forbidden Patterns
13726 @subsection Forbidden Patterns
13727 @cindex Forbidden patterns
13728 @cindex Patterns, forbidden
13730 M4sugar provides a means to define suspicious patterns, patterns
13731 describing tokens which should not be found in the output. For
13732 instance, if an Autoconf @file{configure} script includes tokens such as
13733 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13734 wrong (typically a macro was not evaluated because of overquotation).
13736 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13737 Additional layers, such as M4sh and Autoconf, add additional forbidden
13738 patterns to the list.
13740 @defmac m4_pattern_forbid (@var{pattern})
13741 @msindex{pattern_forbid}
13742 Declare that no token matching @var{pattern} must be found in the
13743 output. The output file is (temporarily) split into one word per line
13744 as part of the @command{autom4te} post-processing, with each line (and
13745 therefore word) then being checked against the Perl regular expression
13746 @var{pattern}. If the regular expression matches, and
13747 @code{m4_pattern_allow} does not also match, then an error is raised.
13749 Comments are not checked; this can be a problem if, for instance, you
13750 have some macro left unexpanded after an @samp{#include}. No consensus
13751 is currently found in the Autoconf community, as some people consider it
13752 should be valid to name macros in comments (which doesn't make sense to
13753 the authors of this documentation: input, such as macros, should be
13754 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13755 document the output).
13757 As an example, if you define your own macros that begin with @samp{M_}
13758 and are composed from capital letters and underscores, the specification
13759 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13760 are expanded when not used in comments.
13762 As an example of a common use of this macro, consider what happens in
13763 packages that want to use the @command{pkg-config} script via the
13764 third-party @code{PKG_CHECK_MODULES} macro. By default, if a developer
13765 checks out the development tree but has not yet installed the pkg-config
13766 macros locally, they can manage to successfully run @command{autoconf}
13767 on the package, but the resulting @file{configure} file will likely
13768 result in a confusing shell message about a syntax error on the line
13769 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro. On the other hand,
13770 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13771 missing pkg-config macros will be detected immediately without allowing
13772 @command{autoconf} to succeed.
13775 Of course, you might encounter exceptions to these generic rules, for
13776 instance you might have to refer to @samp{$m4_flags}.
13778 @defmac m4_pattern_allow (@var{pattern})
13779 @msindex{pattern_allow}
13780 Any token matching @var{pattern} is allowed, including if it matches an
13781 @code{m4_pattern_forbid} pattern.
13783 For example, Gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13784 @code{gl_} namespace for itself, but also uses
13785 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13789 @node Debugging via autom4te
13790 @section Debugging via autom4te
13791 @cindex debugging tips
13792 @cindex autom4te debugging tips
13793 @cindex m4sugar debugging tips
13794 At times, it is desirable to see what was happening inside m4, to see
13795 why output was not matching expectations. However, post-processing done
13796 by @command{autom4te} means that directly using the m4 builtin
13797 @code{m4_traceon} is likely to interfere with operation. Also, frequent
13798 diversion changes and the concept of forbidden tokens make it difficult
13799 to use @code{m4_defn} to generate inline comments in the final output.
13801 There are a couple of tools to help with this. One is the use of the
13802 @option{--trace} option provided by @command{autom4te} (as well as each
13803 of the programs that wrap @command{autom4te}, such as
13804 @command{autoconf}), in order to inspect when a macro is called and with
13805 which arguments. For example, when this paragraph was written, the
13806 autoconf version could be found by:
13809 $ @kbd{autoconf --trace=AC_INIT}
13810 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13811 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13812 version is 2.63b.95-3963
13815 Another trick is to print out the expansion of various m4 expressions to
13816 standard error or to an independent file, with no further m4 expansion,
13817 and without interfering with diversion changes or the post-processing
13818 done to standard output. @code{m4_errprintn} shows a given expression
13819 on standard error. For example, if you want to see the expansion of an
13820 autoconf primitive or of one of your autoconf macros, you can do it like
13824 $ @kbd{cat <<\EOF > configure.ac}
13826 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13827 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13831 @error{}The definition of AC_DEFINE_UNQUOTED:
13832 @error{}_AC_DEFINE_Q([], $@@)
13835 @node Programming in M4sh
13836 @chapter Programming in M4sh
13838 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13839 scripts. This name was coined by Lars J. Aas, who notes that,
13840 according to the Webster's Revised Unabridged Dictionary (1913):
13843 Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische, mash,
13844 wash, and prob.@: to AS. miscian to mix. See ``Mix''.]
13848 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13852 A mixture of meal or bran and water fed to animals.
13855 A mess; trouble. [Obs.] --Beau.@: & Fl.
13859 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13860 the namespace @samp{^AS_} for M4sh macros. It also reserves the shell
13861 and environment variable namespace @samp{^as_}, and the here-document
13862 delimiter namespace @samp{^_AS[A-Z]} in the output file. You should not
13863 define your own macros or output shell code that conflicts with these
13867 * Common Shell Constructs:: Portability layer for common shell constructs
13868 * Polymorphic Variables:: Support for indirect variable names
13869 * Initialization Macros:: Macros to establish a sane shell environment
13870 * File Descriptor Macros:: File descriptor macros for input and output
13873 @node Common Shell Constructs
13874 @section Common Shell Constructs
13876 M4sh provides portable alternatives for some common shell constructs
13877 that unfortunately are not portable in practice.
13879 @c Deprecated, to be replaced by a better API
13881 @defmac AS_BASENAME (@var{file-name})
13883 Output the non-directory portion of @var{file-name}. For example,
13884 if @code{$file} is @samp{/one/two/three}, the command
13885 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13889 @defmac AS_BOX (@var{text}, @dvar{char, -})
13891 Expand into shell code that will output @var{text} surrounded by a box
13892 with @var{char} in the top and bottom border. @var{text} should not
13893 contain a newline, but may contain shell expansions valid for unquoted
13894 here-documents. @var{char} defaults to @samp{-}, but can be any
13895 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13896 @samp{&}, or @samp{`}. This is useful for outputting a comment box into
13897 log files to separate distinct phases of script operation.
13900 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13901 @dots{}, @ovar{default})
13903 Expand into a shell @samp{case} statement, where @var{word} is matched
13904 against one or more patterns. @var{if-matched} is run if the
13905 corresponding pattern matched @var{word}, else @var{default} is run.
13906 @xref{Prerequisite Macros} for why
13907 this macro should be used instead of plain @samp{case} in code
13908 outside of an @code{AC_DEFUN} macro, when the contents of the
13909 @samp{case} use @code{AC_REQUIRE} directly or indirectly.
13910 @xref{case, , Limitations of Shell Builtins},
13911 for how this macro avoids some portability issues.
13912 @xref{Balancing Parentheses}
13913 for how this macro lets you write code with balanced parentheses
13914 even if your code must run on obsolescent shells.
13917 @c Deprecated, to be replaced by a better API
13918 @defmac AS_DIRNAME (@var{file-name})
13920 Output the directory portion of @var{file-name}. For example,
13921 if @code{$file} is @samp{/one/two/three}, the command
13922 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13924 @code{AS_DIRNAME} was designed long ago when
13925 the @command{dirname} command was not universally supported.
13926 Nowadays one can safely use @code{dir=`dirname -- "$file"`} instead.
13927 This interface may be improved in the future to avoid forks and losing
13931 @defmac AS_ECHO (@var{word})
13933 Emit @var{word} to the standard output, followed by a newline.
13934 The @var{word} must be a single shell word (typically a quoted string).
13935 Output the shell expansion of @var{word} as-is,
13936 even if it starts with @samp{-} or contains @samp{\}.
13937 Redirections can be placed outside the macro invocation.
13939 If the shell variable @var{foo} could contain @samp{\} or leading @samp{-}.
13940 @code{AS_ECHO(["$foo"])} is more portable than @command{echo "$foo"}.
13941 @xref{echo, , Limitations of Shell Builtins}.
13943 Also, @code{AS_ECHO(["$foo"])} is often easier to read than the
13944 @samp{printf '%s\n' "$foo"} that it stands for.
13945 However, because it employs @samp{'} characters,
13946 in contexts where @samp{'} is not allowed
13947 it is better to use @command{printf} directly.
13948 For example, @samp{`eval 'foo=$@{'AS_ESCAPE([[$1]], [`\])'@};printf
13949 "%s\\n" "$foo")'`} would not work if @command{printf} were replaced
13950 with @code{AS_ECHO}.
13954 @defmac AS_ECHO_N (@var{word})
13956 Act like @code{AS_ECHO(@var{word})}, except do not output a following newline.
13959 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13960 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13962 Expands to @var{string}, with any characters in @var{chars} escaped with
13963 a backslash (@samp{\}). @var{chars} should be at most four bytes long,
13964 and only contain characters from the set @samp{`\"$}; however,
13965 characters may be safely listed more than once in @var{chars} for the
13966 sake of syntax highlighting editors. The current implementation expands
13967 @var{string} after adding escapes; if @var{string} contains macro calls
13968 that in turn expand to text needing shell quoting, you can use
13969 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13971 The default for @var{chars} (@samp{\"$`}) is the set of characters
13972 needing escapes when @var{string} will be used literally within double
13973 quotes. One common variant is the set of characters to protect when
13974 @var{string} will be used literally within back-ticks or an unquoted
13975 here-document (@samp{\$`}). Another common variant is @samp{""}, which can
13976 be used to form a double-quoted string containing the same expansions
13977 that would have occurred if @var{string} were expanded in an unquoted
13978 here-document; however, when using this variant, care must be taken that
13979 @var{string} does not use double quotes within complex variable
13980 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13981 with improper escapes.
13983 This macro is often used with @code{AS_ECHO}. For an example, observe
13984 the output generated by the shell code generated from this snippet:
13988 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13989 @result{}"$foo" = "bar"
13990 m4_define([macro], [a, [\b]])
13991 AS_ECHO(["AS_ESCAPE([[macro]])"])
13993 AS_ECHO(["AS_ESCAPE([macro])"])
13995 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13999 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
14000 @comment the case of @var{string} that does not contain '.
14001 To escape a string that will be placed within single quotes, use:
14004 m4_bpatsubst([[@var{string}]], ['], ['\\''])
14008 @defmac AS_EXECUTABLE_P (@var{file})
14009 @asindex{EXECUTABLE_P}
14010 Emit code to probe whether @var{file} is a regular file with executable
14011 permissions (and not a directory with search permissions). The caller
14012 is responsible for quoting @var{file}.
14015 @defmac AS_EXIT (@dvar{status, $?})
14017 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
14019 works around shells that see the exit status of the command prior to
14020 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
14021 of Shell Builtins}).
14024 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
14026 Run shell code @var{test1}. If @var{test1} exits with a zero status then
14027 run shell code @var{run-if-true1}, else examine further tests. If no test
14028 exits with a zero status, run shell code @var{run-if-false}, with
14029 simplifications if either @var{run-if-true1} or @var{run-if-false}
14030 is empty. For example,
14033 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
14034 [test "x$foo" != xno], [HANDLE_FOO([maybe])],
14035 [echo foo not specified])
14039 ensures any required macros of @code{HANDLE_FOO}
14040 are expanded before the first test.
14042 This macro should be used instead of plain @samp{if} in code
14043 outside of an @code{AC_DEFUN} macro, when the contents of the @samp{if}
14044 use @code{AC_REQUIRE} directly or indirectly (@pxref{Prerequisite Macros}).
14047 @defmac AS_MKDIR_P (@var{file-name})
14049 Make the directory @var{file-name}, including intervening directories
14050 as necessary. This is equivalent to @samp{mkdir -p -- @var{file-name}}.
14051 If creation of @var{file-name} fails, exit the script.
14053 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
14056 @defmac AS_SET_STATUS (@var{status})
14057 @asindex{SET_STATUS}
14058 Emit shell code to set the value of @samp{$?} to @var{status}, as
14059 efficiently as possible. However, this is not guaranteed to abort a
14060 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
14061 Builtins}). This should also be used at the end of a complex shell
14062 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
14066 @defmac AS_TR_CPP (@var{expression})
14068 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
14072 # This outputs "#define HAVE_CHAR_P 1".
14073 # Notice the m4 quoting around #, to prevent an m4 comment
14075 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
14079 @defmac AS_TR_SH (@var{expression})
14081 Transform @var{expression} into shell code that generates a valid shell
14082 variable name. The result is literal when possible at m4 time, but must
14083 be used with @code{eval} if @var{expression} causes shell indirections.
14087 # This outputs "Have it!".
14088 header="sys/some file.h"
14089 eval AS_TR_SH([HAVE_$header])=yes
14090 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
14094 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
14095 @asindex{SET_CATFILE}
14096 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
14097 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
14098 @var{file} is absolute, etc.).
14101 @defmac AS_UNSET (@var{var})
14103 Unsets the shell variable @var{var}, working around bugs in older
14104 shells (@pxref{unset, , Limitations of Shell
14105 Builtins}). @var{var} can be a literal or indirect variable name.
14108 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
14109 @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
14110 @asindex{VERSION_COMPARE}
14111 Compare two strings @var{version-1} and @var{version-2}, possibly
14112 containing shell variables, as version strings, and expand
14113 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
14114 depending upon the result.
14115 The algorithm to compare is similar to the one used by strverscmp in
14116 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
14117 The GNU C Library}).
14120 @node Polymorphic Variables
14121 @section Support for indirect variable names
14122 @cindex variable name indirection
14123 @cindex polymorphic variable name
14124 @cindex indirection, variable name
14126 Often, it is convenient to write a macro that will emit shell code
14127 operating on a shell variable. The simplest case is when the variable
14128 name is known. But a more powerful idiom is writing shell code that can
14129 work through an indirection, where another variable or command
14130 substitution produces the name of the variable to actually manipulate.
14131 M4sh supports the notion of polymorphic shell variables, making it easy
14132 to write a macro that can deal with either literal or indirect variable
14133 names and output shell code appropriate for both use cases. Behavior is
14134 undefined if expansion of an indirect variable does not result in a
14135 literal variable name.
14137 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
14138 @dvarv{if-simple-ref, if-not})
14139 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
14140 @ovar{if-not}, @dvarv{if-simple-ref, if-not})
14141 @asindex{LITERAL_IF}
14142 @asindex{LITERAL_WORD_IF}
14143 If the expansion of @var{expression} is definitely a shell literal,
14144 expand @var{if-literal}. If the expansion of @var{expression} looks
14145 like it might contain shell indirections (such as @code{$var} or
14146 @code{`expr`}), then @var{if-not} is expanded. Sometimes, it is
14147 possible to output optimized code if @var{expression} consists only of
14148 shell variable expansions (such as @code{$@{var@}}), in which case
14149 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
14150 should always be safe. @code{AS_LITERAL_WORD_IF} only expands
14151 @var{if-literal} if @var{expression} looks like a single shell word,
14152 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
14153 in @var{expression}.
14155 In order to reduce the time spent recognizing whether an
14156 @var{expression} qualifies as a literal or a simple indirection, the
14157 implementation is somewhat conservative: @var{expression} must be a
14158 single shell word (possibly after stripping whitespace), consisting only
14159 of bytes that would have the same meaning whether unquoted or enclosed
14160 in double quotes (for example, @samp{a.b} results in @var{if-literal},
14161 even though it is not a valid shell variable name; while both @samp{'a'}
14162 and @samp{[$]} result in @var{if-not}, because they behave differently
14163 than @samp{"'a'"} and @samp{"[$]"}). This macro can be used in contexts
14164 for recognizing portable file names (such as in the implementation of
14165 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
14166 valid variable names (such as in the implementation of @code{AS_TR_SH},
14167 which uses an additional @code{m4_translit} to convert @samp{.} to
14170 This example shows how to read the contents of the shell variable
14171 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}. It
14172 results in a script that will output the line @samp{hello} three times.
14175 AC_DEFUN([MY_ACTION],
14176 [AS_LITERAL_IF([$1],
14177 [AS_ECHO(["$$1"])],
14179 [AS_VAR_COPY([var], [$1])
14180 AS_ECHO(["$var"])],
14181 [AS_ECHO(["$'"$1"\"])])])
14184 MY_ACTION([`echo bar`])
14189 @defmac AS_VAR_APPEND (@var{var}, @var{text})
14190 @asindex{VAR_APPEND}
14191 Emit shell code to append the shell expansion of @var{text} to the end
14192 of the current contents of the polymorphic shell variable @var{var},
14193 taking advantage of shells that provide the @samp{+=} extension for more
14196 For situations where the final contents of @var{var} are relatively
14197 short (less than 256 bytes), it is more efficient to use the simpler
14198 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
14199 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
14200 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}). But in the case
14201 when the script will be repeatedly appending text into @code{var},
14202 issues of scaling start to become apparent. A naive implementation
14203 requires execution time linear to the length of the current contents of
14204 @var{var} as well as the length of @var{text} for a single append, for
14205 an overall quadratic scaling with multiple appends. This macro takes
14206 advantage of shells which provide the extension
14207 @code{@var{var}+=@var{text}}, which can provide amortized constant time
14208 for a single append, for an overall linear scaling with multiple
14209 appends. Note that unlike @code{AS_VAR_SET}, this macro requires that
14210 @var{text} be quoted properly to avoid field splitting and file name
14214 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
14215 @asindex{VAR_ARITH}
14216 Emit shell code to compute the arithmetic expansion of @var{expression},
14217 assigning the result as the contents of the polymorphic shell variable
14218 @var{var}. The code takes advantage of shells that provide @samp{$(())}
14219 for fewer forks, but uses @command{expr} as a fallback. Therefore, the
14220 syntax for a valid @var{expression} is rather limited: all operators
14221 must occur as separate shell arguments and with proper quoting;
14222 the only operators supported are @samp{*}, @samp{/}, @samp{%}, binary
14223 @samp{+}, binary @samp{-}, @samp{>}, @samp{>=}, @samp{<}, @samp{<=},
14224 @samp{!=}, @samp{&}, and @samp{|};
14225 all variables containing numbers must be expanded prior to the computation;
14226 the first shell argument must not start with @samp{-};
14227 and each number must be an optional @samp{-} followed by one or more
14228 decimal digits, where the first digit is nonzero if there is more than
14229 one digit. In the following example, this snippet
14230 will print @samp{(2+3)*4 == 20}.
14234 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
14235 echo "(2+$bar)*4 == $foo"
14239 @defmac AS_VAR_COPY (@var{dest}, @var{source})
14241 Emit shell code to assign the contents of the polymorphic shell variable
14242 @var{source} to the polymorphic shell variable @var{dest}. For example,
14243 executing this M4sh snippet will output @samp{bar hi}:
14247 AS_VAR_COPY([a], [foo])
14248 AS_VAR_COPY([b], [$foo])
14252 When it is necessary to access the contents of an indirect variable
14253 inside a shell double-quoted context, the recommended idiom is to first
14254 copy the contents into a temporary literal shell variable.
14257 for header in stdint_h inttypes_h ; do
14258 AS_VAR_COPY([var], [ac_cv_header_$header])
14259 AS_ECHO(["$header detected: $var"])
14264 @comment AS_VAR_GET is intentionally undocumented; it can't handle
14265 @comment trailing newlines uniformly, and forks too much.
14267 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
14268 @ovar{if-not-equal})
14270 Output a shell conditional statement. If the contents of the
14271 polymorphic shell variable @var{var} match the string @var{word},
14272 execute @var{if-equal}; otherwise execute @var{if-not-equal}. @var{word}
14273 must be a single shell word (typically a quoted string). Avoids
14274 shell bugs if an interrupt signal arrives while a command substitution
14275 in @var{var} is being expanded.
14278 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
14279 @defmacx AS_VAR_POPDEF (@var{m4-name})
14280 @asindex{VAR_PUSHDEF}
14281 @asindex{VAR_POPDEF}
14282 @cindex composing variable names
14283 @cindex variable names, composing
14284 A common M4sh idiom involves composing shell variable names from an m4
14285 argument (for example, writing a macro that uses a cache variable).
14286 @var{value} can be an arbitrary string, which will be transliterated
14287 into a valid shell name by @code{AS_TR_SH}. In order to access the
14288 composed variable name based on @var{value}, it is easier to declare a
14289 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14290 that macro as the argument to subsequent @code{AS_VAR} macros as a
14291 polymorphic variable name, and finally free the temporary macro with
14292 @code{AS_VAR_POPDEF}. These macros are often followed with @code{dnl},
14293 to avoid excess newlines in the output.
14295 Here is an involved example, that shows the power of writing macros that
14296 can handle composed shell variable names:
14299 m4_define([MY_CHECK_HEADER],
14300 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14301 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14302 AS_VAR_POPDEF([my_Header])dnl
14304 MY_CHECK_HEADER([stdint.h])
14305 for header in inttypes.h stdlib.h ; do
14306 MY_CHECK_HEADER([$header])
14311 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14312 variable names. In the first invocation, the m4 argument is
14313 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14314 As a result, the temporary macro @code{my_Header} expands to the literal
14315 shell name @samp{ac_cv_header_stdint_h}. In the second invocation, the
14316 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14317 temporary macro @code{my_Header} expands to the indirect shell name
14318 @samp{$as_my_Header}. During the shell execution of the for loop, when
14319 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14320 contains @samp{ac_cv_header_inttypes_h}. If this script is then run on a
14321 platform where all three headers have been previously detected, the
14322 output of the script will include:
14325 header stdint.h detected
14326 header inttypes.h detected
14327 header stdlib.h detected
14331 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14333 Emit shell code to assign the contents of the polymorphic shell variable
14334 @var{var} to the shell expansion of @var{value}. @var{value} is not
14335 subject to field splitting or file name expansion, so if command
14336 substitution is used, it may be done with @samp{`""`} rather than using
14337 an intermediate variable (@pxref{Shell Substitutions}). However,
14338 @var{value} does undergo rescanning for additional macro names; behavior
14339 is unspecified if late expansion results in any shell meta-characters.
14342 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14343 @asindex{VAR_SET_IF}
14344 Emit a shell conditional statement, which executes @var{if-set} if the
14345 polymorphic shell variable @code{var} is set to any value, and
14346 @var{if-undef} otherwise.
14349 @defmac AS_VAR_TEST_SET (@var{var})
14350 @asindex{VAR_TEST_SET}
14351 Emit a shell statement that results in a successful exit status only if
14352 the polymorphic shell variable @code{var} is set.
14355 @node Initialization Macros
14356 @section Initialization Macros
14358 @defmac AS_BOURNE_COMPATIBLE
14359 @asindex{BOURNE_COMPATIBLE}
14360 Set up the shell to be more compatible with the Bourne shell as
14361 standardized by POSIX, if possible. This may involve setting
14362 environment variables, or setting options, or similar
14363 implementation-specific actions. This macro is deprecated, since
14364 @code{AS_INIT} already invokes it.
14371 Initialize the M4sh environment. This macro calls @code{m4_init}, then
14372 outputs the @code{#! /bin/sh} line, a notice about where the output was
14373 generated from, and code to sanitize the environment for the rest of the
14374 script. Among other initializations, this sets @env{SHELL} to the shell
14375 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14376 ensure the C locale. Finally, it changes the current diversion to
14377 @code{BODY}. @code{AS_INIT} is called automatically by @code{AC_INIT}
14378 and @code{AT_INIT}, so shell code in @file{configure},
14379 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14383 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14384 @asindex{INIT_GENERATED}
14385 Emit shell code to start the creation of a subsidiary shell script in
14386 @var{file}, including changing @var{file} to be executable. This macro
14387 populates the child script with information learned from the parent
14388 (thus, the emitted code is equivalent in effect, but more efficient,
14389 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14390 @code{AS_SHELL_SANITIZE}). If present, @var{comment} is output near the
14391 beginning of the child, prior to the shell initialization code, and is
14392 subject to parameter expansion, command substitution, and backslash
14394 parent script should check the exit status after this macro, in case
14395 @var{file} could not be properly created (for example, if the disk was
14396 full). If successfully created, the parent script can then proceed to
14397 append additional M4sh constructs into the child script.
14399 Note that the child script starts life without a log file open, so if
14400 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14401 must temporarily disable any attempts to use the log file until after
14402 emitting code to open a log within the child. On the other hand, if the
14403 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14404 @samp{1}, then the child script already has code that copies stdout to
14405 that descriptor. Currently, the suggested
14406 idiom for writing a M4sh shell script from within another script is:
14409 AS_INIT_GENERATED([@var{file}], [[# My child script.
14410 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14411 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14412 cat >> "@var{file}" <<\__EOF__
14413 # Code to initialize AS_MESSAGE_LOG_FD
14414 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14419 This, however, may change in the future as the M4sh interface is
14420 stabilized further.
14422 Also, be aware that use of @env{LINENO} within the child script may
14423 report line numbers relative to their location in the parent script,
14424 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14425 unable to locate a shell with working @env{LINENO} support.
14428 @defmac AS_LINENO_PREPARE
14429 @asindex{LINENO_PREPARE}
14431 Find a shell that supports the special variable @env{LINENO}, which
14432 contains the number of the currently executing line. This macro is
14433 automatically invoked by @code{AC_INIT} in configure scripts.
14436 @defmac AS_ME_PREPARE
14437 @asindex{ME_PREPARE}
14438 Set up variable @env{as_me} to be the basename of the currently executing
14439 script. This macro is automatically invoked by @code{AC_INIT} in
14443 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14447 Create, as safely as possible, a temporary sub-directory within
14448 @var{dir} with a name starting with @var{prefix}. @var{prefix} should
14449 be 2--4 characters, to make it slightly easier to identify the owner of
14450 the directory. If @var{dir} is omitted, then the value of @env{TMPDIR}
14451 will be used (defaulting to @samp{/tmp}). On success, the name of the
14452 newly created directory is stored in the shell variable @code{tmp}. On
14453 error, the script is aborted.
14455 Typically, this macro is coupled with some exit traps to delete the created
14456 directory and its contents on exit or interrupt. However, there is a
14457 slight window between when the directory is created and when the name is
14458 actually known to the shell, so an interrupt at the right moment might
14459 leave the temporary directory behind. Hence it is important to use a
14460 @var{prefix} that makes it easier to determine if a leftover temporary
14461 directory from an interrupted script is safe to delete.
14463 If you set @code{TMPDIR=$tmp} after invoking this macro, you should
14464 reset @code{TMPDIR} before deleting the created directory, to avoid
14465 breaking commands that rely on @code{$TMPDIR}.
14467 The use of the output variable @samp{$tmp} rather than something in the
14468 @samp{as_} namespace is historical; it has the unfortunate consequence
14469 that reusing this otherwise common name for any other purpose inside
14470 your script has the potential to break any cleanup traps designed to
14471 remove the temporary directory.
14474 @defmac AS_SHELL_SANITIZE
14475 @asindex{SHELL_SANITIZE}
14476 Initialize the shell suitably for @command{configure} scripts. This has
14477 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14478 environment variables for predictable results from configuration tests.
14479 For example, it sets @env{LC_ALL} to change to the default C locale.
14480 @xref{Special Shell Variables}. This macro is deprecated, since
14481 @code{AS_INIT} already invokes it.
14485 @node File Descriptor Macros
14486 @section File Descriptor Macros
14488 @cindex standard input
14489 @cindex file descriptors
14490 @cindex descriptors
14491 @cindex low-level output
14492 @cindex output, low-level
14494 The following macros define file descriptors used to output messages
14495 (or input values) from @file{configure} scripts.
14499 AS_ECHO(["$wombats found"]) >&AS_MESSAGE_LOG_FD
14500 AS_ECHO_N(['Enter desired kangaroo count: ']) >&AS_MESSAGE_FD
14501 read kangaroos <&AS_ORIGINAL_STDIN_FD
14505 However doing so is seldom needed, because Autoconf provides higher
14506 level macros as described below.
14508 @defmac AS_MESSAGE_FD
14509 @asindex{MESSAGE_FD}
14510 The file descriptor for @samp{checking for...} messages and results.
14511 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14512 clients. However, @code{AC_INIT} shuffles things around to another file
14513 descriptor, in order to allow the @option{-q} option of
14514 @command{configure} to choose whether messages should go to the script's
14515 standard output or be discarded.
14517 If you want to display some messages, consider using one of the printing
14518 macros (@pxref{Printing Messages}) instead. Copies of messages output
14519 via these macros are also recorded in @file{config.log}.
14522 @anchor{AS_MESSAGE_LOG_FD}
14523 @defmac AS_MESSAGE_LOG_FD
14524 @asindex{MESSAGE_LOG_FD}
14525 This must either be empty, or expand to a file descriptor for log
14526 messages. By default, @code{AS_INIT} sets this macro to the empty
14527 string for standalone M4sh clients, thus disabling logging. However,
14528 @code{AC_INIT} shuffles things around so that both @command{configure}
14529 and @command{config.status} use @file{config.log} for log messages.
14530 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14531 Compiler}), redirect all output to this descriptor. You may want to do
14532 so if you develop such a low-level macro.
14535 @defmac AS_ORIGINAL_STDIN_FD
14536 @asindex{ORIGINAL_STDIN_FD}
14537 This must expand to a file descriptor for the original standard input.
14538 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14539 M4sh clients. However, @code{AC_INIT} shuffles things around for
14542 When @command{configure} runs, it may accidentally execute an
14543 interactive command that has the same name as the non-interactive meant
14544 to be used or checked. If the standard input was the terminal, such
14545 interactive programs would cause @command{configure} to stop, pending
14546 some user input. Therefore @command{configure} redirects its standard
14547 input from @file{/dev/null} during its initialization. This is not
14548 normally a problem, since @command{configure} normally does not need
14551 In the extreme case where your @file{configure} script really needs to
14552 obtain some values from the original standard input, you can read them
14553 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14557 @c =================================================== Writing Autoconf Macros.
14559 @node Writing Autoconf Macros
14560 @chapter Writing Autoconf Macros
14562 When you write a feature test that could be applicable to more than one
14563 software package, the best thing to do is encapsulate it in a new macro.
14564 Here are some instructions and guidelines for writing Autoconf macros.
14565 You should also familiarize yourself with M4sugar (@pxref{Programming in M4})
14566 and M4sh (@pxref{Programming in M4sh}).
14569 * Macro Definitions:: Basic format of an Autoconf macro
14570 * Macro Names:: What to call your new macros
14571 * Dependencies Between Macros:: What to do when macros depend on other macros
14572 * Obsoleting Macros:: Warning about old ways of doing things
14573 * Coding Style:: Writing Autoconf macros à la Autoconf
14576 @node Macro Definitions
14577 @section Macro Definitions
14579 @defmac AC_DEFUN (@var{name}, @ovar{body})
14581 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14582 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14583 named @var{name} and with @var{body} as its expansion. In addition to
14584 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14585 constrain the order in which macros are called, while avoiding redundant
14586 output (@pxref{Prerequisite Macros}).
14589 An Autoconf macro definition looks like this:
14592 AC_DEFUN(@var{macro-name}, @var{macro-body})
14595 You can refer to any arguments passed to the macro as @samp{$1},
14596 @samp{$2}, etc. @xref{Definitions, , How to define new macros, m4,
14597 GNU M4}, for more complete information on writing M4 macros.
14599 Most macros fall in one of two general categories. The first category
14600 includes macros which take arguments, in order to generate output
14601 parameterized by those arguments. Macros in this category are designed
14602 to be directly expanded, often multiple times, and should not be used as
14603 the argument to @code{AC_REQUIRE}. The other category includes macros
14604 which are shorthand for a fixed block of text, and therefore do not take
14605 arguments. For this category of macros, directly expanding the macro
14606 multiple times results in redundant output, so it is more common to use
14607 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14608 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14610 Be sure to properly quote both the @var{macro-body} @emph{and} the
14611 @var{macro-name} to avoid any problems if the macro happens to have
14612 been previously defined.
14614 Each macro should have a header comment that gives its prototype, and a
14615 brief description. When arguments have default values, display them in
14616 the prototype. For example:
14619 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14620 # --------------------------------------
14621 m4_define([AC_MSG_ERROR],
14622 [@{ AS_MESSAGE([error: $1], [2])
14623 exit m4_default([$2], [1]); @}])
14626 Comments about the macro should be left in the header comment. Most
14627 other comments make their way into @file{configure}, so just keep
14628 using @samp{#} to introduce comments.
14631 If you have some special comments about pure M4 code, comments
14632 that make no sense in @file{configure} and in the header comment, then
14633 use the builtin @code{dnl}: it causes M4 to discard the text
14634 through the next newline.
14636 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14637 @code{dnl} is more useful to get rid of the newlines following macros
14638 that produce no output, such as @code{AC_REQUIRE}.
14640 Public third-party macros need to use @code{AC_DEFUN}, and not
14641 @code{m4_define}, in order to be found by @command{aclocal}
14642 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14643 Additionally, if it is ever determined that a macro should be made
14644 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14645 in order to have @command{autoupdate} assist the user in choosing a
14646 better alternative, but there is no corresponding way to make
14647 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14649 There is another subtle, but important, difference between using
14650 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14651 @code{AC_REQUIRE}. When writing a file, it is always safe to replace a
14652 block of text with a @code{m4_define} macro that will expand to the same
14653 text. But replacing a block of text with an @code{AC_DEFUN} macro with
14654 the same content does not necessarily give the same results, because it
14655 changes the location where any embedded but unsatisfied
14656 @code{AC_REQUIRE} invocations within the block will be expanded. For an
14657 example of this, see @ref{Expanded Before Required}.
14660 @section Macro Names
14662 All of the public Autoconf macros have all-uppercase names in the
14663 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14664 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14665 internal macros. All shell variables that they use for internal
14666 purposes have mostly-lowercase names starting with @samp{ac_}. Autoconf
14667 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}. During
14668 @command{configure}, files produced by Autoconf make heavy use of the
14669 file system namespace @samp{^conf}.
14671 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14672 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14673 of those namespaces (@samp{^_?\(m4\|AS\)_}). And since
14674 @file{configure.ac} is also designed to be scanned by Autoheader,
14675 Autoscan, Autoupdate, and Automake, you should be aware of the
14676 @samp{^_?A[HNUM]_} namespaces. In general, you @emph{should not use}
14677 the namespace of a package that does not own the macro or shell code you
14680 To ensure that your macros don't conflict with present or future
14681 Autoconf macros, you should prefix your own macro names and any shell
14682 variables they use with some other sequence. Possibilities include your
14683 initials, or an abbreviation for the name of your organization or
14684 software package. Historically, people have not always followed the
14685 rule of using a namespace appropriate for their package, and this has
14686 made it difficult for determining the origin of a macro (and where to
14687 report bugs about that macro), as well as difficult for the true
14688 namespace owner to add new macros without interference from pre-existing
14689 uses of third-party macros. Perhaps the best example of this confusion
14690 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14693 Most of the Autoconf macros' names follow a structured naming convention
14694 that indicates the kind of feature check by the name. The macro names
14695 consist of several words, separated by underscores, going from most
14696 general to most specific. The names of their cache variables use the
14697 same convention (@pxref{Cache Variable Names}, for more information on
14700 The first word of the name after the namespace initials (such as
14701 @samp{AC_}) usually tells the category
14702 of the feature being tested. Here are the categories used in Autoconf for
14703 specific test macros, the kind of macro that you are more likely to
14704 write. They are also used for cache variables, in all-lowercase. Use
14705 them where applicable; where they're not, invent your own categories.
14709 C language builtin features.
14711 Declarations of C variables in header files.
14713 Functions in libraries.
14715 POSIX group owners of files.
14721 The base names of programs.
14723 Members of aggregates.
14725 Operating system features.
14727 C builtin or declared types.
14729 C variables in libraries.
14732 After the category comes the name of the particular feature being
14733 tested. Any further words in the macro name indicate particular aspects
14734 of the feature. For example, @code{AC_PROG_MAKE_SET} checks whether
14735 @command{make} sets a variable to its own name.
14737 An internal macro should have a name that starts with an underscore;
14738 Autoconf internals should therefore start with @samp{_AC_}.
14739 Additionally, a macro that is an internal subroutine of another macro
14740 should have a name that starts with an underscore and the name of that
14741 other macro, followed by one or more words saying what the internal
14742 macro does. For example, @code{AC_PATH_X} has internal macros
14743 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14745 @node Dependencies Between Macros
14746 @section Dependencies Between Macros
14747 @cindex Dependencies between macros
14749 Some Autoconf macros depend on other macros having been called first in
14750 order to work correctly. Autoconf provides a way to ensure that certain
14751 macros are called if needed and a way to warn the user if macros are
14752 called in an order that might cause incorrect operation.
14755 * Prerequisite Macros:: Ensuring required information
14756 * Suggested Ordering:: Warning about possible ordering problems
14757 * One-Shot Macros:: Ensuring a macro is called only once
14760 @node Prerequisite Macros
14761 @subsection Prerequisite Macros
14762 @cindex Prerequisite macros
14763 @cindex Macros, prerequisites
14765 A macro that you write might need to use values that have previously
14766 been computed by other macros. For example, @code{AC_DECL_YYTEXT}
14767 examines the output of @code{flex} or @code{lex}, so it depends on
14768 @code{AC_PROG_LEX} having been called first to set the shell variable
14771 Rather than forcing the user of the macros to keep track of the
14772 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14773 it automatically. @code{AC_REQUIRE} can ensure that a macro is only
14774 called if it is needed, and only called once.
14776 @defmac AC_REQUIRE (@var{macro-name})
14778 If the M4 macro @var{macro-name} has not already been called, call it
14779 (without any arguments). Make sure to quote @var{macro-name} with
14780 square brackets. @var{macro-name} must have been defined using
14781 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14782 that it has been called.
14784 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14785 must not be called from the top level. Also, it does not make sense to
14786 require a macro that takes parameters.
14789 @code{AC_REQUIRE} is often misunderstood. It really implements
14790 dependencies between macros in the sense that if one macro depends upon
14791 another, the latter is expanded @emph{before} the body of the
14792 former. To be more precise, the required macro is expanded before
14793 the outermost defined macro in the current expansion stack.
14794 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14795 @code{FOO}. For instance, this definition of macros:
14799 AC_DEFUN([TRAVOLTA],
14800 [test "$body_temperature_in_Celsius" -gt 38 &&
14801 dance_floor=occupied])
14802 AC_DEFUN([NEWTON_JOHN],
14803 [test "x$hair_style" = xcurly &&
14804 dance_floor=occupied])
14808 AC_DEFUN([RESERVE_DANCE_FLOOR],
14809 [if test "x`date +%A`" = xSaturday; then
14810 AC_REQUIRE([TRAVOLTA])
14811 AC_REQUIRE([NEWTON_JOHN])
14817 with this @file{configure.ac}
14820 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14821 RESERVE_DANCE_FLOOR
14822 if test "x$dance_floor" = xoccupied; then
14823 AC_MSG_ERROR([cannot pick up here, let's move])
14828 does not leave you with a better chance to meet a kindred soul on
14829 days other than Saturday, since the call to @code{RESERVE_DANCE_FLOOR}
14834 test "$body_temperature_in_Celsius" -gt 38 &&
14835 dance_floor=occupied
14836 test "x$hair_style" = xcurly &&
14837 dance_floor=occupied
14838 if test "x`date +%A`" = xSaturday; then
14845 This behavior was chosen on purpose: (i) it prevents messages in
14846 required macros from interrupting the messages in the requiring macros;
14847 (ii) it avoids bad surprises when shell conditionals are used, as in:
14852 AC_REQUIRE([SOME_CHECK])
14859 However, this implementation can lead to another class of problems.
14860 Consider the case where an outer macro first expands, then indirectly
14861 requires, an inner macro:
14864 AC_DEFUN([TESTA], [[echo in A
14865 if test -n "$SEEN_A" ; then echo duplicate ; fi
14867 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14868 if test -z "$SEEN_A" ; then echo bug ; fi]])
14869 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14870 AC_DEFUN([OUTER], [[echo in OUTER]
14877 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14878 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14879 of @code{OUTER}, but because @code{TESTA} had already been directly
14880 expanded, it failed to hoist @code{TESTA}. Therefore, the expansion of
14881 @code{TESTB} occurs prior to its prerequisites, leading to the following
14893 Newer Autoconf is smart enough to recognize this situation, and hoists
14894 @code{TESTA} even though it has already been expanded, but issues a
14895 syntax warning in the process. This is because the hoisted expansion of
14896 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14897 redundant code, and causes its own set of problems if the hoisted macro
14909 The bug is not in Autoconf, but in the macro definitions. If you ever
14910 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14911 that the macro only needs to be expanded once. But to enforce this,
14912 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14913 this only helps in Autoconf 2.64 or newer), or all
14914 uses of that macro should be through @code{AC_REQUIRE}; directly
14915 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14916 eliminate redundant expansion. In the example, this rule of thumb was
14917 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14918 directly expands it. One way of fixing the bug is to factor
14919 @code{TESTA} into two macros, the portion designed for direct and
14920 repeated use (here, named @code{TESTA}), and the portion designed for
14921 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14922 @code{TESTA_PREREQ}). Then, by fixing all clients to use the correct
14923 calling convention according to their needs:
14926 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14927 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14928 if test -n "$SEEN_A" ; then echo duplicate ; fi
14930 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14931 if test -z "$SEEN_A" ; then echo bug ; fi]])
14932 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14933 AC_DEFUN([OUTER], [[echo in OUTER]
14940 the resulting output will then obey all dependency rules and avoid any
14941 syntax warnings, whether the script is built with old or new Autoconf
14952 You can use the helper macros @code{AS_IF} and @code{AS_CASE} in
14953 top-level code to enforce expansion of required macros outside of shell
14954 conditional constructs; these helpers are not needed in the bodies of
14955 macros defined by @code{AC_DEFUN}.
14956 You are furthermore encouraged, although not required, to
14957 put all @code{AC_REQUIRE} calls
14958 at the beginning of a macro. You can use @code{dnl} to avoid the empty
14961 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14962 macro that has not been defined. However, the @command{aclocal} tool
14963 relies on parsing an incomplete set of input files to trace which macros
14964 have been required, in order to then pull in additional files that
14965 provide those macros; for this particular use case, pre-defining the
14966 macro @code{m4_require_silent_probe} will avoid the warnings.
14968 @node Suggested Ordering
14969 @subsection Suggested Ordering
14970 @cindex Macros, ordering
14971 @cindex Ordering macros
14973 Some macros should be run before another macro if both are called, but
14974 neither @emph{requires} that the other be called. For example, a macro
14975 that changes the behavior of the C compiler should be called before any
14976 macros that run the C compiler. Many of these dependencies are noted in
14979 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14980 with this kind of dependency appear out of order in a
14981 @file{configure.ac} file. The warning occurs when creating
14982 @command{configure} from @file{configure.ac}, not when running
14983 @command{configure}.
14985 For example, @code{AC_PROG_CPP} checks whether the C compiler
14986 can run the C preprocessor when given the @option{-E} option. It should
14987 therefore be called after any macros that change which C compiler is
14988 being used, such as @code{AC_PROG_CC}. So @code{AC_PROG_CC} contains:
14991 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14995 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14996 when @code{AC_PROG_CC} is called.
14998 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
15000 Make M4 print a warning message to the standard error output if
15001 @var{called-macro-name} has already been called. @var{this-macro-name}
15002 should be the name of the macro that is calling @code{AC_BEFORE}. The
15003 macro @var{called-macro-name} must have been defined using
15004 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
15005 that it has been called.
15008 @node One-Shot Macros
15009 @subsection One-Shot Macros
15010 @cindex One-shot macros
15011 @cindex Macros, called once
15013 Some macros should be called only once, either because calling them
15014 multiple time is unsafe, or because it is bad style. For instance
15015 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
15016 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
15017 sense to run these expensive checks more than once. Such one-shot
15018 macros can be defined using @code{AC_DEFUN_ONCE}.
15020 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
15021 @acindex{DEFUN_ONCE}
15022 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
15023 Definitions}), but add additional logic that guarantees that only the
15024 first use of the macro (whether by direct expansion or
15025 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
15026 expansion will occur before the start of any enclosing macro defined by
15027 @code{AC_DEFUN}. Subsequent expansions are silently ignored.
15028 Generally, it does not make sense for @var{macro-body} to use parameters
15032 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
15033 emit a warning if it was directly expanded a second time, so for
15034 portability, it is better to use @code{AC_REQUIRE} than direct
15035 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
15036 (@pxref{Prerequisite Macros}).
15038 @node Obsoleting Macros
15039 @section Obsoleting Macros
15040 @cindex Obsoleting macros
15041 @cindex Macros, obsoleting
15043 Configuration and portability technology has evolved over the years.
15044 Often better ways of solving a particular problem are developed, or
15045 ad-hoc approaches are systematized. This process has occurred in many
15046 parts of Autoconf. One result is that some of the macros are now
15047 considered @dfn{obsolete}; they still work, but are no longer considered
15048 the best thing to do, hence they should be replaced with more modern
15049 macros. Ideally, @command{autoupdate} should replace the old macro calls
15050 with their modern implementation.
15052 Autoconf provides a simple means to obsolete a macro.
15055 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message}, @ovar{silent})
15057 Define @var{old-macro} as @var{implementation}, just like
15058 @code{AC_DEFUN}, but also declare @var{old-macro} to be obsolete.
15059 When @command{autoupdate} is run, occurrences of @var{old-macro} will
15060 be replaced by the text of @var{implementation} in the updated
15061 @file{configure.ac} file.
15063 If a simple textual replacement is not enough to finish the job of
15064 updating a @file{configure.ac} to modern style, provide instructions for
15065 whatever additional manual work is required as @var{message}. These
15066 instructions will be printed by @command{autoupdate}, and embedded in the
15067 updated @file{configure.ac} file, next to the text of @var{implementation}.
15069 Normally, @command{autoconf} will also issue a warning (in the
15070 ``obsolete'' category) when it expands @var{old-macro}. This warning
15071 does not include @var{message}; it only advises the maintainer to run
15072 @command{autoupdate}. If it is inappropriate to issue this warning, set
15073 the @var{silent} argument to the word @code{silent}. One might want to
15074 use a silent @code{AU_DEFUN} when @var{old-macro} is used in a
15075 widely-distributed third-party macro. If that macro's maintainers are
15076 aware of the need to update their code, it's unnecessary to nag all
15077 of the transitive users of @var{old-macro} as well. This capability
15078 was added to @code{AU_DEFUN} in Autoconf 2.70; older versions of
15079 autoconf will ignore the @var{silent} argument and issue the warning
15082 @strong{Caution:} If @var{implementation} contains M4 or M4sugar macros,
15083 they will be evaluated when @command{autoupdate} is run, not emitted
15084 verbatim like the rest of @var{implementation}. This cannot be avoided
15085 with extra quotation, because then @var{old-macro} will not work when
15086 it is called normally. See the definition of @code{AC_FOREACH} in
15087 @file{general.m4} for a workaround.
15090 @defmac AU_ALIAS (@var{old-name}, @var{new-name}, @ovar{silent})
15092 A shorthand version of @code{AU_DEFUN}, to be used when a macro has
15093 simply been renamed. @command{autoupdate} will replace calls to
15094 @var{old-name} with calls to @var{new-name}, keeping any arguments
15095 intact. No instructions for additional manual work will be printed.
15097 The @var{silent} argument works the same as the @var{silent} argument
15098 to @code{AU_DEFUN}. It was added to @code{AU_ALIAS} in Autoconf 2.70.
15100 @strong{Caution:} @code{AU_ALIAS} cannot be used when @var{new-name} is
15101 an M4 or M4sugar macro. See above.
15105 @section Coding Style
15106 @cindex Coding style
15108 The Autoconf macros follow a strict coding style. You are encouraged to
15109 follow this style, especially if you intend to distribute your macro,
15110 either by contributing it to Autoconf itself or the
15111 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
15112 Archive}, or by other means.
15114 The first requirement is to pay great attention to the quotation. For
15115 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
15117 Do not try to invent new interfaces. It is likely that there is a macro
15118 in Autoconf that resembles the macro you are defining: try to stick to
15119 this existing interface (order of arguments, default values, etc.). We
15120 @emph{are} conscious that some of these interfaces are not perfect;
15121 nevertheless, when harmless, homogeneity should be preferred over
15124 Be careful about clashes both between M4 symbols and between shell
15127 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
15128 you are unlikely to generate conflicts. Nevertheless, when you need to
15129 set a special value, @emph{avoid using a regular macro name}; rather,
15130 use an ``impossible'' name. For instance, up to version 2.13, the macro
15131 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
15132 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
15133 But since there is a macro named @code{AC_SUBST_FILE}, it was just
15134 impossible to @samp{AC_SUBST(FILE)}! In this case,
15135 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
15136 have been used (yes, with the parentheses).
15137 @c or better yet, high-level macros such as @code{m4_expand_once}
15139 No Autoconf macro should ever enter the user-variable name space; i.e.,
15140 except for the variables that are the actual result of running the
15141 macro, all shell variables should start with @code{ac_}. In
15142 addition, small macros or any macro that is likely to be embedded in
15143 other macros should be careful not to use obvious names.
15146 Do not use @code{dnl} to introduce comments: most of the comments you
15147 are likely to write are either header comments which are not output
15148 anyway, or comments that should make their way into @file{configure}.
15149 There are exceptional cases where you do want to comment special M4
15150 constructs, in which case @code{dnl} is right, but keep in mind that it
15153 M4 ignores the leading blanks and newlines before each argument.
15154 Use this feature to
15155 indent in such a way that arguments are (more or less) aligned with the
15156 opening parenthesis of the macro being called. For instance, instead of
15159 AC_CACHE_CHECK(for EMX OS/2 environment,
15161 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
15162 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
15169 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15170 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15171 [ac_cv_emxos2=yes],
15172 [ac_cv_emxos2=no])])
15179 AC_CACHE_CHECK([for EMX OS/2 environment],
15181 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
15182 [return __EMX__;])],
15183 [ac_cv_emxos2=yes],
15184 [ac_cv_emxos2=no])])
15187 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
15188 cross-compiling, provide a pessimistic value (typically @samp{no}).
15190 Feel free to use various tricks to prevent auxiliary tools, such as
15191 syntax-highlighting editors, from behaving improperly. For instance,
15195 m4_bpatsubst([$1], [$"])
15202 m4_bpatsubst([$1], [$""])
15206 so that Emacsen do not open an endless ``string'' at the first quote.
15207 For the same reasons, avoid:
15217 test $[@@%:@@] != 0
15221 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
15222 breaking the bracket-matching highlighting from Emacsen. Note the
15223 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc. Do
15224 not escape when it is unnecessary. Common examples of useless quotation
15225 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
15228 When using @command{sed}, don't use @option{-e} except for indenting
15229 purposes. With the @code{s} and @code{y} commands, the preferred
15230 separator is @samp{/} unless @samp{/} itself might appear in the pattern
15231 or replacement, in which case you should use @samp{|}, or optionally
15232 @samp{,} if you know the pattern and replacement cannot contain a file
15233 name. If none of these characters will do, choose a printable character
15234 that cannot appear in the pattern or replacement. Characters from the
15235 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
15236 replacement might contain a file name, since they have special meaning
15237 to the shell and are less likely to occur in file names.
15239 @xref{Macro Definitions}, for details on how to define a macro. If a
15240 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
15241 of an @code{AC_REQUIRE} directive, and macros required by other macros
15242 inside arguments do not need to be expanded before this macro, then
15243 use @code{m4_define}. In case of doubt, use @code{AC_DEFUN}.
15244 Also take into account that public third-party macros need to use
15245 @code{AC_DEFUN} in order to be found by @command{aclocal}
15246 (@pxref{Extending aclocal,,, automake, GNU Automake}).
15247 All the @code{AC_REQUIRE} statements should be at the beginning of the
15248 macro, and each statement should be followed by @code{dnl}.
15250 You should not rely on the number of arguments: instead of checking
15251 whether an argument is missing, test that it is not empty. It provides
15252 both a simpler and a more predictable interface to the user, and saves
15253 room for further arguments.
15255 Unless the macro is short, try to leave the closing @samp{])} at the
15256 beginning of a line, followed by a comment that repeats the name of the
15257 macro being defined. This introduces an additional newline in
15258 @command{configure}; normally, that is not a problem, but if you want to
15259 remove it you can use @samp{[]dnl} on the last line. You can similarly
15260 use @samp{[]dnl} after a macro call to remove its newline. @samp{[]dnl}
15261 is recommended instead of @samp{dnl} to ensure that M4 does not
15262 interpret the @samp{dnl} as being attached to the preceding text or
15263 macro output. For example, instead of:
15266 AC_DEFUN([AC_PATH_X],
15267 [AC_MSG_CHECKING([for X])
15269 @r{# @dots{}omitted@dots{}}
15270 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15278 AC_DEFUN([AC_PATH_X],
15279 [AC_REQUIRE_CPP()[]dnl
15280 AC_MSG_CHECKING([for X])
15281 @r{# @dots{}omitted@dots{}}
15282 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15287 If the macro is long, try to split it into logical chunks. Typically,
15288 macros that check for a bug in a function and prepare its
15289 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15290 this setup. Do not hesitate to introduce auxiliary macros to factor
15293 In order to highlight the recommended coding style, here is a macro
15294 written the old way:
15297 dnl Check for EMX on OS/2.
15299 AC_DEFUN(_AC_EMXOS2,
15300 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15301 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15302 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15303 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15312 # Check for EMX on OS/2.
15313 m4_define([_AC_EMXOS2],
15314 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15315 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15316 [ac_cv_emxos2=yes],
15317 [ac_cv_emxos2=no])])
15318 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15325 @c ============================================= Portable Shell Programming
15327 @node Portable Shell
15328 @chapter Portable Shell Programming
15329 @cindex Portable shell programming
15331 When writing your own checks, there are some shell-script programming
15332 techniques you should avoid in order to make your code portable. The
15333 Bourne shell and upward-compatible shells like the Korn shell and Bash
15334 have evolved over the years, and many features added to the original
15335 System7 shell are now supported on all interesting porting targets.
15336 However, the following discussion between Russ Allbery and Robert Lipe
15343 The GNU assumption that @command{/bin/sh} is the one and only shell
15344 leads to a permanent deadlock. Vendors don't want to break users'
15345 existing shell scripts, and there are some corner cases in the Bourne
15346 shell that are not completely compatible with a POSIX shell. Thus,
15347 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15348 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15356 This is exactly the problem. While most (at least most System V's) do
15357 have a Bourne shell that accepts shell functions most vendor
15358 @command{/bin/sh} programs are not the POSIX shell.
15360 So while most modern systems do have a shell @emph{somewhere} that meets the
15361 POSIX standard, the challenge is to find it.
15364 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15365 is to find such a shell. But to prevent trouble, if you're not using
15366 M4sh you should not take advantage of features that were added after Unix
15367 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15368 negated character classes, or even @command{unset}. @code{#} comments,
15369 while not in Unix version 7, were retrofitted in the original Bourne
15370 shell and can be assumed to be part of the least common denominator.
15372 On the other hand, if you're using M4sh you can assume that the shell
15373 has the features that were added in SVR2 (circa 1984), including shell
15375 @command{return}, @command{unset}, and I/O redirection for builtins. For
15376 more information, refer to @uref{https://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15377 However, some pitfalls have to be avoided for portable use of these
15378 constructs; these will be documented in the rest of this chapter.
15379 See in particular @ref{Shell Functions} and @ref{Limitations of
15380 Builtins, , Limitations of Shell Builtins}.
15382 The set of external programs you should run in a @command{configure} script
15383 is fairly small. @xref{Utilities in Makefiles, , Utilities in
15384 Makefiles, standards, The GNU Coding Standards}, for the list. This
15385 restriction allows users to start out with a fairly small set of
15386 programs and build the rest, avoiding too many interdependencies between
15389 Some of these external utilities have a portable subset of features; see
15390 @ref{Limitations of Usual Tools}.
15392 There are other sources of documentation about shells. The
15393 specification for the POSIX
15394 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/V3_chap02.html,
15395 Shell Command Language}, though more generous than the restrictive shell
15396 subset described above, is fairly portable nowadays. Also please see
15397 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15400 * Systemology:: A zoology of operating systems
15401 * Shellology:: A zoology of shells
15402 * Invoking the Shell:: Invoking the shell as a command
15403 * Here-Documents:: Quirks and tricks
15404 * File Descriptors:: FDs and redirections
15405 * Signal Handling:: Shells, signals, and headaches
15406 * File System Conventions:: File names
15407 * Shell Pattern Matching:: Pattern matching
15408 * Shell Substitutions:: Variable and command expansions
15409 * Assignments:: Varying side effects of assignments
15410 * Parentheses:: Parentheses in shell scripts
15411 * Special Shell Variables:: Variables you should not change
15412 * Shell Functions:: What to look out for if you use them
15413 * Limitations of Builtins:: Portable use of not so portable /bin/sh
15414 * Limitations of Usual Tools:: Portable use of portable tools
15419 @section Systemology
15420 @cindex Systemology
15422 This section aims at presenting some systems and pointers to
15423 documentation. It may help you addressing particular problems reported
15426 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX-conforming
15427 systems} are derived from the
15428 @uref{https://@/en.wikipedia.org/@/wiki/@/Unix, Unix operating system}.
15430 The @uref{https://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
15431 contains a table correlating the features of various POSIX-conforming
15432 systems. @uref{https://@/www.levenez.com/@/unix/, Unix History} is a
15433 simplified diagram of how many Unix systems were derived from each
15436 @uref{https://@/heirloom.sourceforge.net/, The Heirloom Project}
15437 provides some variants of traditional implementations of Unix utilities.
15444 Darwin is a partially proprietary operating system maintained by Apple
15445 Computer and used by most of their products. It is also known as macOS,
15446 iOS, etc.@: depending on the exact variant. Older versions were called
15449 By default the file system will be case insensitive, albeit case
15450 preserving. This can cause nasty problems: for instance, the
15451 installation attempt for a package having an @file{INSTALL} file can
15452 result in @samp{make install} reporting that nothing is to be done!
15454 Darwin does support case-sensitive file systems, but they must be
15455 formatted specially as such, and Apple discourages use of a
15456 case-sensitive volume for the base operating system. To build software
15457 that expects case-sensitive filenames, it is best to create a separate
15458 disk volume or disk image formatted as case sensitive; this can be done
15459 using the @command{diskutil} command or the Disk Utility application.
15463 @c FIXME: Please, if you feel like writing something more precise,
15464 @c it'd be great. In particular, I can't understand the difference with
15466 QNX is a realtime operating system running on Intel architecture
15467 meant to be scalable from the small embedded systems to the hundred
15468 processor super-computer. It claims to be POSIX certified. More
15469 information is available on the
15470 @uref{https://@/blackberry.qnx.com/@/en, QNX home page}.
15472 @item Unix version 7
15473 @cindex Unix version 7
15475 Officially this was called the ``Seventh Edition'' of ``the UNIX
15476 time-sharing system'' but we use the more-common name ``Unix version 7''.
15477 Documentation is available in the
15478 @uref{https://@/s3.amazonaws.com/@/plan9-bell-labs/@/7thEdMan/@/index.html,
15479 Unix Seventh Edition Manual}.
15480 Previous versions of Unix are called ``Unix version 6'', etc., but
15481 they were not as widely used.
15486 @section Shellology
15489 There are several families of shells, most prominently the Bourne family
15490 and the C shell family which are deeply incompatible. If you want to
15491 write portable shell scripts, avoid members of the C shell family. The
15492 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15493 Shell difference FAQ} includes a small history of POSIX shells, and a
15494 comparison between several of them.
15496 Below we describe some of the members of the Bourne shell family.
15501 Ash is often used on GNU/Linux and BSD
15502 systems as a light-weight Bourne-compatible shell. Ash 0.2 has some
15503 bugs that are fixed in the 0.3.x series, but portable shell scripts
15504 should work around them, since version 0.2 is still shipped with many
15505 GNU/Linux distributions.
15507 To be compatible with Ash 0.2:
15511 don't use @samp{$?} after expanding empty or unset variables,
15512 or at the start of an @command{eval}:
15518 echo "Do not use it: $?"
15520 eval 'echo "Do not use it: $?"'
15524 don't use command substitution within variable expansion:
15531 beware that single builtin substitutions are not performed by a
15532 subshell, hence their effect applies to the current shell! @xref{Shell
15533 Substitutions}, item ``Command Substitution''.
15538 To detect whether you are running Bash, test whether
15539 @code{BASH_VERSION} is set. To require
15540 POSIX compatibility, run @samp{set -o posix}. @xref{Bash POSIX
15541 Mode, , Bash POSIX Mode, bash, The GNU Bash Reference
15542 Manual}, for details.
15544 @item Bash 2.05 and later
15545 @cindex Bash 2.05 and later
15546 Versions 2.05 and later of Bash use a different format for the
15547 output of the @command{set} builtin, designed to make evaluating its
15548 output easier. However, this output is not compatible with earlier
15549 versions of Bash (or with many other shells, probably). So if
15550 you use Bash 2.05 or higher to execute @command{configure},
15551 you'll need to use Bash 2.05 for all other build tasks as well.
15556 @prindex @samp{ksh}
15557 @prindex @samp{ksh88}
15558 @prindex @samp{ksh93}
15559 The Korn shell is compatible with the Bourne family and it mostly
15560 conforms to POSIX. It has two major variants commonly
15561 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15562 release. It is usually called @command{ksh}, but is called @command{sh}
15563 on some hosts if you set your path appropriately.
15565 On Solaris 11, @command{/bin/sh} and @command{/usr/bin/ksh} are both
15566 @samp{ksh93}. On Solaris 10 and earlier, @command{/bin/sh} is a
15567 pre-POSIX Bourne shell and the Korn shell is found elsewhere:
15568 @prindex @command{/usr/bin/ksh} on Solaris
15569 @command{/usr/bin/ksh} is @samp{ksh88} on Solaris 10,
15570 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15571 @command{/usr/xpg4/bin/sh} is a POSIX-compliant variant of
15572 @samp{ksh88} on Solaris 10 and later,
15573 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15574 and @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15575 Variants that are not standard may be parts of optional
15576 packages. There is no extra charge for these packages, but they are
15577 not part of a minimal OS install and therefore some installations may
15581 @prindex @samp{pdksh}
15582 A public-domain clone of the Korn shell called @command{pdksh} is widely
15583 available: it has most of the @samp{ksh88} features along with a few of
15584 its own. It usually sets @code{KSH_VERSION}, except if invoked as
15585 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15586 POSIX compatibility by running @samp{set -o posix}. Unfortunately, with
15587 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15588 POSIX mode is buggy and causes @command{pdksh} to depart from POSIX in
15589 at least one respect, see @ref{Shell Substitutions}.
15593 To detect whether you are running @command{zsh}, test whether
15594 @code{ZSH_VERSION} is set. By default @command{zsh} is @emph{not}
15595 compatible with the Bourne shell: you must execute @samp{emulate sh},
15596 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15597 set @code{NULLCMD} to @samp{:}. @xref{Compatibility, , Compatibility,
15598 zsh, The Z Shell Manual}, for details.
15600 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15601 Bash in Mac OS X 10.2 (2002) and changed back to Zsh in macOS 10.15 (2019).
15604 @node Invoking the Shell
15605 @section Invoking the Shell
15606 @cindex invoking the shell
15607 @cindex shell invocation
15609 The Korn shell (up to at least version M-12/28/93d) has a bug when
15610 invoked on a file whose name does not contain a slash. It first
15611 searches for the file's name in @env{PATH}, and if found it executes
15612 that rather than the original file. For example, assuming there is a
15613 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15614 command in the following example fails because the Korn shell finds
15615 @file{/usr/bin/script} and refuses to execute it as a shell script:
15618 $ @kbd{touch xxyzzyz script}
15619 $ @kbd{ksh xxyzzyz}
15620 $ @kbd{ksh ./script}
15622 ksh: script: cannot execute
15625 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15626 option-argument ends in backslash-newline, Bash incorrectly reports a
15627 syntax error. The problem does not occur if a character follows the
15631 $ @kbd{$ bash -c 'echo foo \}
15633 bash: -c: line 2: syntax error: unexpected end of file
15634 $ @kbd{bash -c 'echo foo \}
15640 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15642 @node Here-Documents
15643 @section Here-Documents
15644 @cindex Here-documents
15645 @cindex Shell here-documents
15647 Because unquoted here-documents are subject to parameter expansion and
15648 command substitution, the characters @samp{$} and @samp{`} are special
15649 in unquoted here-documents and should be escaped by @samp{\} if you want
15650 them as-is. Also, @samp{\} is special if it precedes @samp{$},
15651 @samp{`}, newline or @samp{\} itself, so @samp{\} should be doubled if
15652 it appears before these characters and you want it as-is.
15654 Using command substitutions in a here-document that is fed to a shell
15655 function is not portable. For example, with Solaris 10 @command{/bin/sh}:
15658 $ @kbd{kitty () @{ cat; @}}
15662 /tmp/sh199886: cannot open
15667 Some shells mishandle large here-documents: for example,
15668 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 POSIX shell, which are
15669 derived from Korn shell version M-12/28/93d, mishandle braced variable
15670 expansion that crosses a 1024- or 4096-byte buffer boundary
15671 within a here-document. Only the part of the variable name after the boundary
15672 is used. For example, @code{$@{variable@}} could be replaced by the expansion
15673 of @code{$@{ble@}}. If the end of the variable name is aligned with the block
15674 boundary, the shell reports an error, as if you used @code{$@{@}}.
15675 Instead of @code{$@{variable-default@}}, the shell may expand
15676 @code{$@{riable-default@}}, or even @code{$@{fault@}}. This bug can often
15677 be worked around by omitting the braces: @code{$variable}. The bug was
15679 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15680 still shipping older versions with the bug.
15682 Empty here-documents are not portable either; with the following code,
15683 @command{zsh} up to at least version 4.3.10 creates a file with a single
15684 newline, whereas other shells create an empty file:
15691 Many shells (including the Bourne shell) implement here-documents
15692 inefficiently. In particular, some shells can be extremely inefficient when
15693 a single statement contains many here-documents. For instance if your
15694 @file{configure.ac} includes something like:
15698 AS_IF([<cross_compiling>],
15699 [assume this and that],
15702 check something else
15709 A shell parses the whole @code{if}/@code{fi} construct generated by
15710 @code{AS_IF}, creating
15711 temporary files for each here-document in it. Some shells create links
15712 for such here-documents on every @code{fork}, so that the clean-up code
15713 they had installed correctly removes them. It is creating the links
15714 that can take the shell forever.
15716 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15717 @code{if}/@code{fi} constructs, would improve the performance
15718 significantly. Anyway, this kind of construct is not exactly the
15719 typical use of Autoconf. In fact, it's even not recommended, because M4
15720 macros can't look into shell conditionals, so we may fail to expand a
15721 macro when it was expanded before in a conditional path, and the
15722 condition turned out to be false at runtime, and we end up not
15723 executing the macro at all.
15725 Be careful with the use of @samp{<<-} to unindent here-documents. The
15726 behavior is only portable for stripping leading @key{TAB}s, and things
15727 can silently break if an overzealous editor converts to using leading
15728 spaces (not all shells are nice enough to warn about unterminated
15732 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15736 $ @kbd{printf 'cat <<-x\n 1\n 2\n x\n' | bash-3.2 && echo done}
15743 @node File Descriptors
15744 @section File Descriptors
15745 @cindex Descriptors
15746 @cindex File descriptors
15747 @cindex Shell file descriptors
15749 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15750 stderr, even for subshells. This might result in undesirable content
15751 if you meant to capture the standard-error output of the inner command:
15754 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15756 + eval echo foo >&2
15759 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15761 + eval 'echo foo >&2'
15764 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15765 @i{# Traces on startup files deleted here.}
15767 +zsh:1> eval echo foo >&2
15773 One workaround is to grep out uninteresting lines, hoping not to remove
15776 If you intend to redirect both standard error and standard output,
15777 redirect standard output first. This works better with HP-UX,
15778 since its shell mishandles tracing if standard error is redirected
15782 $ @kbd{sh -x -c ': 2>err >out'}
15784 + 2> err $ @kbd{cat err}
15788 Don't try to redirect the standard error of a command substitution. It
15789 must be done @emph{inside} the command substitution. When running
15790 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15791 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15793 On the other hand, some shells, such as Solaris or FreeBSD
15794 @command{/bin/sh}, warn about missing programs before performing
15795 redirections. Therefore, to silently check whether a program exists, it
15796 is necessary to perform redirections on a subshell or brace group:
15798 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15800 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15801 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15802 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15805 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15808 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15809 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15811 Some shells, like @command{ash}, don't recognize bi-directional
15812 redirection (@samp{<>}). And even on shells that recognize it, it is
15813 not portable to use on fifos: POSIX does not require read-write support
15814 for named pipes, and Cygwin does not support it:
15817 $ @kbd{mkfifo fifo}
15818 $ @kbd{exec 5<>fifo}
15819 $ @kbd{echo hi >&5}
15820 bash: echo: write error: Communication error on send
15824 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15825 regular files when using @samp{<>}:
15828 $ @kbd{echo a > file}
15829 $ @kbd{bash -c ': 1<>file'; cat file}
15831 $ @kbd{dash -c ': 1<>file'; cat file}
15835 Solaris 10 @code{/bin/sh} executes redirected compound commands
15836 in a subshell, while other shells don't:
15839 $ @kbd{/bin/sh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15841 $ @kbd{ksh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15843 $ @kbd{bash -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15847 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15848 (even if it is redirected) in a loop after the first iteration, or in a
15849 shell function after the first call:
15852 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15855 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15861 As a workaround, @command{echo} or @command{eval} can be used.
15863 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15864 subsidiary program. If any of these descriptors is closed, the
15865 operating system may open an unspecified file for the descriptor in the
15866 new process image. POSIX 2008 says this may be done only if the
15867 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15868 it even for ordinary programs, and the next version of POSIX will allow
15871 If you want a file descriptor above 2 to be inherited into a child
15872 process, then you must use redirections specific to that command or a
15873 containing subshell or command group, rather than relying on
15874 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15875 @command{sh}, file descriptors above 2 which are opened using
15876 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15877 that involved in the fork-and-exec which runs a program or script):
15880 $ @kbd{echo 'echo hello >&5' >k}
15881 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15883 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15885 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15886 ./k[1]: 5: cannot open [Bad file number]
15887 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15889 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15891 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15895 Don't rely on duplicating a closed file descriptor to cause an
15896 error. With Solaris 10 @command{/bin/sh}, failed duplication is silently
15897 ignored, which can cause unintended leaks to the original file
15898 descriptor. In this example, observe the leak to standard output:
15901 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15902 bash: 3: Bad file descriptor
15904 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15909 Fortunately, an attempt to close an already closed file descriptor will
15910 portably succeed. Likewise, it is safe to use either style of
15911 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15912 even if it doesn't match the read/write mode that the file descriptor
15915 DOS variants cannot rename or remove open files, such as in
15916 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15917 perfectly portable among POSIX hosts.
15919 A few ancient systems reserved some file descriptors. By convention,
15920 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15921 Eighth Edition (1985) through Tenth Edition Unix (1989). File
15922 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15923 1990), though we don't now remember what it was. Both these systems are
15924 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15925 other file descriptors.
15927 On the other hand, you can't portably use multi-digit file descriptors.
15928 @command{dash} and Solaris @command{ksh} don't understand any file
15929 descriptor larger than @samp{9}:
15932 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15934 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15936 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15937 ksh[1]: exec: 10: not found
15939 $ @kbd{dash -c 'exec 9>&-'; echo $?}
15941 $ @kbd{dash -c 'exec 10>&-'; echo $?}
15942 exec: 1: 10: not found
15946 @c <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15947 @node Signal Handling
15948 @section Signal Handling
15949 @cindex Signal handling in the shell
15950 @cindex Signals, shells and
15952 Portable handling of signals within the shell is another major source of
15953 headaches. This is worsened by the fact that various different, mutually
15954 incompatible approaches are possible in this area, each with its
15955 distinctive merits and demerits. A detailed description of these possible
15956 approaches, as well as of their pros and cons, can be found in
15957 @uref{https://www.cons.org/cracauer/sigint.html, this article}.
15959 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15960 the shell still exits with error upon termination by one of those signals,
15961 but in such a case the exit status might be somewhat unexpected (even if
15962 allowed by POSIX, strictly speaking):
15963 @c FIXME: We had a reference for this behavior but the website no longer
15964 @c exists and the page is not in the Internet Archive. --zw 2020-07-10.
15967 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15970 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15973 $ @kbd{for sig in 1 2 3 15; do}
15974 > @kbd{ echo $sig:}
15975 > @kbd{ /bin/sh -c "kill -$s \$\$"; echo $?}
15988 This gets even worse if one is using the POSIX ``wait'' interface to get
15989 details about the shell process terminations: it will result in the shell
15990 having exited normally, rather than by receiving a signal.
15993 $ @kbd{cat > foo.c <<'END'}
15994 #include <stdio.h> /* for printf */
15995 #include <stdlib.h> /* for system */
15996 #include <sys/wait.h> /* for WIF* macros */
15999 int status = system ("kill -15 $$");
16000 printf ("Terminated by signal: %s\n",
16001 WIFSIGNALED (status) ? "yes" : "no");
16002 printf ("Exited normally: %s\n",
16003 WIFEXITED (status) ? "yes" : "no");
16008 $ @kbd{cc -o foo foo.c}
16009 $ @kbd{./a.out} # On GNU/Linux
16010 Terminated by signal: no
16011 Exited normally: yes
16012 $ @kbd{./a.out} # On Solaris 10
16013 Terminated by signal: yes
16014 Exited normally: no
16017 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
16018 if it is not blocked, and even if the shell is not running interactively
16019 (in fact, even if the shell has no attached tty); among these shells
16020 are at least Bash (from version 2 onward), Zsh 4.3.12, Solaris 10
16021 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
16022 Still, @code{SIGQUIT} seems to be trappable quite portably within all
16023 these shells. OTOH, some other shells doesn't special-case the handling
16024 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
16025 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
16027 Some shells (especially Korn shells and derivatives) might try to
16028 propagate to themselves a signal that has killed a child process; this is
16029 not a bug, but a conscious design choice (although its overall value might
16030 be debatable). The exact details of how this is attained vary from shell
16031 to shell. For example, upon running @code{perl -e 'kill 2, $$'}, after
16032 the perl process has been interrupted, AT&T @code{ksh93} (2011) will
16033 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
16034 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
16035 128 + 2). In any case, if there is an active trap associated with
16036 @code{SIGINT}, those shells will correctly execute it.
16038 @c See: <https://www.austingroupbugs.net/view.php?id=51>
16039 Some Korn shells, when a child process die due receiving a signal with
16040 signal number @var{n}, can leave in @samp{$?} an exit status of
16041 256+@var{n} instead of the more common 128+@var{n}. Observe the
16042 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
16046 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
16047 /bin/ksh: line 1: 7837: Hangup
16049 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
16050 /bin/bash: line 1: 7861 Hangup (sh -c "kill -1 \$\$")
16055 This @command{ksh} behavior is allowed by POSIX, if implemented with
16056 due care; see this @uref{https://www.austingroupbugs.net/view.php?id=51,
16057 Austin Group discussion} for more background. However, if it is not
16058 implemented with proper care, such a behavior might cause problems
16059 in some corner cases. To see why, assume we have a ``wrapper'' script
16064 # Ignore some signals in the shell only, not in its child processes.
16066 wrapped_command "$@@"
16073 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
16074 has signal number 1), @code{ret} will be set to 257. Unless the
16075 @command{exit} shell builtin is smart enough to understand that such
16076 a value can only have originated from a signal, and adjust the final
16077 wait status of the shell appropriately, the value 257 will just get
16078 truncated to 1 by the closing @code{exit} call, so that a caller of
16079 the script will have no way to determine that termination by a signal
16080 was involved. Observe the different behavior of AT&T @code{ksh93}
16081 (2011) and @code{bash} 4.1.5 on Debian:
16090 $ @kbd{/bin/ksh foo.sh; echo $?}
16091 foo.sh: line 2: 12479: Hangup
16094 $ @kbd{/bin/bash foo.sh; echo $?}
16095 foo.sh: line 2: 12487 Hangup (sh -c 'kill -1 $$')
16100 @node File System Conventions
16101 @section File System Conventions
16102 @cindex File system conventions
16104 Autoconf uses shell-script processing extensively, so the file names
16105 that it processes should not contain characters that are special to the
16106 shell. Special characters include space, tab, newline, NUL, and
16110 " # $ & ' ( ) * ; < = > ? [ \ ` |
16113 Also, file names should not begin with @samp{~} or @samp{-}, and should
16114 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
16115 immediately after @samp{:}. On POSIX-like platforms, directory names
16116 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
16119 These restrictions apply not only to the files that you distribute, but
16120 also to the absolute file names of your source, build, and destination
16123 On some POSIX-like platforms, @samp{!} and @samp{^} are special too, so
16124 they should be avoided.
16126 POSIX lets implementations treat leading @file{//} specially, but
16127 requires leading @file{///} and beyond to be equivalent to @file{/}.
16128 Most Unix variants treat @file{//} like @file{/}. However, some treat
16129 @file{//} as a ``super-root'' that can provide access to files that are
16130 not otherwise reachable from @file{/}. The super-root tradition began
16131 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
16134 While @command{autoconf} and friends are usually run on some POSIX
16135 variety, they can be used on other systems, most notably DOS
16136 variants. This impacts several assumptions regarding file names.
16139 For example, the following code:
16146 foo_dir=$dots$foo_dir ;;
16151 fails to properly detect absolute file names on those systems, because
16152 they can use a drivespec, and usually use a backslash as directory
16153 separator. If you want to be portable to DOS variants (at the
16154 price of rejecting valid but oddball POSIX file names like @file{a:\b}),
16155 you can check for absolute file names like this:
16157 @cindex absolute file names, detect
16160 [\\/]* | ?:[\\/]* ) # Absolute
16163 foo_dir=$dots$foo_dir ;;
16168 Make sure you quote the brackets if appropriate and keep the backslash as
16169 first character. @xref{case, , Limitations of Shell Builtins}.
16171 Also, because the colon is used as part of a drivespec, these systems don't
16172 use it as path separator. When creating or accessing paths, you can use the
16173 @code{PATH_SEPARATOR} output variable instead. @command{configure} sets this
16174 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
16177 File names need extra care as well. While DOS variants
16178 that are POSIXy enough to run @command{autoconf} (such as DJGPP)
16179 are usually able to handle long file names properly, there are still
16180 limitations that can seriously break packages. Several of these issues
16181 can be easily detected by the
16182 @uref{https://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
16185 A short overview follows; problems are marked with SFN/LFN to
16186 indicate where they apply: SFN means the issues are only relevant to
16187 plain DOS, not to DOS under Microsoft Windows
16188 variants, while LFN identifies problems that exist even under
16189 Microsoft Windows variants.
16192 @item No multiple dots (SFN)
16193 DOS cannot handle multiple dots in file names. This is an especially
16194 important thing to remember when building a portable configure script,
16195 as @command{autoconf} uses a .in suffix for template files.
16197 This is perfectly OK on POSIX variants:
16200 AC_CONFIG_HEADERS([config.h])
16201 AC_CONFIG_FILES([source.c foo.bar])
16206 but it causes problems on DOS, as it requires @samp{config.h.in},
16207 @samp{source.c.in} and @samp{foo.bar.in}. To make your package more portable
16208 to DOS-based environments, you should use this instead:
16211 AC_CONFIG_HEADERS([config.h:config.hin])
16212 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
16216 @item No leading dot (SFN)
16217 DOS cannot handle file names that start with a dot. This is usually
16218 not important for @command{autoconf}.
16220 @item Case insensitivity (LFN)
16221 DOS is case insensitive, so you cannot, for example, have both a
16222 file called @samp{INSTALL} and a directory called @samp{install}. This
16223 also affects @command{make}; if there's a file called @samp{INSTALL} in
16224 the directory, @samp{make install} does nothing (unless the
16225 @samp{install} target is marked as PHONY).
16227 @item The 8+3 limit (SFN)
16228 Because the DOS file system only stores the first 8 characters of
16229 the file name and the first 3 of the extension, those must be unique.
16230 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
16231 @file{foobar-prettybird.c} all resolve to the same file name
16232 (@file{FOOBAR-P.C}). The same goes for @file{foo.bar} and
16233 @file{foo.bartender}.
16235 The 8+3 limit is not usually a problem under Microsoft Windows, as it
16237 tails in the short version of file names to make them unique. However, a
16238 registry setting can turn this behavior off. While this makes it
16239 possible to share file trees containing long file names between SFN
16240 and LFN environments, it also means the above problem applies there
16243 @item Invalid characters (LFN)
16244 Some characters are invalid in DOS file names, and should therefore
16245 be avoided. In a LFN environment, these are @samp{/}, @samp{\},
16246 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
16247 In a SFN environment, other characters are also invalid. These
16248 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
16250 @item Invalid names (LFN)
16251 Some DOS file names are reserved, and cause problems if you
16252 try to use files with those names. These names include @file{CON},
16253 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
16254 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
16255 File names are case insensitive, so even names like
16256 @file{aux/config.guess} are disallowed.
16260 @node Shell Pattern Matching
16261 @section Shell Pattern Matching
16262 @cindex Shell pattern matching
16264 Nowadays portable patterns can use negated character classes like
16265 @samp{[!-aeiou]}. The older syntax @samp{[^-aeiou]} is supported by
16266 some shells but not others; hence portable scripts should never use
16267 @samp{^} as the first character of a bracket pattern.
16269 Outside the C locale, patterns like @samp{[a-z]} are problematic since
16270 they may match characters that are not lower-case letters.
16272 @node Shell Substitutions
16273 @section Shell Substitutions
16274 @cindex Shell substitutions
16276 Contrary to a persistent urban legend, the Bourne shell does not
16277 systematically split variables and back-quoted expressions, in particular
16278 on the right-hand side of assignments and in the argument of @code{case}.
16279 For instance, the following code:
16282 case "$given_srcdir" in
16283 .) top_srcdir="`printf '%s\n' "$dots" | sed 's|/$||'`" ;;
16284 *) top_srcdir="$dots$given_srcdir" ;;
16289 is more readable when written as:
16292 case $given_srcdir in
16293 .) top_srcdir=`printf '%s\n' "$dots" | sed 's|/$||'` ;;
16294 *) top_srcdir=$dots$given_srcdir ;;
16299 and in fact it is even @emph{more} portable: in the first case of the
16300 first attempt, the computation of @code{top_srcdir} is not portable,
16301 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16302 for example Solaris 10 @command{ksh}:
16305 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16306 ksh: : cannot execute
16307 ksh: bar | sed 's, ,,': cannot execute
16311 POSIX does not specify behavior for this sequence. On the other hand,
16312 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by POSIX,
16313 but in practice, not all shells understand it the same way: pdksh 5.2.14
16314 prints spurious quotes when in POSIX mode:
16317 $ @kbd{echo "`echo \"hello\"`"}
16319 $ @kbd{set -o posix}
16320 $ @kbd{echo "`echo \"hello\"`"}
16325 There is just no portable way to use double-quoted strings inside
16326 double-quoted back-quoted expressions (pfew!).
16328 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16329 parameter expansions are elided during word splitting. Meanwhile, zsh
16330 does not perform word splitting except when in Bourne compatibility
16331 mode. In the example below, the correct behavior is to have five
16332 arguments to the function, and exactly two spaces on either side of the
16333 middle @samp{-}, since word splitting collapses multiple spaces in
16334 @samp{$f} but leaves empty arguments intact.
16337 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16339 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16341 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16343 $ @kbd{zsh -c 'emulate sh;}
16344 > @kbd{n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16349 You can work around this by doing manual word splitting, such as using
16350 @samp{"$str" $list} rather than @samp{"$str"$list}.
16352 There are also portability pitfalls with particular expansions:
16356 @cindex @code{"$@@"}
16357 Autoconf macros often use the @command{set} command to update
16358 @samp{$@@}, so if you are writing shell code intended for
16359 @command{configure} you should not assume that the value of @samp{$@@}
16360 persists for any length of time.
16362 You may see usages like @samp{$@{1+"$@@"@}} in older shell scripts
16363 designed to work around a portability problem in ancient shells.
16364 Unfortunately this runs afoul of bugs in more-recent shells, and
16365 nowadays it is better to use plain @samp{"$@@"} instead.
16367 The portability problem with ancient shells was significant.
16368 When there are no positional arguments @samp{"$@@"} should be discarded,
16369 but the original Unix version 7 Bourne shell mistakenly treated it as
16370 equivalent to @samp{""} instead, and many ancient shells followed its lead.
16372 For many years shell scripts worked around this portability problem by
16373 using @samp{$@{1+"$@@"@}} instead of @samp{"$@@"}, and you may see this
16374 usage in older scripts. Unfortunately, @samp{$@{1+"$@@"@}} does not
16375 work with @command{ksh93} M 93t+ (2009) as shipped in AIX 7.2 (2015),
16376 as this shell drops a trailing empty argument:
16379 $ @kbd{set a b c ""}
16380 $ @kbd{set $@{1+"$@@"@}}
16385 Also, @samp{$@{1+"$@@"@}} does not work with Zsh 4.2.6 (2005) and
16386 earlier, as shipped in Mac OS X releases before 10.5, as this old Zsh
16387 incorrectly word splits the result:
16390 zsh $ @kbd{emulate sh}
16391 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16394 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16400 To work around these problems Autoconf does two things. First, in the
16401 shell code that it generates Autoconf avoids @samp{"$@@"} if it is
16402 possible that there may be no positional arguments. You can use this
16403 workaround in your own code, too, if you want it to be portable to
16404 ancient shells. For example, instead of:
16407 cat conftest.c "$@@"
16414 0) cat conftest.c;;
16415 *) cat conftest.c "$@@";;
16420 Second, Autoconf-generated @command{configure} scripts work around most
16421 of the old Zsh problem by using Zsh's ``global aliases'' to convert
16422 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16425 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16428 This workaround is for the benefit of any instances of
16429 @samp{$@{1+"$@@"@}} in user-written code appearing in
16430 @command{configure} scripts. However, it is not a complete solution, as
16431 Zsh recognizes the alias only when a shell word matches it exactly,
16432 which means older Zsh still mishandles more-complicated cases like
16433 @samp{"foo"$@{1+"$@@"@}}.
16436 @cindex positional parameters
16437 The 10th, 11th, @dots{} positional parameters can be accessed only after
16438 a @code{shift}. The 7th Edition shell reported an error if given
16439 @code{$@{10@}}, and
16440 Solaris 10 @command{/bin/sh} still acts that way:
16443 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16444 $ @kbd{echo $@{10@}}
16448 Conversely, not all shells obey the POSIX rule that when braces are
16449 omitted, multiple digits beyond a @samp{$} imply the single-digit
16450 positional parameter expansion concatenated with the remaining literal
16451 digits. To work around the issue, you must use braces.
16454 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16456 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16460 @item $@{@var{var}-@var{value}@}
16461 @itemx $@{@var{var}:-@var{value}@}
16462 @itemx $@{@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 @cindex @code{$@{@var{var}-@var{value}@}}
16469 @cindex @code{$@{@var{var}=@var{value}@}}
16470 @cindex @code{$@{@var{var}?@var{value}@}}
16471 @cindex @code{$@{@var{var}+@var{value}@}}
16472 @c Info cannot handle ':' in index entries.
16474 @cindex @code{$@{@var{var}:-@var{value}@}}
16475 @cindex @code{$@{@var{var}:=@var{value}@}}
16476 @cindex @code{$@{@var{var}:?@var{value}@}}
16477 @cindex @code{$@{@var{var}:+@var{value}@}}
16479 When using @samp{$@{@var{var}-@var{value}@}} or
16480 similar notations that modify a parameter expansion,
16481 POSIX requires that @var{value} must be a single shell word,
16482 which can contain quoted strings but cannot contain unquoted spaces.
16483 If this requirement is not met Solaris 10 @command{/bin/sh}
16484 sometimes complains, and anyway the behavior is not portable.
16487 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16488 /bin/sh: bad substitution
16489 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16491 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16493 $ @kbd{/bin/sh -c 'cat <<EOF
16499 Most shells treat the special parameters @code{*} and @code{@@} as being
16500 unset if there are no positional parameters. However, some shells treat
16501 them as being set to the empty string. POSIX does not clearly specify
16505 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16507 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16511 According to POSIX, if an expansion occurs inside double quotes, then
16512 the use of unquoted double quotes within @var{value} is unspecified, and
16513 any single quotes become literal characters; in that case, escaping must
16514 be done with backslash. Likewise, the use of unquoted here-documents is
16515 a case where double quotes have unspecified results:
16518 $ @kbd{/bin/sh -c 'echo "$@{a-"b c"@}"'}
16519 /bin/sh: bad substitution
16520 $ @kbd{ksh -c 'echo "$@{a-"b c"@}"'}
16522 $ @kbd{bash -c 'echo "$@{a-"b c"@}"'}
16524 $ @kbd{/bin/sh -c 'a=; 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 'cat <<EOF
16536 $ @kbd{/bin/sh -c 'cat <<EOF
16540 $ @kbd{bash -c 'cat <<EOF
16544 $ @kbd{bash -c 'cat <<EOF
16550 Perhaps the easiest way to work around quoting issues in a manner
16551 portable to all shells is to place the results in a temporary variable,
16552 then use @samp{$t} as the @var{value}, rather than trying to inline
16553 the expression needing quoting.
16556 $ @kbd{/bin/sh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16558 $ @kbd{ksh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16560 $ @kbd{bash -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16564 @item $@{@var{var}=@var{value}@}
16565 @cindex @code{$@{@var{var}=@var{value}@}}
16566 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16567 to @var{var}, remember that even though the assignment to @var{var} does
16568 not undergo file name expansion, the result of the variable expansion
16569 does unless the expansion occurred within double quotes. In particular,
16570 when using @command{:} followed by unquoted variable expansion for the
16571 side effect of setting a default value, if the final value of
16572 @samp{$var} contains any globbing characters (either from @var{value} or
16573 from prior contents), the shell has to spend time performing file name
16574 expansion and field splitting even though those results will not be
16575 used. Therefore, it is a good idea to consider double quotes when performing
16576 default initialization; while remembering how this impacts any quoting
16577 characters appearing in @var{value}.
16580 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16586 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16592 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16599 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16607 As with @samp{+} and @samp{-}, @var{value} must be a single shell word,
16608 otherwise some shells, such as Solaris 10 @command{/bin/sh} or on Digital
16609 Unix V 5.0, die because of a ``bad substitution''. Meanwhile, POSIX
16610 requires that with @samp{=}, quote removal happens prior to the
16611 assignment, and the expansion be the final contents of @var{var} without
16612 quoting (and thus subject to field splitting), in contrast to the
16613 behavior with @samp{-} passing the quoting through to the final
16614 expansion. However, @command{bash} 4.1 does not obey this rule.
16617 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16619 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16621 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16625 Finally, POSIX states that when mixing @samp{$@{a=b@}} with regular
16626 commands, it is unspecified whether the assignments affect the parent
16627 shell environment. It is best to perform assignments independently from
16628 commands, to avoid the problems demonstrated in this example running on
16632 $ @kbd{cmd='x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";printf "%s\\n" -$x-'}
16633 $ @kbd{bash -c "$cmd"}
16636 $ @kbd{/bin/sh -c "$cmd"}
16639 $ @kbd{ksh -c "$cmd"}
16644 @item $@{@var{var}=@var{value}@}
16645 @cindex @code{$@{@var{var}=@var{literal}@}}
16646 Solaris 10 @command{/bin/sh} has a frightening bug in its handling of
16647 literal assignments. Imagine you need set a variable to a string containing
16648 @samp{@}}. This @samp{@}} character confuses Solaris 10 @command{/bin/sh}
16649 when the affected variable was already set. This bug can be exercised
16654 $ @kbd{foo=$@{foo='@}'@}}
16657 $ @kbd{foo=$@{foo='@}' # no error; this hints to what the bug is}
16660 $ @kbd{foo=$@{foo='@}'@}}
16666 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16667 though it is enclosed in single quotes. The problem doesn't happen
16668 using double quotes, or when using a temporary variable holding the
16669 problematic string.
16671 @item $@{@var{var}=@var{expanded-value}@}
16672 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16673 On shells so old that they are no longer relevant, the command
16676 # Set the shell variable to a default value
16677 # if it is not already set.
16678 : $@{var="$default"@}
16682 misbehaved badly in some cases. Older scripts worked around the bugs by
16683 using one of following two lines, the latter of which was more portable:
16686 var=$@{var="$default"@}
16687 test $@{var+y@} || var=$default
16691 However, these workarounds are no longer needed.
16693 @item $@{#@var{var}@}
16694 @itemx $@{@var{var}%@var{word}@}
16695 @itemx $@{@var{var}%%@var{word}@}
16696 @itemx $@{@var{var}#@var{word}@}
16697 @itemx $@{@var{var}##@var{word}@}
16698 @cindex @code{$@{#@var{var}@}}
16699 @cindex @code{$@{@var{var}%@var{word}@}}
16700 @cindex @code{$@{@var{var}%%@var{word}@}}
16701 @cindex @code{$@{@var{var}#@var{word}@}}
16702 @cindex @code{$@{@var{var}##@var{word}@}}
16703 POSIX requires support for these usages, but they do not work with many
16704 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16706 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms. For
16707 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16708 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16709 yields the empty string.
16712 @item `@var{commands}`
16713 @cindex @code{`@var{commands}`}
16714 @cindex Command Substitution
16715 POSIX requires shells to trim all trailing newlines from command
16716 output before substituting it, so assignments like
16717 @samp{dir=`printf '%s\n' "$file" | tr a A`} do not work as expected if
16718 @samp{$file} ends in a newline.
16720 While in general it makes no sense, do not substitute a single builtin
16721 with side effects, because Ash 0.2, trying to optimize, does not fork a
16722 subshell to perform the command.
16723 For instance, if you wanted to check that @command{cd} is silent, do not
16724 use @samp{test -z "`cd /`"} because the following can happen:
16729 $ @kbd{test -z "`cd /`" && pwd}
16734 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16736 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16737 command substitution of a native program, if the end of the substitution
16738 is not aligned with the end of the double quote. This may be worked
16739 around by inserting another pair of quotes:
16742 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16743 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16744 - broken differ: char 4, line 1
16747 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16748 replace it with a null string, and wrongly evaluate the enclosing
16749 command before entering the trap or ending the script. This can lead to
16753 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16755 sh: test: hi: unexpected operator/operand
16759 You can avoid this by assigning the command substitution to a temporary
16763 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16764 if test "x$res" = xhi; then echo yes; fi'}
16768 @item $(@var{commands})
16769 @cindex @code{$(@var{commands})}
16770 This construct is meant to replace @samp{`@var{commands}`},
16771 and it has most of the problems listed under @code{`@var{commands}`}.
16773 This construct can be
16774 nested while this is impossible to do portably with back quotes.
16775 Although it is almost universally supported, unfortunately Solaris 10
16776 and earlier releases lack it:
16779 $ @kbd{showrev -c /bin/sh | grep version}
16780 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16781 $ @kbd{echo $(echo blah)}
16782 syntax error: `(' unexpected
16785 If you do use @samp{$(@var{commands})}, make sure that the commands
16786 do not start with a parenthesis, as that would cause confusion with
16787 a different notation @samp{$((@var{expression}))} that in modern
16788 shells is an arithmetic expression not a command. To avoid the
16789 confusion, insert a space between the two opening parentheses.
16791 Avoid @var{commands} that contain unbalanced parentheses in
16792 here-documents, comments, or case statement patterns, as many shells
16793 mishandle them. For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16794 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16797 echo $(case x in x) echo hello;; esac)
16801 @item $((@var{expression}))
16802 @cindex @code{$((@var{expression}))}
16803 Arithmetic expansion is not portable as some shells (most
16804 notably Solaris 10 @command{/bin/sh}) don't support it.
16806 Among shells that do support @samp{$(( ))}, not all of them obey the
16807 POSIX rule that octal and hexadecimal constants must be recognized:
16810 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16812 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16814 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16816 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16817 pdksh: 010 + 0x10 : bad number `0x10'
16818 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16822 When it is available, using arithmetic expansion provides a noticeable
16823 speedup in script execution; but testing for support requires
16824 @command{eval} to avoid syntax errors. The following construct is used
16825 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16826 arguments are decimal integers without leading zeros, and all
16827 operators are properly quoted and appear as distinct arguments:
16830 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16831 eval 'func_arith ()
16833 func_arith_result=$(( $* ))
16838 func_arith_result=`expr "$@@"`
16842 foo=$func_arith_result
16847 @cindex @code{^} quoting
16848 Always quote @samp{^}, otherwise traditional shells such as
16849 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16855 @section Assignments
16856 @cindex Shell assignments
16858 When setting several variables in a row, be aware that the order of the
16859 evaluation is undefined. For instance @samp{foo=1 foo=2; echo $foo}
16860 gives @samp{1} with Solaris 10 @command{/bin/sh}, but @samp{2} with Bash.
16862 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16864 Don't rely on the following to find @file{subdir/program}:
16867 PATH=subdir$PATH_SEPARATOR$PATH program
16871 as this does not work with Zsh 3.0.6. Use something like this
16875 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16878 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16879 the status and propagates that of the last statement:
16882 $ @kbd{false || foo=bar; echo $?}
16884 $ @kbd{false || foo=`:`; echo $?}
16889 and to make things even worse, QNX 4.25 just sets the exit status
16893 $ @kbd{foo=`exit 1`; echo $?}
16897 To assign default values, follow this algorithm:
16901 If the default value is a literal and does not contain any closing
16905 : "$@{var='my literal'@}"
16909 If the default value contains no closing brace, has to be expanded, and
16910 the variable being initialized is not intended to be IFS-split
16911 (i.e., it's not a list), then use:
16914 : $@{var="$default"@}
16918 If the default value contains no closing brace, has to be expanded, and
16919 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16923 var=$@{var="$default"@}
16927 If the default value contains a closing brace, then use:
16930 test $@{var+y@} || var="has a '@}'"
16934 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16935 doubt, just use the last form. @xref{Shell Substitutions}, items
16936 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16940 @section Parentheses in Shell Scripts
16941 @cindex Shell parentheses
16943 Beware of two opening parentheses in a row, as many shell
16944 implementations treat them specially, and POSIX says that a portable
16945 script cannot use @samp{((} outside the @samp{$((} form used for shell
16946 arithmetic. In traditional shells, @samp{((cat))} behaves like
16947 @samp{(cat)}; but many shells, including
16948 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16949 expression equivalent to @samp{let "cat"}, and may or may not report an
16950 error when they detect that @samp{cat} is not a number. As another
16951 example, @samp{pdksh} 5.2.14 does not treat the following code
16952 as a traditional shell would:
16955 if ((true) || false); then
16961 To work around this problem, insert a space between the two opening
16962 parentheses. There is a similar problem and workaround with
16963 @samp{$((}; see @ref{Shell Substitutions}.
16965 @node Special Shell Variables
16966 @section Special Shell Variables
16967 @cindex Shell variables
16968 @cindex Special shell variables
16970 Some shell variables should not be used, since they can have a deep
16971 influence on the behavior of the shell. In order to recover a sane
16972 behavior from the shell, some variables should be unset; M4sh takes
16973 care of this and provides fallback values, whenever needed, to cater
16974 for a very old @file{/bin/sh} that does not support @command{unset}.
16975 (@pxref{Portable Shell, , Portable Shell Programming}).
16977 As a general rule, shell variable names containing a lower-case letter
16978 are safe; you can define and use these variables without worrying about
16979 their effect on the underlying system, and without worrying about
16980 whether the shell changes them unexpectedly. (The exception is the
16981 shell variable @code{status}, as described below.)
16983 Here is a list of names that are known to cause trouble. This list is
16984 not exhaustive, but you should be safe if you avoid the name
16985 @code{status} and names containing only upper-case letters and
16988 @c Alphabetical order, case insensitive, 'A' before 'a'.
16991 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16992 , Limitations of Shell Builtins}). Not all shells manage @samp{$?}
16993 correctly in shell functions (@pxref{Shell Functions}) or in traps
16994 (@pxref{trap, , Limitations of Shell Builtins}). Not all shells reset
16995 @samp{$?} to zero after an empty command.
16998 $ @kbd{bash -c 'false; $empty; echo $?'}
17000 $ @kbd{zsh -c 'false; $empty; echo $?'}
17006 Many shells reserve @samp{$_} for various purposes, e.g., the name of
17007 the last command executed.
17011 When this variable is set it specifies a list of directories to search
17012 when invoking @code{cd} with a relative file name that did not start
17013 with @samp{./} or @samp{../}. POSIX
17014 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
17015 is used successfully, @code{cd} prints the resulting absolute
17016 file name. Unfortunately this output can break idioms like
17017 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
17018 Also, many shells do not conform to this part of POSIX; for
17019 example, @command{zsh} prints the result only if a directory name
17020 other than @file{.} was chosen from @env{CDPATH}.
17022 In practice the shells that have this problem also support
17023 @command{unset}, so you can work around the problem as follows:
17026 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
17029 You can also avoid output by ensuring that your directory name is
17030 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
17032 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
17033 possible, so you need not worry about this problem in those scripts.
17035 @item CLICOLOR_FORCE
17036 @evindex CLICOLOR_FORCE
17037 When this variable is set, some implementations of tools like
17038 @command{ls} attempt to add color to their output via terminal escape
17039 sequences, even when the output is not directed to a terminal, and can
17040 thus cause spurious failures in scripts. Configure scripts use M4sh,
17041 which automatically unsets this variable.
17045 In the MKS shell, case statements and file name generation are
17046 case-insensitive unless @env{DUALCASE} is nonzero.
17047 Autoconf-generated scripts export this variable when they start up.
17061 These variables should not matter for shell scripts, since they are
17062 supposed to affect only interactive shells. However, at least one
17063 shell (the pre-3.0 UWIN Korn shell) gets confused about
17064 whether it is interactive, which means that (for example) a @env{PS1}
17065 with a side effect can unexpectedly modify @samp{$?}. To work around
17066 this bug, M4sh scripts (including @file{configure} scripts) do something
17070 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
17077 (actually, there is some complication due to bugs in @command{unset};
17078 @pxref{unset, , Limitations of Shell Builtins}).
17082 The Korn shell uses @env{FPATH} to find shell functions, so avoid
17083 @env{FPATH} in portable scripts. @env{FPATH} is consulted after
17084 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
17085 to find whether a command exists, since they might report the wrong
17086 result if @env{FPATH} is also set.
17089 @evindex GREP_OPTIONS
17090 When this variable is set, some implementations of @command{grep} honor
17091 these options, even if the options include direction to enable colored
17092 output via terminal escape sequences, and the result can cause spurious
17093 failures when the output is not directed to a terminal. Configure
17094 scripts use M4sh, which automatically unsets this variable.
17098 Long ago, shell scripts inherited @env{IFS} from the environment,
17099 but this caused many problems so modern shells ignore any environment
17100 settings for @env{IFS}.
17102 Don't set the first character of @env{IFS} to backslash. Indeed,
17103 Bourne shells use the first character (backslash) when joining the
17104 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
17105 backslash escapes, so you can end up with backspace and other strange
17108 The proper value for @env{IFS} (in regular code, not when performing
17109 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}. The first character is
17110 especially important, as it is used to join the arguments in @samp{$*};
17111 however, note that traditional shells, but also bash-2.04, fail to adhere
17112 to this and join with a space anyway.
17114 M4sh guarantees that @env{IFS} will have the default value at the
17115 beginning of a script, and many macros within autoconf rely on this
17116 setting. It is okay to use blocks of shell code that temporarily change
17117 the value of @env{IFS} in order to split on another character, but
17118 remember to restore it before expanding further macros.
17120 Unsetting @code{IFS} instead of resetting it to the default sequence
17121 is not suggested, since code that tries to save and restore the
17122 variable's value will incorrectly reset it to an empty value, thus
17123 disabling field splitting:
17127 # default separators used for field splitting
17133 # no field splitting performed
17146 @evindex LC_COLLATE
17148 @evindex LC_MESSAGES
17149 @evindex LC_MONETARY
17150 @evindex LC_NUMERIC
17153 You should set all these variables to @samp{C} because so much
17154 configuration code assumes the C locale and POSIX requires that locale
17155 environment variables be set to @samp{C} if the C locale is desired;
17156 @file{configure} scripts and M4sh do that for you.
17157 Export these variables after setting them.
17162 @env{LANGUAGE} is not specified by POSIX, but it is a GNU
17163 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
17167 @itemx LC_IDENTIFICATION
17168 @itemx LC_MEASUREMENT
17171 @itemx LC_TELEPHONE
17172 @evindex LC_ADDRESS
17173 @evindex LC_IDENTIFICATION
17174 @evindex LC_MEASUREMENT
17177 @evindex LC_TELEPHONE
17179 These locale environment variables are GNU extensions. They
17180 are treated like their POSIX brethren (@env{LC_COLLATE},
17181 etc.)@: as described above.
17185 Most modern shells provide the current line number in @code{LINENO}.
17186 Its value is the line number of the beginning of the current command.
17187 M4sh, and hence Autoconf, attempts to execute @command{configure} with
17188 a shell that supports @code{LINENO}. If no such shell is available, it
17189 attempts to implement @code{LINENO} with a Sed prepass that replaces each
17190 instance of the string @code{$LINENO} (not followed by an alphanumeric
17191 character) with the line's number. In M4sh scripts you should execute
17192 @code{AS_LINENO_PREPARE} so that these workarounds are included in
17193 your script; configure scripts do this automatically in @code{AC_INIT}.
17195 You should not rely on @code{LINENO} within @command{eval} or shell
17196 functions, as the behavior differs in practice. The presence of a
17197 quoted newline within simple commands can alter which line number is
17198 used as the starting point for @code{$LINENO} substitutions within that
17199 command. Also, the possibility of the Sed prepass means that you should
17200 not rely on @code{$LINENO} when quoted, when in here-documents, or when
17201 line continuations are used. Subshells should be OK, though. In the
17202 following example, lines 1, 9, and 14 are portable, but the other
17203 instances of @code{$LINENO} do not have deterministic values:
17216 ( echo 9. $LINENO )
17217 eval 'echo 10. $LINENO'
17218 eval 'echo 11. $LINENO
17223 f () @{ echo $1 $LINENO;
17230 $ @kbd{bash-3.2 ./lineno}
17249 $ @kbd{zsh-4.3.4 ./lineno}
17268 $ @kbd{pdksh-5.2.14 ./lineno}
17287 $ @kbd{sed '=' <lineno |}
17293 > @kbd{ s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17296 > @kbd{ s,^[0-9]*\n,,}
17318 In particular, note that @file{config.status} (and any other subsidiary
17319 script created by @code{AS_INIT_GENERATED}) might report line numbers
17320 relative to the parent script as a result of the potential Sed pass.
17324 When executing the command @samp{>foo}, @command{zsh} executes
17325 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17326 compatibility mode and the @command{zsh} version is newer
17327 than 3.1.6-dev-18. If you are using an older @command{zsh}
17328 and forget to set @env{NULLCMD},
17329 your script might be suspended waiting for data on its standard input.
17333 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17334 array even after @code{emulate sh}, so it should not be used.
17336 @item PATH_SEPARATOR
17337 @evindex PATH_SEPARATOR
17338 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17339 variable can be set to either @samp{:} or @samp{;} to control the path
17340 separator Bash uses to set up certain environment variables (such as
17341 @env{PATH}). You can set this variable to @samp{;} if you want
17342 @command{configure} to use @samp{;} as a separator; this might be useful
17343 if you plan to use non-POSIX shells to execute files. @xref{File System
17344 Conventions}, for more information about @code{PATH_SEPARATOR}.
17346 @item POSIXLY_CORRECT
17347 @evindex POSIXLY_CORRECT
17348 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17349 (even empty) causes programs to try harder to conform to POSIX.
17350 Autoconf does not directly manipulate this variable, but @command{bash}
17351 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17352 running in POSIX mode. Therefore, take care when exporting or unsetting
17353 this variable, so as not to change whether @command{bash} is in POSIX
17357 $ @kbd{bash --posix -c 'set -o | grep posix}
17358 > @kbd{unset POSIXLY_CORRECT}
17359 > @kbd{set -o | grep posix'}
17366 POSIX 1003.1-2001 requires that @command{cd} and
17367 @command{pwd} must update the @env{PWD} environment variable to point
17368 to the logical name of the current directory, but traditional shells
17369 do not support this. This can cause confusion if one shell instance
17370 maintains @env{PWD} but a subsidiary and different shell does not know
17371 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17372 points to the wrong directory. Use @samp{`pwd`} rather than
17377 Many shells provide @code{RANDOM}, a variable that returns a different
17378 integer each time it is used. It is common
17379 practice to use @code{$RANDOM} as part of a file name, but code
17380 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17384 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17385 hence read-only. Do not use it.
17388 @node Shell Functions
17389 @section Shell Functions
17390 @cindex Shell Functions
17392 Nowadays, it is difficult to find a shell that does not support
17393 shell functions at all. However, some differences should be expected.
17395 When declaring a shell function, you must include whitespace between the
17396 @samp{)} after the function name and the start of the compound
17397 expression, to avoid upsetting @command{ksh}. While it is possible to
17398 use any compound command, most scripts use @samp{@{@dots{}@}}.
17401 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17403 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17404 ksh: syntax error at line 1: `@}' unexpected
17405 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17409 Inside a shell function, you should not rely on the error status of a
17410 subshell if the last command of that subshell was @code{exit} or
17411 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17412 find a shell that does not exhibit the bug, zsh might be the only shell
17413 present on the user's machine.
17415 Likewise, the state of @samp{$?} is not reliable when entering a shell
17416 function. This has the effect that using a function as the first
17417 command in a @command{trap} handler can cause problems.
17420 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17423 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17428 DJGPP bash 2.04 has a bug in that @command{return} from a
17429 shell function which also used a command substitution causes a
17430 segmentation fault. To work around the issue, you can use
17431 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17432 in the execution flow of the function (@pxref{Common Shell Constructs}).
17434 Not all shells treat shell functions as simple commands impacted by
17435 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17438 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17439 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17443 Shell variables and functions may share the same namespace, for example
17444 with Solaris 10 @command{/bin/sh}:
17447 $ @kbd{f () @{ :; @}; f=; f}
17452 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17453 uses the prefix @samp{as_fn_} for its functions.
17455 Handling of positional parameters and shell options varies among shells.
17456 For example, Korn shells reset and restore trace output (@samp{set -x})
17457 and other options upon function entry and exit.
17459 It is not portable to pass temporary environment variables to shell
17460 functions. Solaris 10 @command{/bin/sh} does not see the variable.
17461 Meanwhile, not all shells follow the POSIX rule that the assignment must
17462 affect the current environment in the same manner as special built-ins.
17465 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17468 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17471 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17476 Some ancient Bourne shell variants with function support did not reset
17477 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17478 arguments of the script were lost after the first function invocation.
17479 It is probably not worth worrying about these shells any more.
17481 With AIX sh, a @command{trap} on 0 installed in a shell function
17482 triggers at function exit rather than at script exit. @xref{trap, ,
17483 Limitations of Shell Builtins}.
17485 @node Limitations of Builtins
17486 @section Limitations of Shell Builtins
17487 @cindex Shell builtins
17488 @cindex Limitations of shell builtins
17490 No, no, we are serious: some shells do have limitations! :)
17492 You should always keep in mind that any builtin or command may support
17493 options, and therefore differ in behavior with arguments
17494 starting with a dash. For instance, even the innocent @samp{echo "$word"}
17495 can give unexpected results when @code{word} starts with a dash. To avoid
17496 this problem, use @samp{printf '%s\n' "$word"}. Many of these limitations
17497 can be worked around using M4sh (@pxref{Programming in M4sh}).
17499 @c This table includes things like '@command{test} (files)', so we can't
17500 @c use @table @command.
17504 @prindex @command{.}
17505 Use @command{.} only with regular files (use @samp{test -f}). Bash
17506 2.03, for instance, chokes on @samp{. /dev/null}. Remember that
17507 @command{.} uses @env{PATH} if its argument contains no slashes. Also,
17508 some shells, including bash 3.2, implicitly append the current directory
17509 to this @env{PATH} search, even though POSIX forbids it. So if you want
17510 to use @command{.} on a file @file{foo} in the current directory, you
17511 must use @samp{. ./foo}.
17513 Not all shells gracefully handle syntax errors within a sourced file.
17514 On one extreme, some non-interactive shells abort the entire script. On
17515 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17519 $ @kbd{echo 'fi' > syntax}
17520 $ @kbd{bash -c '. ./syntax; echo $?'}
17521 ./syntax: line 1: syntax error near unexpected token `fi'
17522 ./syntax: line 1: `fi'
17524 $ @kbd{ash -c '. ./syntax; echo $?'}
17525 ./syntax: 1: Syntax error: "fi" unexpected
17526 $ @kbd{zsh -c '. ./syntax; echo $?'}
17527 ./syntax:1: parse error near `fi'
17534 @prindex @command{!}
17535 The Unix version 7 shell did not support
17536 negating the exit status of commands with @command{!}, and this feature
17537 is still absent from some shells (e.g., Solaris 10 @command{/bin/sh}).
17538 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17539 bugs when using @command{!}:
17542 $ @kbd{sh -c '! : | :'; echo $?}
17544 $ @kbd{ash -c '! : | :'; echo $?}
17546 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17548 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17550 Syntax error: "@}" unexpected
17554 Shell code like this:
17557 if ! cmp file1 file2 >/dev/null 2>&1; then
17558 echo files differ or trouble
17562 is therefore not portable in practice. Typically it is easy to rewrite
17566 cmp file1 file2 >/dev/null 2>&1 ||
17567 echo files differ or trouble
17570 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17574 AS_IF([cmp -s file file.new], [],
17575 [echo files differ or trouble])
17578 This kind of rewriting is needed in code outside macro definitions that
17579 calls other macros. @xref{Common Shell Constructs}. It is also useful
17580 inside macro definitions, where the @dfn{then} and @dfn{else} branches
17581 might contain macro arguments.
17583 More generally, one can always rewrite @samp{! @var{command}} as:
17586 AS_IF([@var{command}], [(exit 1)])
17589 @item @command{&&} and @command{||}
17590 @c --------------------------------
17591 @prindex @command{&&}
17592 @prindex @command{||}
17593 If an AND-OR list is not inside @code{AC_DEFUN}, and it contains
17594 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
17595 @xref{Common Shell Constructs}. The operators @code{&&} and @code{||}
17596 have equal precedence and are left associative, so instead of:
17599 # This is dangerous outside AC_DEFUN.
17600 cmp a b >/dev/null 2>&1 &&
17601 AS_ECHO([files are same]) >$tmpfile ||
17602 AC_MSG_NOTICE([files differ, or echo failed])
17608 # This is OK outside AC_DEFUN.
17609 AS_IF([AS_IF([cmp a b >/dev/null 2>&1],
17610 [AS_ECHO([files are same]) >$tmpfile],
17612 [AC_MSG_NOTICE([files differ, or echo failed])])
17615 @item @command{@{...@}}
17616 @c --------------------
17617 @prindex @command{@{...@}}
17618 Bash 3.2 (and earlier versions) sometimes does not properly set
17619 @samp{$?} when failing to write redirected output of a compound command.
17620 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17621 not occur with @samp{(@dots{})}. For example:
17624 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17625 bash: line 1: /bad: Permission denied
17627 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17628 bash: line 1: /bad: Permission denied
17632 To work around the bug, prepend @samp{:;}:
17635 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17636 bash: line 1: /bad: Permission denied
17640 POSIX requires a syntax error if a brace list has no contents. However,
17641 not all shells obey this rule; and on shells where empty lists are
17642 permitted, the effect on @samp{$?} is inconsistent. To avoid problems,
17643 ensure that a brace list is never empty.
17646 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17647 bash: line 1: syntax error near unexpected token `@}'
17648 bash: line 1: `false; @{ @}; echo $?'
17650 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17652 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17657 @item @command{break}
17658 @c ------------------
17659 @prindex @command{break}
17660 The use of @samp{break 2} etc.@: is safe.
17664 @item @command{case}
17665 @c -----------------
17666 @prindex @command{case}
17667 If a @code{case} command is not inside @code{AC_DEFUN}, and it contains
17668 calls to Autoconf macros, it should be rewritten using @code{AS_CASE}.
17669 @xref{Common Shell Constructs}. Instead of:
17672 # This is dangerous outside AC_DEFUN.
17674 *.[ch]) AC_MSG_NOTICE([C source file]);;
17682 # This is OK outside AC_DEFUN.
17683 AS_CASE([$filename],
17684 [[*.[ch]]], [AC_MSG_NOTICE([C source file])])
17687 You don't need to quote the argument; no splitting is performed.
17689 You don't need the final @samp{;;}, but you should use it.
17691 POSIX requires support for @code{case} patterns with opening
17692 parentheses like this:
17696 (*.c) echo "C source code";;
17701 but the @code{(} in this example is not portable to a few obsolescent Bourne
17702 shell implementations, which is a pity for those of us using tools that
17703 rely on balanced parentheses. For instance, with Solaris 10
17707 $ @kbd{case foo in (foo) echo foo;; esac}
17708 @error{}syntax error: `(' unexpected
17712 The leading @samp{(} can be omitted safely. Unfortunately, there are
17713 contexts where unbalanced parentheses cause other problems, such as when
17714 using a syntax-highlighting editor that searches for the balancing
17715 counterpart, or more importantly, when using a case statement as an
17716 underquoted argument to an Autoconf macro. @xref{Balancing
17717 Parentheses}, for trade-offs involved in various styles of dealing with
17718 unbalanced @samp{)}.
17720 Zsh handles pattern fragments derived from parameter expansions or
17721 command substitutions as though quoted:
17724 $ pat=\?; case aa in ?$pat) echo match;; esac
17725 $ pat=\?; case a? in ?$pat) echo match;; esac
17730 Because of a bug in its @code{fnmatch}, Bash fails to properly
17731 handle backslashes in character classes:
17734 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17739 This is extremely unfortunate, since you are likely to use this code to
17740 handle POSIX or MS-DOS absolute file names. To work around this
17741 bug, always put the backslash first:
17744 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17746 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17750 Many Bourne shells cannot handle closing brackets in character classes
17753 Some shells also have problems with backslash escaping in case you do not want
17754 to match the backslash: both a backslash and the escaped character match this
17755 pattern. To work around this, specify the character class in a variable, so
17756 that quote removal does not apply afterwards, and the special characters don't
17757 have to be backslash-escaped:
17760 $ @kbd{case '\' in [\<]) echo OK;; esac}
17762 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17766 Even with this, Solaris @command{ksh} matches a backslash if the set
17768 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17770 Some shells, such as Ash 0.3.8, are confused by an empty
17771 @code{case}/@code{esac}:
17774 ash-0.3.8 $ @kbd{case foo in esac;}
17775 @error{}Syntax error: ";" unexpected (expecting ")")
17778 POSIX requires @command{case} to give an exit status of 0 if no cases
17779 match. However, @command{/bin/sh} in Solaris 10 does not obey this
17780 rule. Meanwhile, it is unclear whether a case that matches, but
17781 contains no statements, must also change the exit status to 0. The M4sh
17782 macro @code{AS_CASE} works around these inconsistencies.
17785 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17787 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17794 @prindex @command{cd}
17795 POSIX 1003.1-2001 requires that @command{cd} must support
17796 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17797 with @option{-L} being the default. However, traditional shells do
17798 not support these options, and their @command{cd} command has the
17799 @option{-P} behavior.
17801 Portable scripts should assume neither option is supported, and should
17802 assume neither behavior is the default. This can be a bit tricky,
17803 since the POSIX default behavior means that, for example,
17804 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17805 the current logical directory is a symbolic link. It is safe to use
17806 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17807 Also, Autoconf-generated scripts check for this problem when computing
17808 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17809 so it is safe to @command{cd} to these variables.
17811 POSIX states that behavior is undefined if @command{cd} is given an
17812 explicit empty argument. Some shells do nothing, some change to the
17813 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17814 the shell rather than returning an error. Unfortunately, this means
17815 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17816 than @samp{cd $var} (at least the latter is well-behaved in all shells
17817 at changing to @env{HOME}, although this is probably not what you wanted
17818 in a script). You should check that a directory name was supplied
17819 before trying to change locations.
17821 @xref{Special Shell Variables}, for portability problems involving
17822 @command{cd} and the @env{CDPATH} environment variable.
17823 Also please see the discussion of the @command{pwd} command.
17827 @item @command{echo}
17828 @c -----------------
17829 @prindex @command{echo}
17830 The simple @command{echo} is probably the most surprising source of
17831 portability troubles. It is not possible to use @samp{echo} portably
17832 unless both options and escape sequences are omitted.
17834 Do not use options, as some shells support them and others do not.
17835 For example, POSIX says that the behavior of @samp{echo -n foo} is
17836 implementation-defined. On some platforms the output is @samp{foo}
17837 without a trailing newline, on others it is @samp{-n foo} with a
17838 trailing newline, and POSIX allows even other behavior.
17840 Do not use backslashes in the arguments, as there is no consensus on
17841 their handling. For @samp{echo '\n' | wc -l}, the @command{sh} of
17842 Solaris 10 outputs 2,
17843 but Bash and Zsh (in @command{sh} emulation mode) output 1.
17844 The problem is truly @command{echo}: all the shells
17845 understand @samp{'\n'} as the string composed of a backslash and an
17848 Because of these problems, do not pass a string containing arbitrary
17849 characters to @command{echo}. For example, @samp{echo "$foo"} is safe
17850 only if you know that @var{foo}'s value cannot contain backslashes and
17851 cannot start with @samp{-}.
17853 Normally, @command{printf} is safer and easier to use than @command{echo}
17854 and @command{echo -n}. Thus, you should use @command{printf '%s\n'}
17855 instead of @command{echo}, and similarly use @command{printf %s} instead
17856 of @command{echo -n}.
17858 Older scripts, written before @command{printf} was portable,
17859 sometimes used a here-document as a safer alternative to @command{echo},
17869 However, this usage is problematic, as even some modern shells have
17870 hard-to-reproduce bugs when dealing with here-documents.
17873 @item @command{eval}
17874 @c -----------------
17875 @prindex @command{eval}
17876 The @command{eval} command is useful in limited circumstances, e.g.,
17877 using commands like @samp{eval table_$key=\$value} and @samp{eval
17878 value=table_$key} to simulate a hash table when the key is known to be
17881 You should also be wary of common bugs in @command{eval} implementations.
17882 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17883 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17884 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17885 @samp{$?} is 0, so they exhibit behavior like this:
17888 $ @kbd{false; eval 'echo $?'}
17892 The correct behavior here is to output a nonzero value,
17893 but portable scripts should not rely on this.
17895 You should not rely on @code{LINENO} within @command{eval}.
17896 @xref{Special Shell Variables}.
17898 Note that, even though these bugs are easily avoided,
17899 @command{eval} is tricky to use on arbitrary arguments.
17900 It is obviously unwise to use @samp{eval $cmd} if the string value of
17901 @samp{cmd} was derived from an untrustworthy source. But even if the
17902 string value is valid, @samp{eval $cmd} might not work as intended,
17903 since it causes field splitting and file name expansion to occur twice,
17904 once for the @command{eval} and once for the command itself. It is
17905 therefore safer to use @samp{eval "$cmd"}. For example, if @var{cmd}
17906 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17907 equivalent of @samp{cat test;.c} if there happens to be a file named
17908 @file{test;.c} in the current directory; and this in turn
17909 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17910 then execute the command @command{.c}. To avoid this problem, use
17911 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17913 However, suppose that you want to output the text of the evaluated
17914 command just before executing it. Assuming the previous example,
17915 @samp{printf '%s\n' "Executing: $cmd"} outputs @samp{Executing: cat test?.c},
17916 but this output doesn't show the user that @samp{test;.c} is the actual
17917 name of the copied file.
17918 Conversely, @samp{printf 'Executing:'; eval "printf ' %s' $cmd"; printf '\n'}
17919 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17920 since it mistakenly replaces the contents of @file{bar} by the
17921 string @samp{ cat foo}. No simple, general, and portable solution to
17922 this problem is known.
17924 @item @command{exec}
17925 @c -----------------
17926 @prindex @command{exec}
17927 POSIX describes several categories of shell built-ins. Special
17928 built-ins (such as @command{exit}) must impact the environment of the
17929 current shell, and need not be available through @command{exec}. All
17930 other built-ins are regular, and must not propagate variable assignments
17931 to the environment of the current shell. However, the group of regular
17932 built-ins is further distinguished by commands that do not require a
17933 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17934 are offered as a more efficient version of something that must still be
17935 found in a @env{PATH} search (such as @command{echo}). POSIX is not
17936 clear on whether @command{exec} must work with the list of 17 utilities
17937 that are invoked without a @env{PATH} search, and many platforms lack an
17938 executable for some of those built-ins:
17941 $ @kbd{sh -c 'exec cd /tmp'}
17942 sh: line 0: exec: cd: not found
17945 All other built-ins that provide utilities specified by POSIX must have
17946 a counterpart executable that exists on @env{PATH}, although POSIX
17947 allows @command{exec} to use the built-in instead of the executable.
17948 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17951 $ @kbd{bash -c 'pwd --version' | head -n1}
17952 bash: line 0: pwd: --: invalid option
17953 pwd: usage: pwd [-LP]
17954 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17955 pwd (GNU coreutils) 6.10
17956 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17957 pdksh: pwd: --: unknown option
17960 When it is desired to avoid a regular shell built-in, the workaround is
17961 to use some other forwarding command, such as @command{env} or
17962 @command{nice}, that will ensure a path search:
17965 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17966 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17967 true (GNU coreutils) 6.10
17968 $ @kbd{pdksh -c 'env true --version' | head -n1}
17969 true (GNU coreutils) 6.10
17972 @item @command{exit}
17973 @c -----------------
17974 @prindex @command{exit}
17975 The default value of @command{exit} is supposed to be @code{$?};
17976 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17977 perform @samp{exit 0}.
17980 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17982 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17984 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17988 Using @samp{exit $?} restores the expected behavior.
17990 Some shell scripts, such as those generated by @command{autoconf}, use a
17991 trap to clean up before exiting. If the last shell command exited with
17992 nonzero status, the trap also exits with nonzero status so that the
17993 invoker can tell that an error occurred.
17995 Unfortunately, in some shells, such as Solaris 10 @command{/bin/sh}, an exit
17996 trap ignores the @code{exit} command's argument. In these shells, a trap
17997 cannot determine whether it was invoked by plain @code{exit} or by
17998 @code{exit 1}. Instead of calling @code{exit} directly, use the
17999 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
18003 @item @command{export}
18004 @c -------------------
18005 @prindex @command{export}
18006 The builtin @command{export} dubs a shell variable @dfn{environment
18007 variable}. Each update of exported variables corresponds to an update
18008 of the environment variables. Conversely, each environment variable
18009 received by the shell when it is launched should be imported as a shell
18010 variable marked as exported.
18012 Alas, some older shells, such as Solaris 10 @command{/bin/sh}, forget to
18013 @command{export} the environment variables they receive. As a result,
18014 two variables coexist: the environment variable and the shell
18015 variable. The following code demonstrates this failure:
18026 when run with @samp{FOO=foo} in the environment, these shells print
18027 alternately @samp{foo} and @samp{bar}, although they should print only
18028 @samp{foo} and then a sequence of @samp{bar}s.
18030 Therefore you should @command{export} again each environment variable
18031 that you update; the export can occur before or after the assignment.
18033 POSIX is not clear on whether the @command{export} of an undefined
18034 variable causes the variable to be defined with the value of an empty
18035 string, or merely marks any future definition of a variable by that name
18036 for export. Various shells behave differently in this regard:
18039 $ @kbd{sh -c 'export foo; env | grep foo'}
18040 $ @kbd{ash -c 'export foo; env | grep foo'}
18044 POSIX requires @command{export} to honor assignments made as arguments,
18045 but older shells do not support this, including @command{/bin/sh} in
18046 Solaris 10. Portable scripts should separate assignments and exports
18047 into different statements.
18050 $ @kbd{bash -c 'export foo=bar; echo $foo'}
18052 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
18053 /bin/sh: foo=bar: is not an identifier
18054 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
18058 POSIX requires @command{export} to work with any arbitrary value for the
18059 contents of the variable being exported, as long as the total size of
18060 the environment combined with arguments doesn't exceed @code{ARG_MAX}
18061 when executing a child process. However, some shells have extensions
18062 that involve interpreting some environment values specially, regardless
18063 of the variable name. We currently know of one case: all versions of
18064 Bash released prior to 27 September 2014 interpret an environment
18065 variable with an initial content substring of @code{() @{} as an
18066 exported function definition (this is the ``Shellshock'' remote
18067 execution bug, CVE-2014-6271 and friends, where it was possible to
18068 exploit the function parser to cause remote code execution on child bash
18069 startup; newer versions of Bash use special environment variable
18070 @emph{names} instead of values to implement the same feature).
18072 There may be entries inherited into the environment that are not valid
18073 as shell variable names; POSIX states that processes should be tolerant
18074 of these names. Some shells such as @command{dash} do this by removing
18075 those names from the environment at startup, while others such as
18076 @command{bash} hide the entry from shell access but still pass it on to
18077 child processes. While you can set such names using @command{env} for a
18078 direct child process, you cannot rely on them being preserved through an
18079 intermediate pass through the shell.
18081 @item @command{false}
18082 @c ------------------
18083 @prindex @command{false}
18084 Don't expect @command{false} to exit with status 1: in native
18085 Solaris @file{/bin/false} exits with status 255.
18088 @item @command{for}
18089 @c ----------------
18090 @prindex @command{for}
18091 To loop over positional arguments, use:
18096 printf '%s\n' "$arg"
18101 You may @emph{not} leave the @code{do} on the same line as @code{for},
18102 since some shells improperly grok:
18106 printf '%s\n' "$arg"
18110 If you want to explicitly refer to the positional arguments, use:
18113 for arg in "$@@"; do
18114 printf '%s\n' "$arg"
18118 POSIX requires support for a @command{for} loop with no list after
18119 @code{in}. However, Solaris 10 @command{/bin/sh} treats that as a syntax
18120 error. It is possible to work around this by providing any shell word
18121 that expands to nothing, or by ignoring an obvious sentinel.
18124 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
18125 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
18126 /bin/sh: syntax error at line 1: `;' unexpected
18129 This syntax problem is most frequently encountered in code that goes
18130 through several layers of expansion, such as an m4 macro or makefile
18131 variable used as a list body, where the first layer of expansion (m4 or
18132 make) can end up expanding to nothing in the version handed to the
18133 shell. In the makefile context, one common workaround is to use a shell
18134 variable rather than a make variable as the source of the list.
18137 $ @kbd{cat Makefile}
18140 @@for arg in $(list); do \
18141 printf '%s\n' $$arg; \
18144 @@list='$(list)'; \
18145 for arg in $$list; do \
18146 printf '%s\n' $$arg; \
18148 $ @kbd{make bad 2&>1 | head -n1}
18149 sh: syntax error at line 1: `;' unexpected
18150 $ @kbd{make bad list='a b'}
18154 $ @kbd{make good list='a b'}
18159 In Solaris 10 @command{/bin/sh}, when the list of arguments of a
18160 @command{for} loop starts with @emph{unquoted} tokens looking like
18161 variable assignments, the loop is not executed on those tokens:
18164 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
18170 Thankfully, quoting the assignment-like tokens, or starting the list
18171 with other tokens (including unquoted variable expansion that results in
18172 an assignment-like result), avoids the problem, so it is easy to work
18176 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
18178 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
18186 @prindex @command{if}
18187 If an @code{if} command is not inside @code{AC_DEFUN}, and it contains
18188 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
18189 @xref{Common Shell Constructs}.
18191 Using @code{if ! @dots{}} is not portable. @xref{!,,@command{!} notes}.
18193 Some very old shells did not reset the exit status from an @command{if}
18194 with no @command{else}:
18197 $ @kbd{if (exit 42); then true; fi; echo $?}
18202 whereas a proper shell should have printed @samp{0}. Although this is no
18203 longer a portability problem, as any shell that supports functions gets it
18204 correct, it explains why some makefiles have lengthy
18208 if test -f "$file"; then
18209 install "$file" "$dest"
18216 @item @command{printf}
18217 @c ------------------
18218 @prindex @command{printf}
18219 A format string starting with a @samp{-} can cause problems.
18220 Bash interprets it as an option and
18221 gives an error. And @samp{--} to mark the end of options is not good
18222 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
18223 literally as the format string. Putting the @samp{-} in a @samp{%c}
18224 or @samp{%s} is probably easiest:
18230 AIX 7.2 @command{sh} mishandles octal escapes in multi-byte locales by
18231 treating them as characters instead of bytes. For example, in a locale
18232 using the UTF-8 encoding, @samp{printf '\351'} outputs the two bytes C3,
18233 A9 (the UTF-8 encoding for U+00E9) instead of the desired single byte E9.
18234 To work around the bug, use the C locale.
18236 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
18239 $ @kbd{printf '\045'}
18240 bash: printf: `%': missing format character
18243 Large outputs may cause trouble. On Solaris 10, for
18244 example, @file{/usr/bin/printf} is buggy, so when using
18245 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18248 Since @command{printf} is not always a shell builtin, there is a
18249 potential speed penalty for using @code{printf '%s\n'} as a replacement
18250 for an @command{echo} that does not interpret @samp{\} or leading
18251 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18252 -r --} for this role instead.
18254 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18255 portable alternatives to both @command{printf} and @command{echo}.
18258 @item @command{pwd}
18259 @c ----------------
18260 @prindex @command{pwd}
18261 With modern shells, plain @command{pwd} outputs a ``logical''
18262 directory name, some of whose components may be symbolic links. These
18263 directory names are in contrast to ``physical'' directory names, whose
18264 components are all directories.
18266 POSIX 1003.1-2001 requires that @command{pwd} must support
18267 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18268 with @option{-L} being the default. However, traditional shells do
18269 not support these options, and their @command{pwd} command has the
18270 @option{-P} behavior.
18272 Portable scripts should assume neither option is supported, and should
18273 assume neither behavior is the default. Also, on many hosts
18274 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but POSIX
18275 does not require this behavior and portable scripts should not rely on
18278 Typically it's best to use plain @command{pwd}. On modern hosts this
18279 outputs logical directory names, which have the following advantages:
18283 Logical names are what the user specified.
18285 Physical names may not be portable from one installation
18286 host to another due to network file system gymnastics.
18288 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18289 some parent directory, but plain @command{pwd} cannot fail for this
18293 Also please see the discussion of the @command{cd} command.
18296 @item @command{read}
18297 @c -----------------
18298 @prindex @command{read}
18299 No options are portable, not even support @option{-r} (Solaris 10
18300 @command{/bin/sh} for example).
18304 @item @command{set}
18305 @c ----------------
18306 @prindex @command{set}
18307 With the FreeBSD 6.0 shell, the @command{set} command (without
18308 any options) does not sort its output.
18310 The @command{set} builtin faces the usual problem with arguments
18312 dash. Modern shells such as Bash or Zsh understand @option{--} to specify
18313 the end of the options (any argument after @option{--} is a parameter,
18314 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18315 10 @command{/bin/sh}) simply stop option
18316 processing as soon as a non-option argument is found. Therefore, use
18317 @samp{dummy} or simply @samp{x} to end the option processing, and use
18318 @command{shift} to pop it out:
18321 set x $my_list; shift
18324 Avoid @samp{set -}, e.g., @samp{set - $my_list}. POSIX no
18325 longer requires support for this command, and in traditional shells
18326 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18327 makes scripts harder to debug.
18329 Some nonstandard shells do not recognize more than one option
18330 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line). It is
18331 better to combine them:
18337 @cindex @command{set -e}
18338 The @option{-e} option has historically been under-specified, with enough
18339 ambiguities to cause numerous differences across various shell
18340 implementations; see for example
18341 @uref{https://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18342 or @uref{https://www.austingroupbugs.net/@/view.php?id=52, this link},
18343 documenting a change to POSIX 2008 to match @command{ksh88} behavior.
18344 Note that mixing @code{set -e} and shell functions is asking for surprises:
18357 According to the recommendation, @samp{one} should always be output
18358 regardless of whether the @command{rm} failed, because it occurs within
18359 the body of the shell function @samp{doit} invoked on the left side of
18360 @samp{||}, where the effects of @samp{set -e} are not enforced.
18361 Likewise, @samp{two} should never be printed, since the failure of
18362 @command{rm} does not abort the function, such that the status of
18365 The BSD shell has had several problems with the @option{-e}
18366 option. Older versions of the BSD
18367 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18368 @samp{case} when @option{-e} was in effect, causing the shell to exit
18369 unexpectedly in some cases. This was particularly a problem with
18370 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18371 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18372 wrapper works around the bug (@pxref{Failure in Make Rules}).
18374 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18375 wrongly exit with @option{-e} if the last command within a compound
18376 statement fails and is guarded by an @samp{&&} only. For example:
18382 test -n "$foo" && exit 1
18385 test -n "$foo" && exit 1
18387 test -n "$foo" && exit 1
18393 does not print @samp{three}. One workaround is to change the last
18394 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18395 "$foo"; then exit 1; fi} instead. Another possibility is to warn BSD
18396 users not to use @samp{sh -e}.
18398 When @samp{set -e} is in effect, a failed command substitution in
18399 Solaris 10 @command{/bin/sh} cannot be ignored, even with @samp{||}.
18402 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18403 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18409 Moreover, a command substitution, successful or not, causes this shell to
18410 exit from a failing outer command even in presence of an @samp{&&} list:
18413 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18415 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18419 @cindex @command{set -b}
18420 @cindex @command{set -m}
18421 Job control is not provided by all shells, so the use of @samp{set -m}
18422 or @samp{set -b} must be done with care. When using @command{zsh} in
18423 native mode, asynchronous notification (@samp{set -b}) is enabled by
18424 default, and using @samp{emulate sh} to switch to POSIX mode does not
18425 clear this setting (although asynchronous notification has no impact
18426 unless job monitoring is also enabled). Also, @command{zsh} 4.3.10 and
18427 earlier have a bug where job control can be manipulated in interactive
18428 shells, but not in subshells or scripts. Furthermore, some shells, like
18429 @command{pdksh}, fail to treat subshells as interactive, even though the
18433 $ @kbd{echo $ZSH_VERSION}
18435 $ @kbd{set -m; echo $?}
18437 $ @kbd{zsh -c 'set -m; echo $?'}
18438 set: can't change option: -m
18439 $ @kbd{(set -m); echo $?}
18440 set: can't change option: -m
18442 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18447 @cindex @command{set -n}
18448 Use of @command{set -n} (typically via @command{sh -n script}) to
18449 validate a script is not foolproof. Modern @command{ksh93} tries to be
18450 helpful by informing you about better syntax, but switching the script
18451 to use the suggested syntax in order to silence the warnings would
18452 render the script no longer portable to older shells:
18455 $ @kbd{ksh -nc '``'}
18456 ksh: warning: line 1: `...` obsolete, use $(...)
18461 itself uses @command{sh -n} within its testsuite to check that correct
18462 scripts were generated, but only after first probing for other shell
18463 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18464 a reasonably fast and working implementation.
18466 @item @command{shift}
18467 @c ------------------
18468 @prindex @command{shift}
18469 Not only is @command{shift}ing a bad idea when there is nothing left to
18470 shift, but in addition it is not portable: the shell of MIPS
18471 RISC/OS 4.52 refuses to do it.
18473 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18474 it is also absent in many pre-POSIX shells.
18477 @item @command{source}
18478 @c -------------------
18479 @prindex @command{source}
18480 This command is not portable, as POSIX does not require it; use
18481 @command{.} instead.
18484 @item @command{test}
18485 @c -----------------
18486 @prindex @command{test}
18487 The @code{test} program is the way to perform many file and string
18488 tests. It is often invoked by the alternate name @samp{[}, but using
18489 that name in Autoconf code is asking for trouble since it is an M4 quote
18492 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18493 present in all implementations, and have been marked obsolete by POSIX
18494 2008. This is because there are inherent ambiguities in using them.
18495 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18496 check whether two strings are both non-empty, but if @samp{$1} is the
18497 literal @samp{!}, then some implementations of @command{test} treat it
18498 as a negation of the unary operator @option{-a}.
18500 Thus, portable uses of @command{test} should never have more than four
18501 arguments, and scripts should use shell constructs like @samp{&&} and
18502 @samp{||} instead. If you combine @samp{&&} and @samp{||} in the same
18503 statement, keep in mind that they have equal precedence, so it is often
18504 better to parenthesize even when this is redundant. For example:
18508 test "X$a" = "X$b" -a \
18509 '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18512 test "X$a" = "X$b" &&
18513 @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18516 @command{test} does not process options like most other commands do; for
18517 example, it does not recognize the @option{--} argument as marking the
18520 It is safe to use @samp{!} as a @command{test} operator. For example,
18521 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18522 -d foo; @dots{}} is not.
18525 @item @command{test} (files)
18526 @c -------------------------
18527 To enable @command{configure} scripts to support cross-compilation, they
18528 shouldn't do anything that tests features of the build system instead of
18529 the host system. But occasionally you may find it necessary to check
18530 whether some arbitrary file exists. To do so, use @samp{test -f},
18531 @samp{test -r}, or @samp{test -x}. Do not use @samp{test -e}, because
18532 Solaris 10 @command{/bin/sh}
18533 lacks it. To test for symbolic links on systems that have them, use
18534 @samp{test -h} rather than @samp{test -L}; either form conforms to
18535 POSIX 1003.1-2001, but @option{-h} has been around longer.
18537 For historical reasons, POSIX reluctantly allows implementations of
18538 @samp{test -x} that will succeed for the root user, even if no execute
18539 permissions are present. Furthermore, shells do not all agree on
18540 whether Access Control Lists should affect @samp{test -r}, @samp{test
18541 -w}, and @samp{test -x}; some shells base test results strictly on the
18542 current user id compared to file owner and mode, as if by
18543 @code{stat(2)}; while other shells base test results on whether the
18544 current user has the given right, even if that right is only granted by
18545 an ACL, as if by @code{faccessat(2)}. Furthermore, there is a classic
18546 time of check to time of use race between any use of @command{test}
18547 followed by operating on the just-checked file. Therefore, it is a good
18548 idea to write scripts that actually attempt an operation, and are
18549 prepared for the resulting failure if permission is denied, rather than
18550 trying to avoid an operation based solely on whether @command{test}
18551 guessed that it might not be permitted.
18553 @item @command{test} (strings)
18554 @c ---------------------------
18555 POSIX says that @samp{test "@var{string}"} succeeds if @var{string} is
18556 not null, but this usage is not portable to traditional platforms like
18557 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18558 @samp{-n}. However, it @emph{is} portable to test if a variable is set
18559 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18560 implementations properly distinguish between no arguments and a
18561 known-safe string of @samp{y}.
18563 POSIX also says that @samp{test ! "@var{string}"},
18564 @samp{test -n "@var{string}"} and
18565 @samp{test -z "@var{string}"} work with any string, but many
18566 shells (such as Solaris 10, AIX 3.2, UNICOS 10.0.0.6,
18567 Digital Unix 4, etc.)@: get confused if
18568 @var{string} looks like an operator:
18572 test: argument expected
18574 test: argument expected
18575 $ @kbd{test -z ")"; echo $?}
18579 Similarly, POSIX says that both @samp{test "@var{string1}" = "@var{string2"}}
18580 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18581 strings, but in practice this is not true for troublesome strings that
18582 look like operators or parentheses, or that begin with @samp{-}.
18584 It is best to protect such strings with a leading @samp{X}, e.g.,
18585 @samp{test "X@var{string}" != X} rather than @samp{test -n
18586 "@var{string}"} or @samp{test ! "@var{string}"}.
18588 It is common to find variations of the following idiom:
18591 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18596 to take an action when a token matches a given pattern. Such constructs
18597 should be avoided by using:
18600 AS_CASE([$ac_feature],
18601 [[*[!-a-zA-Z0-9_]*]], [@var{action}])
18604 If the pattern is a complicated regular expression that cannot be
18605 expressed as a shell pattern, use something like this instead:
18608 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18612 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18613 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18614 @samp{@var{foo}} contains backslashes.
18618 @item @command{trap}
18619 @c -----------------
18620 @prindex @command{trap}
18621 It is safe to trap at least the signals 1, 2, 13, and 15. You can also
18622 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18623 explicit @command{exit}, or the end of the script). The trap for 0 should be
18624 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18625 will invoke the trap at the end of this function.
18627 POSIX says that @samp{trap - 1 2 13 15} resets the traps for the
18628 specified signals to their default values, but many common shells (e.g.,
18629 Solaris 10 @command{/bin/sh}) misinterpret this and attempt to execute a
18630 ``command'' named @command{-} when the specified conditions arise.
18631 POSIX 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18632 reset traps, as this is supported by a larger set of shells, but there
18633 are still shells like @command{dash} that mistakenly try to execute
18634 @command{1} instead of resetting the traps. Therefore, there is no
18635 portable workaround, except for @samp{trap - 0}, for which
18636 @samp{trap '' 0} is a portable substitute.
18638 Although POSIX is not absolutely clear on this point, it is widely
18639 admitted that when entering the trap @samp{$?} should be set to the exit
18640 status of the last command run before the trap. The ambiguity can be
18641 summarized as: ``when the trap is launched by an @command{exit}, what is
18642 the @emph{last} command run: that before @command{exit}, or
18643 @command{exit} itself?''
18645 Bash considers @command{exit} to be the last command, while Zsh and
18646 Solaris 10 @command{/bin/sh} consider that when the trap is run it is
18647 @emph{still} in the @command{exit}, hence it is the previous exit status
18648 that the trap receives:
18651 $ @kbd{cat trap.sh}
18654 $ @kbd{zsh trap.sh}
18656 $ @kbd{bash trap.sh}
18660 The portable solution is then simple: when you want to @samp{exit 42},
18661 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18662 set the exit status to 42 for Zsh, and the second to trigger the trap
18663 and pass 42 as exit status for Bash. In M4sh, this is covered by using
18666 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18667 reset to 0 by empty lines if the code is inside @command{trap}.
18670 $ @kbd{trap 'false}
18678 Fortunately, this bug only affects @command{trap}.
18680 Several shells fail to execute an exit trap that is defined inside a
18681 subshell, when the last command of that subshell is not a builtin. A
18682 workaround is to use @samp{exit $?} as the shell builtin.
18685 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18687 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18688 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18693 Likewise, older implementations of @command{bash} failed to preserve
18694 @samp{$?} across an exit trap consisting of a single cleanup command.
18697 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18699 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18701 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18705 Be aware that a trap can be called from any number of places in your
18706 script, and therefore the trap handler should not make assumptions about
18707 shell state. For some examples, if your script temporarily modifies
18708 @env{IFS}, then the trap should include an initialization back to its
18709 typical value of space-tab-newline (autoconf does this for generated
18710 @file{configure} files). Likewise, if your script changes the current
18711 working directory at some point after the trap is installed, then your
18712 trap cannot assume which directory it is in, and should begin by
18713 changing directories to an absolute path if that is important to the
18714 cleanup efforts (autotest does this for generated @file{testsuite}
18717 @item @command{true}
18718 @c -----------------
18719 @prindex @command{true}
18720 @c Info cannot handle ':' in index entries.
18721 @c @prindex @command{:}
18722 Don't worry: as far as we know @command{true} is portable.
18723 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18724 portable shell community tends to prefer using @command{:}. This has a
18725 funny side effect: when asked whether @command{false} is more portable
18726 than @command{true} Alexandre Oliva answered:
18729 In a sense, yes, because if it doesn't exist, the shell will produce an
18730 exit status of failure, which is correct for @command{false}, but not
18731 for @command{true}.
18734 Remember that even though @samp{:} ignores its arguments, it still takes
18735 time to compute those arguments. It is a good idea to use double quotes
18736 around any arguments to @samp{:} to avoid time spent in field splitting
18737 and file name expansion.
18741 @item @command{unset}
18742 @c ------------------
18743 @prindex @command{unset}
18744 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18745 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18746 @code{unset FOO} fails when @code{FOO} is not set. This can interfere
18747 with @code{set -e} operation. You can use
18754 if you are not sure that @code{FOO} is set.
18756 A few ancient shells lack @command{unset} entirely. For some variables
18757 such as @code{PS1}, you can use a neutralizing value instead:
18763 Usually, shells that do not support @command{unset} need less effort to
18764 make the environment sane, so for example is not a problem if you cannot
18765 unset @command{CDPATH} on those shells. However, Bash 2.01 mishandles
18766 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18767 So, you should do something like
18770 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18774 @xref{Special Shell Variables}, for some neutralizing values. Also, see
18775 @ref{export, , Limitations of Builtins}, for
18776 the case of environment variables.
18778 @item @command{wait}
18779 @c -----------------
18780 @prindex @command{wait}
18781 The exit status of @command{wait} is not always reliable.
18784 @node Limitations of Usual Tools
18785 @section Limitations of Usual Tools
18786 @cindex Limitations of usual tools
18788 The small set of tools you can expect to find on any machine can still
18789 include some limitations you should be aware of.
18791 @comment Between this list and the list of builtins above, we should
18792 @comment mention all the tools in GNU Coding Standards ``Utilities in
18793 @comment Makefiles''.
18795 @c This table includes things like '@command{expr} (|)', so we can't
18796 @c use @table @command.
18799 @item @command{awk}
18800 @c ----------------
18801 @prindex @command{awk}
18802 Don't leave white space before the opening parenthesis in a user function call.
18803 POSIX does not allow this and GNU Awk rejects it:
18806 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
18807 BEGIN @{ die () @}'}
18808 gawk: cmd. line:2: BEGIN @{ die () @}
18809 gawk: cmd. line:2: ^ parse error
18810 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
18811 BEGIN @{ die() @}'}
18815 POSIX says that if a program contains only @samp{BEGIN} actions, and
18816 contains no instances of @code{getline}, then the program merely
18817 executes the actions without reading input. However, traditional Awk
18818 implementations (such as Solaris 10 @command{awk}) read and discard
18819 input in this case. Portable scripts can redirect input from
18820 @file{/dev/null} to work around the problem. For example:
18823 awk 'BEGIN @{print "hello world"@}' </dev/null
18826 POSIX says that in an @samp{END} action, @samp{$NF} (and presumably,
18827 @samp{$1}) retain their value from the last record read, if no
18828 intervening @samp{getline} occurred. However, some implementations
18829 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18830 @samp{awk}) reset these variables. A workaround is to use an
18831 intermediate variable prior to the @samp{END} block. For example:
18834 $ @kbd{cat end.awk}
18836 END @{ print "a", $1, $NF, "b", tmp @}
18837 $ @kbd{echo 1 | awk -f end.awk}
18839 $ @kbd{echo 1 | gawk -f end.awk}
18843 If you want your program to be deterministic, don't depend on @code{for}
18847 $ @kbd{cat for.awk}
18854 $ @kbd{gawk -f for.awk </dev/null}
18857 $ @kbd{nawk -f for.awk </dev/null}
18862 Some Awk implementations, such as HP-UX 11.0's native one,
18866 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18867 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18869 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18871 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18876 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18877 or use a simple test to reject such implementations.
18879 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18883 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18887 AIX version 5.2 has an arbitrary limit of 399 on the
18888 length of regular expressions and literal strings in an Awk program.
18890 Traditional Awk implementations derived from Unix version 7, such as
18891 Solaris @command{/bin/awk}, have many limitations and do not
18892 conform to POSIX. Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18893 Programs}) finds you an Awk that doesn't have these problems, but if
18894 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18895 address them. For more detailed descriptions, see @ref{Language
18896 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18898 Traditional Awk does not support multidimensional arrays or user-defined
18901 Traditional Awk does not support the @option{-v} option. You can use
18902 assignments after the program instead, e.g., @code{$AWK '@{print v
18903 $1@}' v=x}; however, don't forget that such assignments are not
18904 evaluated until they are encountered (e.g., after any @code{BEGIN}
18907 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18909 Traditional Awk does not support the expressions
18910 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18911 or @code{@var{a}^=@var{b}}.
18913 Traditional Awk does not support the predefined @code{CONVFMT} or
18914 @code{ENVIRON} variables.
18916 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18917 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18918 @code{sqrt}, and @code{substr}.
18920 Traditional Awk @code{getline} is not at all compatible with POSIX;
18923 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18924 @code{in} keyword. For example, it lacks @code{if (i in a) @dots{}}.
18926 In code portable to both traditional and modern Awk, @code{FS} must be a
18927 string containing just one ordinary character, and similarly for the
18928 field-separator argument to @code{split}.
18930 Traditional Awk has a limit of 99 fields in a record
18931 and splits the input even if you don't refer to any field in the script.
18932 To circumvent this problem, set @samp{FS}
18933 to an unusual character and use @code{split}.
18935 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18936 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18939 The original version of Awk had a limit of at most 99 bytes per
18940 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18941 per run of non-special characters in a @code{printf} format, but these
18942 bugs have been fixed on all practical hosts that we know of.
18944 HP-UX 11.00 Awk requires that input files have a line length
18945 of at most 3070 bytes.
18947 @item @command{basename}
18948 @c ---------------------
18949 @prindex @command{basename}
18950 Long ago some hosts lacked a working @command{basename},
18951 and portable scripts needed to use @command{expr} instead.
18952 Nowadays it is safe to use @command{basename}. For example:
18955 base=`basename -- "$file"`
18958 @c AS_BASENAME is to be replaced by a better API.
18960 Not all hosts have a working @command{basename}, and you should instead
18961 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18962 @command{expr} if you need to strip a suffix. For example:
18965 a=`basename "$aname"` # This is not portable.
18966 a=`AS_BASENAME(["$aname"])` # This is more portable.
18968 # This is not portable.
18969 c=`basename "$cname" .c`
18971 # This is more portable.
18972 c=`AS_BASENAME(["$cname"])`
18974 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18980 @item @command{cat}
18981 @c ----------------
18982 @prindex @command{cat}
18983 Don't rely on any option.
18988 @prindex @command{cc}
18989 The command @samp{cc -c foo.c} traditionally produces an object file
18990 named @file{foo.o}. Most compilers allow @option{-c} to be combined
18991 with @option{-o} to specify a different object file name, but
18992 POSIX does not require this combination and a few compilers
18993 lack support for it. @xref{C Compiler}, for how GNU Make
18994 tests for this feature with @code{AC_PROG_CC_C_O}.
18996 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18997 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18999 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
19000 assemble. @samp{cc -c foo.S} appears to succeed, but in fact does
19003 The default executable, produced by @samp{cc foo.c}, can be
19006 @item @file{a.out} -- usual POSIX convention.
19007 @item @file{b.out} -- i960 compilers (including @command{gcc}).
19008 @item @file{a.exe} -- DJGPP port of @command{gcc}.
19009 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
19010 @item @file{foo.exe} -- various MS-DOS compilers.
19013 The C compiler's traditional name is @command{cc}, but other names like
19014 @command{gcc} are common. POSIX 1003.1-2001 through 1003.1-2017 specify the
19015 name @command{c99}, but older POSIX editions specified
19016 @command{c89}, future POSIX standards will likely specify
19017 other commands, and anyway these standard names are rarely used in
19018 practice. Typically the C compiler is invoked from makefiles that use
19019 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
19022 @item @command{chgrp}
19023 @itemx @command{chown}
19024 @c -------------------
19025 @prindex @command{chgrp}
19026 @prindex @command{chown}
19027 It is not portable to change a file's group to a group that the owner
19028 does not belong to.
19030 @item @command{chmod}
19031 @c ------------------
19032 @prindex @command{chmod}
19033 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
19034 instead, for two reasons. First, plain @option{-w} does not necessarily
19035 make the file unwritable, since it does not affect mode bits that
19036 correspond to bits in the file mode creation mask. Second,
19037 POSIX says that the @option{-w} might be interpreted as an
19038 implementation-specific option, not as a mode; POSIX suggests
19039 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
19040 @samp{--} does not work on some older hosts.
19043 @item @command{cmp}
19044 @c ----------------
19045 @prindex @command{cmp}
19046 @command{cmp} performs a raw data comparison of two files, while
19047 @command{diff} compares two text files. Therefore, if you might compare
19048 DOS files, even if only checking whether two files are different, use
19049 @command{diff} to avoid spurious differences due to differences of
19055 @prindex @command{cp}
19056 The @option{-i}, @option{-f}, @option{-p} and @option{-R} options are
19057 widely used. POSIX also specifies @option{-H}, @option{-L}, and
19058 @option{-P}. Avoid other options in portable scripts.
19060 @cindex timestamp resolution
19061 Traditionally, file timestamps had 1-second resolution, and @samp{cp
19062 -p} copied the timestamps exactly. However, many modern file systems
19063 have timestamps with 1-nanosecond resolution. Unfortunately, some older
19064 @samp{cp -p} implementations truncate timestamps when copying files,
19065 which can cause the destination file to appear to be older than the
19066 source. The exact amount of truncation depends on the resolution of
19067 the system calls that @command{cp} uses. Traditionally this was
19068 @code{utime}, which has 1-second resolution. Less-ancient @command{cp}
19069 implementations such as GNU Core Utilities 5.0.91 (2003) use
19070 @code{utimes}, which has 1-microsecond resolution. Modern
19071 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
19072 the full nanosecond resolution, using the modern system calls
19073 @code{futimens} and @code{utimensat} when they are available. As of
19074 2011, though, many platforms do not yet fully support these new system
19077 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
19078 ownerships. But whether it actually does copy ownerships or not is a
19079 system dependent policy decision implemented by the kernel. If the
19080 kernel allows it then it happens. If the kernel does not allow it then
19081 it does not happen. It is not something @command{cp} itself has control
19084 In Unix System V any user can chown files to any other user, and System
19085 V also has a non-sticky @file{/tmp}. That probably derives from the
19086 heritage of System V in a business environment without hostile users.
19088 to be a more secure model where only root can @command{chown} files and
19089 a sticky @file{/tmp} is used. That undoubtedly derives from the heritage
19090 of BSD in a campus environment.
19092 GNU/Linux and Solaris by default follow BSD, but
19093 can be configured to allow a System V style @command{chown}. On the
19094 other hand, HP-UX follows System V, but can
19095 be configured to use the modern security model and disallow
19096 @command{chown}. Since it is an administrator-configurable parameter
19097 you can't use the name of the kernel as an indicator of the behavior.
19101 @item @command{date}
19102 @c -----------------
19103 @prindex @command{date}
19104 When most versions of @command{date} do not recognize a @samp{%}
19105 conversion specification, they quietly pass it through,
19106 and exit with success:
19109 $ @kbd{date --version | head -n 1}
19110 date (GNU coreutils) 9.5
19111 $ @kbd{date +'%H:%M %Q'}
19116 However, this behavior is not required by POSIX.
19119 @item @command{dirname}
19120 @c --------------------
19121 @prindex @command{dirname}
19122 Long ago some hosts lacked a working @command{dirname} and portable
19123 scripts needed to use use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).
19124 Nowadays @command{dirname} suffices and the following are equivalent:
19127 dir=`dirname -- "$file"`
19128 dir=`AS_DIRNAME(["$file"])`
19132 @item @command{egrep}
19133 @c ------------------
19134 @prindex @command{egrep}
19135 Although POSIX stopped requiring @command{egrep} in 2001,
19136 a few traditional hosts (notably Solaris 10) do not support the POSIX
19137 replacement @code{grep -E}. Also, some traditional implementations do
19138 not work on long input lines. To work around these problems, invoke
19139 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
19141 Portable extended regular expressions should use @samp{\} only to escape
19142 characters in the string @samp{$()*+.?[\^@{|}. For example, @samp{\@}}
19143 is not portable, even though it typically matches @samp{@}}.
19145 The empty alternative is not portable. Use @samp{?} instead. For
19146 instance with Digital Unix v5.0:
19149 > printf 'foo\n|foo\n' | $EGREP '^(|foo|bar)$'
19151 > printf 'bar\nbar|\n' | $EGREP '^(foo|bar|)$'
19153 > printf 'foo\nfoo|\n|bar\nbar\n' | $EGREP '^(foo||bar)$'
19158 For more information about what can appear in portable extended regular
19159 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
19161 @command{$EGREP} also suffers the limitations of @command{grep}
19162 (@pxref{grep, , Limitations of Usual Tools}).
19164 @item @command{expr}
19165 @c -----------------
19166 @prindex @command{expr}
19167 Not all implementations obey the POSIX rule that @samp{--} separates
19168 options from arguments; likewise, not all implementations provide the
19169 extension to POSIX that the first argument can be treated as part of a
19170 valid expression rather than an invalid option if it begins with
19171 @samp{-}. When performing arithmetic, use @samp{expr 0 + $var} if
19172 @samp{$var} might be a negative number, to keep @command{expr} from
19173 interpreting it as an option.
19175 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
19176 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
19177 misinterpreting @var{word}.
19179 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
19181 @item @command{expr} (@samp{|})
19182 @prindex @command{expr} (@samp{|})
19183 You can use @samp{|}. Although POSIX does require that @samp{expr
19184 ''} return the empty string, it does not specify the result when you
19185 @samp{|} together the empty string (or zero) with the empty string. For
19192 POSIX 1003.2-1992 returns the empty string
19193 for this case, but traditional Unix returns @samp{0} (Solaris is
19194 one such example). In POSIX 1003.1-2001, the specification was
19195 changed to match traditional Unix's behavior (which is
19196 bizarre, but it's too late to fix this). Please note that the same
19197 problem does arise when the empty string results from a computation,
19201 expr bar : foo \| foo : bar
19205 Avoid this portability problem by avoiding the empty string.
19208 @item @command{expr} (@samp{:})
19209 @c ----------------------------
19210 @prindex @command{expr}
19211 Portable @command{expr} regular expressions should use @samp{\} to
19212 escape only characters in the string @samp{$()*.123456789[\^@{@}}.
19213 For example, alternation, @samp{\|}, is common but POSIX does not
19214 require its support, so it should be avoided in portable scripts.
19215 Similarly, @samp{\+} and @samp{\?} should be avoided.
19217 Portable @command{expr} regular expressions should not begin with
19218 @samp{^}. Patterns are automatically anchored so leading @samp{^} is
19221 On the other hand, the behavior of the @samp{$} anchor is not portable
19222 on multi-line strings. POSIX is ambiguous whether the anchor applies to
19223 each line, as was done in older versions of the GNU Core Utilities, or
19224 whether it applies only to the end of the overall string, as in
19225 Coreutils 6.0 and most other implementations.
19230 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19232 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19236 The POSIX standard is ambiguous as to whether
19237 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19238 In practice, it outputs the empty string on most platforms, but portable
19239 scripts should not assume this. For instance, the QNX 4.25 native
19240 @command{expr} returns @samp{0}.
19242 One might think that a way to get a uniform behavior would be to use
19243 the empty string as a default value:
19246 expr a : '\(b\)' \| ''
19250 Unfortunately this behaves exactly as the original expression; see the
19251 @command{expr} (@samp{|}) entry for more information.
19253 Some ancient @command{expr} implementations (e.g.,
19254 Solaris 10 @command{/usr/ucb/expr}) have a silly length limit that causes
19255 @command{expr} to fail if the matched substring is longer than 120
19256 bytes. In this case, you might want to fall back on @samp{printf|sed} if
19257 @command{expr} fails. Nowadays this is of practical importance only for
19258 the rare installer who mistakenly puts @file{/usr/ucb} before
19259 @file{/usr/bin} in @env{PATH} on Solaris 10.
19261 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19262 some cases. For example, the command
19264 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19268 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19269 This particular case can be worked around by substituting @samp{[^--]}
19272 Don't leave, there is some more!
19274 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19275 the empty string, has a funny behavior in its exit status: it's always 1
19276 when parentheses are used!
19279 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19281 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19284 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19286 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19291 In practice this can be a big problem if you are ready to catch failures
19292 of @command{expr} programs with some other method (such as using
19293 @command{sed}), since you may get twice the result. For instance
19296 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19300 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25. A
19301 simple workaround consists of testing @command{expr} and using a variable
19302 set to @command{expr} or to @command{false} according to the result.
19304 On HP-UX 11, @command{expr} supports only a single
19308 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19309 expr: More than one '\(' was used.
19313 @item @command{fgrep}
19314 @c ------------------
19315 @prindex @command{fgrep}
19316 Although POSIX stopped requiring @command{fgrep} in 2001,
19317 a few traditional hosts (notably Solaris 10) do not support the POSIX
19318 replacement @code{grep -F}. Also, some traditional implementations do
19319 not work on long input lines. To work around these problems, invoke
19320 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19323 @item @command{find}
19324 @c -----------------
19325 @prindex @command{find}
19326 Many operands of GNU @command{find} are not standardized by POSIX and
19327 are missing on many platforms. These nonportable operands include
19328 @option{-follow}, @option{-maxdepth}, @option{-mindepth},
19329 @option{-printf}, and @option{,}. See the
19330 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/find.html,
19331 POSIX spec for @command{find}} for @command{find} operands that
19332 should be portable nowadays.
19334 The replacement of @samp{@{@}} is guaranteed only if the argument is
19335 exactly @emph{@{@}}, not if it's only a part of an argument. For
19336 instance, on HP-UX 11:
19340 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19345 while GNU @command{find} reports @samp{./foo-./foo}.
19346 POSIX allows either behavior.
19350 @item @command{grep}
19351 @c -----------------
19352 @prindex @command{grep}
19353 Portable scripts can rely on the @command{grep} options @option{-c},
19354 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19355 options. For example, don't use @option{-w}, as POSIX does not require it.
19356 Also, portable scripts should not combine @option{-c} with @option{-l},
19357 as POSIX does not allow this.
19359 Some of the options required by POSIX are not portable in practice.
19360 Don't use @samp{grep -q} to suppress output, because traditional @command{grep}
19361 implementations (e.g., Solaris 10) do not support @option{-q}.
19362 Don't use @samp{grep -s} to suppress output either, because POSIX
19363 says @option{-s} does not suppress output, only some error messages;
19364 also, the @option{-s} option of traditional @command{grep} behaved
19365 like @option{-q} does in most modern implementations. Instead,
19366 redirect the standard output and standard error (in case the file
19367 doesn't exist) of @code{grep} to @file{/dev/null}. Check the exit
19368 status of @code{grep} to determine whether it found a match.
19370 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19371 but works with @code{grep -c '^'}. Other alternatives for counting
19372 lines are to use @code{sed -n '$='} or @code{wc -l}.
19374 Some traditional @command{grep} implementations do not work on long
19375 input lines. On AIX the default @code{grep} silently truncates long
19376 lines on the input before matching.
19378 Also, Solaris 10 @command{grep} does not support @option{-e}.
19379 To work around this, invoke @code{AC_PROG_GREP} and then use @code{$GREP}.
19381 Another possible workaround for the multiple @option{-e} problem is to
19382 separate the patterns by newlines, for example:
19390 except that this fails with traditional @command{grep}
19391 implementations and with OpenBSD 3.8 @command{grep}.
19393 Traditional @command{grep} implementations (e.g., Solaris 10) do not
19394 support the @option{-E} or @option{-F} options. To work around these
19395 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19396 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}. Even if you are
19397 willing to require support for POSIX @command{grep}, your script should
19398 not use both @option{-E} and @option{-F}, since POSIX does not allow
19401 Portable @command{grep} regular expressions should use @samp{\} only to
19402 escape characters in the string @samp{$()*.123456789[\^@{@}}. For example,
19403 alternation, @samp{\|}, is common but POSIX does not require its
19404 support in basic regular expressions, so it should be avoided in
19405 portable scripts. Solaris and HP-UX @command{grep} do not support it.
19406 Similarly, the following escape sequences should also be avoided:
19407 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19408 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19409 For more information about what can appear in portable regular expressions,
19410 @pxref{Problematic Expressions,,, grep, GNU Grep}.
19412 POSIX does not specify the behavior of @command{grep} on binary files.
19413 An example where this matters is using BSD @command{grep} to
19414 search text that includes embedded ANSI escape sequences for
19415 colored output to terminals (@samp{\033[m} is the sequence to restore
19416 normal output); the behavior depends on whether input is seekable:
19419 $ @kbd{printf 'esc\033[mape\n' > sample}
19420 $ @kbd{grep . sample}
19421 Binary file sample matches
19422 $ @kbd{cat sample | grep .}
19427 @item @command{join}
19428 @c -----------------
19429 @prindex @command{join}
19430 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19431 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19432 the workaround is to use @command{join -a1 file1 file2} instead.
19434 On some circa-2020 BSD-based systems @command{join} mishandles inputs
19435 with missing fields. For example, an empty line is not treated as
19436 containing an empty join field. As a workaround, input lines should
19437 always have a join field.
19439 On platforms with the BusyBox tools, the @command{join} command is
19440 entirely missing. As a workaround, you can simulate special cases of the
19441 @command{join} command using an @command{awk} script. For an example,
19442 see @url{https://lists.gnu.org/r/bug-gnulib/2021-04/msg00054.html}.
19447 @prindex @command{ln}
19448 The @option{-f} option is portable nowadays.
19450 @cindex Symbolic links
19451 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19452 a portable substitute.
19454 For versions of the DJGPP before 2.04,
19455 @command{ln} emulates symbolic links
19456 to executables by generating a stub that in turn calls the real
19457 program. This feature also works with nonexistent files like in the
19458 POSIX spec. So @samp{ln -s file link} generates @file{link.exe},
19459 which attempts to call @file{file.exe} if run. But this feature only
19460 works for executables, so @samp{cp -p} is used instead for these
19461 systems. DJGPP versions 2.04 and later have full support
19462 for symbolic links.
19467 @prindex @command{ls}
19468 @cindex Listing directories
19469 The portable options are @option{-acdilrtu}. Current practice is for
19470 @option{-l} to output both owner and group, even though ancient versions
19471 of @command{ls} omitted the group.
19473 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19474 to standard output if @file{foo} did not exist. Hence a shell command
19475 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19476 was equivalent to @samp{sources='*.c not found'} in the absence of
19477 @samp{.c} files. This is no longer a practical problem, since current
19478 @command{ls} implementations send diagnostics to standard error.
19480 The behavior of @command{ls} on a directory that is being concurrently
19481 modified is not always predictable, because of a data race where cached
19482 information returned by @code{readdir} does not match the current
19483 directory state. In fact, Mac OS X 10.5 had an intermittent bug where
19484 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19485 once if other files were added or removed from the directory immediately
19486 prior to the @command{ls} call. Since @command{ls} already sorts its
19487 output, the duplicate entries can be avoided by piping the results
19488 through @code{uniq}.
19491 @item @command{mkdir}
19492 @c ------------------
19493 @prindex @command{mkdir}
19494 @cindex Making directories
19495 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19496 go-w -p @var{dir}}, often leads to trouble. FreeBSD
19497 @command{mkdir} incorrectly attempts to change the permissions of
19498 @var{dir} even if it already exists. HP-UX 11.23
19499 @command{mkdir} often assigns the wrong permissions to
19500 any newly-created parents of @var{dir}.
19502 POSIX does not clearly specify whether @samp{mkdir -p foo}
19503 should succeed when @file{foo} is a symbolic link to an already-existing
19504 directory. The GNU @command{mkdir}
19505 succeeds, but Solaris 10 @command{mkdir} fails.
19507 Traditional @code{mkdir -p} implementations suffer from race conditions.
19508 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19509 at the same time, both processes might detect that @file{a} is missing,
19510 one might create @file{a}, then the other might try to create @file{a}
19511 and fail with a @code{File exists} diagnostic. Solaris 10 @command{mkdir}
19512 is vulnerable, and other traditional Unix systems are
19513 probably vulnerable too. This possible race is harmful in parallel
19514 builds when several Make rules call @code{mkdir -p} to
19515 construct directories. You may use
19516 @code{install-sh -d} as a safe replacement, for example by setting
19517 @samp{MKDIR_P='/path/to/install-sh -d'} in the environment of
19518 @command{configure}, assuming the package distributes @file{install-sh}.
19520 @item @command{mkfifo}
19521 @itemx @command{mknod}
19522 @c -------------------
19523 @prindex @command{mkfifo}
19524 @prindex @command{mknod}
19525 The GNU Coding Standards state that @command{mknod} is safe to use on
19526 platforms where it has been tested to exist; but it is generally portable
19527 only for creating named FIFOs, since device numbers are
19528 platform-specific. Autotest uses @command{mkfifo} to implement parallel
19529 testsuites. POSIX states that behavior is unspecified when opening a
19530 named FIFO for both reading and writing; on at least Cygwin, this
19531 results in failure on any attempt to read or write to that file
19534 @item @command{mktemp}
19535 @c -------------------
19536 @prindex @command{mktemp}
19537 @cindex Creating temporary files
19538 Shell scripts can use temporary files safely with @command{mktemp}, but
19539 it does not exist on all systems. A portable way to create a safe
19540 temporary file name is to create a temporary directory with mode 700 and
19541 use a file inside this directory. Both methods prevent attackers from
19542 gaining control, though @command{mktemp} is far less likely to fail
19543 gratuitously under attack.
19545 Here is sample code to create a new temporary directory @samp{$dir} safely:
19548 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19549 # Use mktemp if possible; otherwise fall back on mkdir,
19550 # with $RANDOM to make collisions less likely.
19551 : "$@{TMPDIR:=/tmp@}"
19554 (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19558 dir=$TMPDIR/foo$$-$RANDOM
19559 @c $$ restore font-lock
19560 (umask 077 && mkdir "$dir")
19567 @prindex @command{mv}
19568 @cindex Moving open files
19569 The only portable options are @option{-f} and @option{-i}.
19571 Moving individual files between file systems is portable (it was in Unix
19573 but it is not always atomic: when doing @samp{mv new existing}, there's
19574 a critical section where neither the old nor the new version of
19575 @file{existing} actually exists.
19577 On some systems moving files from @file{/tmp} can sometimes cause
19578 undesirable (but perfectly valid) warnings, even if you created these
19579 files. This is because @file{/tmp} belongs to a group that ordinary
19580 users are not members of, and files created in @file{/tmp} inherit
19581 the group of @file{/tmp}. When the file is copied, @command{mv} issues
19582 a diagnostic without failing:
19585 $ @kbd{touch /tmp/foo}
19586 $ @kbd{mv /tmp/foo .}
19587 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19595 This annoying behavior conforms to POSIX, unfortunately.
19597 Moving directories across mount points is not portable, use @command{cp}
19600 DOS variants cannot rename or remove open files, and do not
19601 support commands like @samp{mv foo bar >foo}, even though this is
19602 perfectly portable among POSIX hosts.
19607 @prindex @command{od}
19609 In Mac OS X versions prior to 10.4.3, @command{od} does not support the
19610 standard POSIX options @option{-A}, @option{-j}, @option{-N}, or
19611 @option{-t}, or the XSI option, @option{-s}. The only
19612 supported POSIX option is @option{-v}, and the only supported
19613 XSI options are those in @option{-bcdox}. The BSD
19614 @command{hexdump} program can be used instead.
19616 In some versions of some operating systems derived from Solaris 11,
19617 @command{od} prints decimal byte values padded with zeros rather than
19621 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19629 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19633 We have observed this on both OpenIndiana and OmniOS;
19634 Illumos may also be affected.
19635 As a workaround, you can use octal output (option @code{-t o1}).
19640 @prindex @command{rm}
19641 The @option{-f} and @option{-r} options are portable.
19643 It is not portable to invoke @command{rm} without options or operands.
19644 On the other hand, POSIX now requires @command{rm -f} to silently
19645 succeed when there are no operands (useful for constructs like
19646 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19647 was empty). But this was not always portable; at least NetBSD
19648 @command{rm} built before 2008 would fail with a diagnostic.
19650 A file might not be removed even if its parent directory is writable
19651 and searchable. Many POSIX hosts cannot remove a mount point, a named
19652 stream, a working directory, or a last link to a file that is being
19655 DOS variants cannot rename or remove open files, and do not
19656 support commands like @samp{rm foo >foo}, even though this is
19657 perfectly portable among POSIX hosts.
19659 @item @command{rmdir}
19660 @c ------------------
19661 @prindex @command{rmdir}
19662 Just as with @command{rm}, some platforms refuse to remove a working
19666 @item @command{sed}
19667 @c ----------------
19668 @prindex @command{sed}
19669 Patterns should not include the separator (unless escaped), even as part
19670 of a character class. In conformance with POSIX, the Cray
19671 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19672 Even when escaped, patterns should not include separators that are also
19673 used as @command{sed} metacharacters. For example, GNU sed 4.0.9 rejects
19674 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19675 before evaluating the basic regular expression.
19677 Avoid empty patterns within parentheses (i.e., @samp{\(\)}). POSIX does
19678 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19681 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19683 Sed scripts should not use branch labels longer than 7 characters and
19684 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19685 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19686 48 labels, which cannot be circumvented by using more than one script
19687 file. It can execute up to 19 reads with the @samp{r} command per cycle.
19688 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19689 about 6000 bytes for the internal representation of commands.
19691 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19692 NetBSD 1.4.2's, incorrectly try to interpret the second
19693 @samp{;} as a command:
19696 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19697 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19700 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19701 and this limits the size of input lines, output lines, and internal
19702 buffers that can be processed portably. Likewise,
19703 not all @command{sed} implementations can handle embedded @code{NUL} or
19704 a missing trailing newline.
19706 Remember that ranges within a bracket expression of a regular expression
19707 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19708 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19709 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19710 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19711 than to rely on @samp{[A-Z]}.
19713 Additionally, POSIX states that regular expressions are only
19714 well-defined on characters. Unfortunately, there exist platforms such
19715 as Mac OS X 10.5 where not all 8-bit byte values are valid characters,
19716 even though that platform has a single-byte @samp{C} locale. And POSIX
19717 allows the existence of a multi-byte @samp{C} locale, although that does
19718 not yet appear to be a common implementation. At any rate, it means
19719 that not all bytes will be matched by the regular expression @samp{.}:
19722 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19724 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19728 Portable @command{sed} regular expressions should use @samp{\} only to escape
19729 characters in the string @samp{$()*.123456789[\^n@{@}}. For example,
19730 alternation, @samp{\|}, is common but POSIX does not require its
19731 support, so it should be avoided in portable scripts. Solaris
19732 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19733 deletes only lines that contain the literal string @samp{a|b}.
19734 Similarly, @samp{\+} and @samp{\?} should be avoided.
19736 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19738 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19739 quite portable to current hosts, but was not supported by some ancient
19740 @command{sed} implementations like SVR3.
19742 Some @command{sed} implementations, e.g., Solaris, restrict the special
19743 role of the asterisk @samp{*} to one-character regular expressions and
19744 back-references, and the special role of interval expressions
19745 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19746 to one-character regular expressions. This may lead to unexpected behavior:
19749 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19751 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19755 The @option{-e} option is mostly portable.
19756 However, its argument cannot be empty, as this fails on AIX 7.3.
19757 Some people prefer to use @samp{-e}:
19760 sed -e '@var{command-1}' \
19761 -e '@var{command-2}'
19765 as opposed to the equivalent:
19775 The following usage is sometimes equivalent:
19778 sed '@var{command-1};@var{command-2}'
19781 but POSIX says that this use of a semicolon has undefined effect if
19782 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19783 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19784 should use semicolon only with simple scripts that do not use these
19787 POSIX up to the 2008 revision requires the argument of the @option{-e}
19788 option to be a syntactically complete script. GNU @command{sed} allows
19789 to pass multiple script fragments, each as argument of a separate
19790 @option{-e} option, that are then combined, with newlines between the
19791 fragments, and a future POSIX revision may allow this as well. This
19792 approach is not portable with script fragments ending in backslash; for
19793 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19794 don't allow splitting in this case:
19797 $ @kbd{echo a | sed -n -e 'i\}
19800 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19801 Unrecognized command: 0
19805 In practice, however, this technique of joining fragments
19806 through @option{-e} works for multiple @command{sed} functions within
19807 @samp{@{} and @samp{@}}, even if that is not specified by POSIX:
19810 @c The quote around the closing brace silences interactive zsh.
19811 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19815 Commands inside @{ @} brackets are further restricted. POSIX 2008 says that
19816 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19817 each command must be followed immediately by a newline, without any
19818 intervening blanks or semicolons. The closing bracket must be alone on
19819 a line, other than white space preceding or following it. However, a
19820 future version of POSIX may standardize the use of addresses within brackets.
19822 Contrary to yet another urban legend, you may portably use @samp{&} in
19823 the replacement part of the @code{s} command to mean ``what was
19824 matched''. All descendants of Unix version 7 @command{sed}
19826 don't have first hand experience with older @command{sed} implementations) have
19829 POSIX requires that you must not have any white space between
19830 @samp{!} and the following command. It is OK to have blanks between
19831 the address and the @samp{!}. For instance, on Solaris:
19834 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19835 @error{}Unrecognized command: /bar/ ! p
19836 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19837 @error{}Unrecognized command: /bar/! p
19838 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19842 POSIX also says that you should not combine @samp{!} and @samp{;}. If
19843 you use @samp{!}, it is best to put it on a command that is delimited by
19844 newlines rather than @samp{;}.
19846 Also note that POSIX requires that the @samp{b}, @samp{t}, @samp{r}, and
19847 @samp{w} commands be followed by exactly one space before their argument.
19848 On the other hand, no white space is allowed between @samp{:} and the
19849 subsequent label name.
19851 If a sed script is specified on the command line and ends in an
19852 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19853 should be followed by a newline. Otherwise some @command{sed}
19854 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19857 Many @command{sed} implementations (e.g., Mac OS X 10.4,
19858 OpenBSD 3.9, Solaris 10
19859 @command{/usr/ucb/sed}) strip leading white space from the text of
19860 @samp{a}, @samp{c}, and @samp{i} commands. Prepend a backslash to
19861 work around this incompatibility with POSIX:
19864 $ @kbd{echo flushleft | sed 'a\}
19869 $ @kbd{echo foo | sed 'a\}
19876 POSIX requires that with an empty regular expression, the last non-empty
19877 regular expression from either an address specification or substitution
19878 command is applied. However, busybox 1.6.1 complains when using a
19879 substitution command with a replacement containing a back-reference to
19880 an empty regular expression; the workaround is repeating the regular
19884 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19885 sed: No previous regexp.
19886 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19890 Portable scripts should be aware of the inconsistencies and options for
19891 handling word boundaries, as these are not specified by POSIX.
19895 Solaris 10 yes no no
19896 Solaris XPG4 yes no error
19897 NetBSD 5.1 no no yes
19898 FreeBSD 9.1 no no yes
19900 busybox yes yes error
19903 @item @command{sed} (@samp{t})
19904 @c ---------------------------
19905 @prindex @command{sed} (@samp{t})
19906 There are two things one should remember about @samp{t} in @command{sed}.
19907 First, @samp{t} jumps if @emph{some} substitution
19908 succeeded, not only the immediately preceding substitution. Therefore,
19909 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19910 line, to reset the @samp{t} flag where needed.
19912 Second, do not rely on @command{sed} to clear the flag at each new cycle.
19914 For example, the following script replaces all instances of ``keep me''
19915 with ``kept'', and replaces the contents of all lines that did not
19916 contain ``keep me'' with ``deleted''.
19927 @item @command{sed} (@samp{w})
19928 @c ---------------------------
19929 @prindex @command{sed} (@samp{w})
19931 When a script contains multiple commands to write lines to the same
19932 output file, BusyBox @command{sed} mistakenly opens a separate output
19933 stream for each command. This can cause one of the commands to ``win''
19934 and the others to ``lose'', in the sense that their output is discarded.
19947 This might output only @samp{a} to @file{xxx}; the @samp{b} is lost.
19948 To avoid the problem, a portable script should contain at most one
19949 @samp{w} or @samp{s/.../.../w} command per output file.
19951 @item @command{sleep}
19952 @c ------------------
19953 @prindex @command{sleep}
19954 Using @command{sleep} is generally portable. However, remember that
19955 adding a @command{sleep} to work around timestamp issues, with a minimum
19956 granularity of one second, doesn't scale well for parallel builds on
19957 modern machines with sub-second process completion.
19959 @item @command{sort}
19960 @c -----------------
19961 @prindex @command{sort}
19962 Remember that sort order is influenced by the current locale. Inside
19963 @file{configure}, the C locale is in effect, but in Makefile snippets,
19964 you may need to specify @code{LC_ALL=C sort}.
19966 @item @command{tar}
19967 @c ----------------
19968 @prindex @command{tar}
19969 There are multiple file formats for @command{tar}; if you use Automake,
19970 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19971 level of portability to use.
19974 @item @command{touch}
19975 @c ------------------
19976 @prindex @command{touch}
19977 @cindex timestamp resolution
19978 If you specify the desired timestamp (e.g., with the @option{-r}
19979 option), older @command{touch} implementations use the @code{utime} or
19980 @code{utimes} system call, which can result in the same kind of
19981 timestamp truncation problems that @samp{cp -p} has.
19985 @prindex @command{tr}
19986 @cindex carriage return, deleting
19987 @cindex newline, deleting
19988 @cindex deleting carriage return
19989 Not all versions of @command{tr} handle all backslash character escapes.
19990 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19991 Solaris contains more modern @command{tr} in other locations.
19992 Using octal escapes is more portable for carriage returns, since
19993 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19994 literal carriage returns in scripts causes a number of other problems.
19995 But for other characters, like newline, using octal escapes ties the
19996 operation to ASCII, so it is better to use literal characters.
19999 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
20002 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
20004 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
20007 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
20011 Not all versions of @command{tr} recognize direct ranges of characters: at
20012 least Solaris @command{/usr/bin/tr} still fails to do so. But you can
20013 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in POSIX
20014 transliterate to themselves).
20017 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
20019 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
20021 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
20025 When providing two arguments, be sure the second string is at least as
20029 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
20031 $ @kbd{echo abc | coreutils/tr bc d}
20035 On platforms with the BusyBox tools, @command{tr} does not support the
20036 @code{[@var{x}*@var{n}]} option syntax.
20039 $ @kbd{echo abc | tr 'abcd' '[A*4]'}
20041 $ @kbd{echo abc | coreutils/tr 'abcd' '[A*4]'}
20043 $ @kbd{echo xyz | tr 'a-z' '[A*]'}
20045 $ @kbd{echo xyz | coreutils/tr 'a-z' '[A*]'}
20049 POSIX requires @command{tr} to operate on binary files. But at least
20050 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
20051 @code{NUL} in the input prior to doing any translation. When using
20052 @command{tr} to process a binary file that may contain @code{NUL} bytes,
20053 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
20054 @command{/usr/xpg6/bin/tr} if that is available.
20057 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
20059 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
20061 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
20065 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
20066 octal escape for @code{NUL}.
20069 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
20071 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
20073 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
20080 @node Portable Make
20081 @chapter Portable Make Programming
20082 @prindex @command{make}
20083 @cindex Limitations of @command{make}
20085 Writing portable makefiles is an art. Since a makefile's commands are
20086 executed by the shell, you must consider the shell portability issues
20087 already mentioned. However, other issues are specific to @command{make}
20091 * $< in Ordinary Make Rules:: $< in ordinary rules
20092 * Failure in Make Rules:: Failing portably in rules
20093 * Command Line Prefixes:: What's at the start of makefile command lines
20094 * Special Chars in Names:: Special characters in macro names
20095 * Backslash-Newline-Empty:: Empty lines after backslash-newline
20096 * Backslash-Newline Comments:: Spanning comments across line boundaries
20097 * Macros and Submakes:: @code{make macro=value} and submakes
20098 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
20099 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
20100 * Parallel Make:: Parallel @command{make} quirks
20101 * Comments in Make Rules:: Other problems with Make comments
20102 * Newlines in Make Rules:: Using literal newlines in rules
20103 * Comments in Make Macros:: Other problems with Make comments in macros
20104 * Trailing whitespace in Make Macros:: Macro substitution problems
20105 * Command-line Macros and whitespace:: Whitespace trimming of values
20106 * obj/ and Make:: Don't name a subdirectory @file{obj}
20107 * make -k Status:: Exit status of @samp{make -k}
20108 * VPATH and Make:: @code{VPATH} woes
20109 * Single Suffix Rules:: Single suffix rules and separated dependencies
20110 * Timestamps and Make:: Sub-second timestamp resolution
20113 @node $< in Ordinary Make Rules
20114 @section @code{$<} in Ordinary Make Rules
20116 POSIX says that the @samp{$<} construct in makefiles can be
20117 used only in inference rules and in the @samp{.DEFAULT} rule; its
20118 meaning in ordinary rules is unspecified. Solaris @command{make}
20119 for instance replaces it with the empty string. OpenBSD (3.0 and
20120 later) @command{make} diagnoses these uses and errors out.
20122 @node Failure in Make Rules
20123 @section Failure in Make Rules
20125 Unless errors are being ignored
20126 (e.g., because a makefile command line is preceded by a @samp{-} prefix),
20127 POSIX 2008 requires that @command{make} must invoke each command with
20128 the equivalent of a @samp{sh -e -c} subshell, which causes the
20129 subshell to exit immediately if a subsidiary simple-command fails,
20130 with some complicated exceptions.
20131 Historically not all @command{make} implementations
20132 followed this rule. For
20133 example, the command @samp{touch T; rm -f U} may attempt to
20134 remove @file{U} even if the @command{touch} fails, although this is not
20135 permitted with POSIX make. One way to work around failures in simple
20136 commands is to reword them so that they always succeed, e.g., @samp{touch
20138 However, even this approach can run into common bugs in BSD
20139 implementations of the @option{-e} option of @command{sh} and
20140 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
20142 about porting to buggy BSD shells it may be simpler to migrate
20143 complicated @command{make} actions into separate scripts.
20145 @node Command Line Prefixes
20146 @section Makefile Command Line Prefixes
20148 Makefile command lines can be preceded by zero or more of
20149 the command line prefixes @samp{-}, @samp{@@}, and @samp{+},
20150 which modify how @command{make} processes the command.
20151 Although POSIX says these are the only command line prefixes,
20152 some @command{make} implementations, such as Solaris @command{make},
20153 support the additional prefixes @samp{!} and @samp{?}.
20154 Portable makefiles should therefore avoid using these two characters at
20155 the start of a makefile command line.
20159 mishandled-by-Solaris-make:; ! grep FIXME foo.c
20160 portable-to-Solaris-make:; :;! grep FIXME foo.c
20163 @node Special Chars in Names
20164 @section Special Characters in Make Macro Names
20166 POSIX limits macro names to nonempty strings containing only
20167 ASCII letters and digits, @samp{.}, and @samp{_}. Many
20168 @command{make} implementations allow a wider variety of characters, but
20169 portable makefiles should avoid them. It is portable to start a name
20170 with a special character, e.g., @samp{$(.FOO)}.
20172 Some ancient @command{make} implementations don't support leading
20173 underscores in macro names. An example is NEWS-OS 4.2R.
20176 $ @kbd{cat Makefile}
20179 all:; @@echo this is test
20181 Make: Must be a separator on rules line 2. Stop.
20182 $ @kbd{cat Makefile2}
20185 all:; @@echo this is test
20186 $ @kbd{make -f Makefile2}
20191 However, this problem is no longer of practical concern.
20193 @node Backslash-Newline-Empty
20194 @section Backslash-Newline Before Empty Lines
20196 @c This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20197 @c but another hppa hpux 10.20 didn't have it. Bob Proulx
20198 @c <bob@proulx.com> thinks it was in hpux 8.0 too.
20199 On some versions of HP-UX, @command{make} reads multiple newlines
20200 following a backslash, continuing to the next non-empty line. For
20214 shows @code{FOO} equal to @code{one BAR = two}. Other implementations
20215 sensibly let a backslash continue only to the immediately following
20218 @node Backslash-Newline Comments
20219 @section Backslash-Newline in Make Comments
20221 According to POSIX, Make comments start with @code{#}
20222 and continue until an unescaped newline is reached.
20225 $ @kbd{cat Makefile}
20232 $ @kbd{make} # GNU make
20237 However this is not always the case. Some implementations
20238 discard everything from @code{#} through the end of the line, ignoring any
20239 trailing backslash.
20242 $ @kbd{pmake} # BSD make
20243 "Makefile", line 3: Need an operator
20244 Fatal errors encountered -- cannot continue
20248 Therefore, if you want to comment out a multi-line definition, prefix each
20249 line with @code{#}, not only the first.
20257 @node Macros and Submakes
20258 @section @code{make macro=value} and Submakes
20260 A command-line variable definition such as @code{foo=bar} overrides any
20261 definition of @code{foo} in a makefile. Some @command{make}
20262 implementations (such as GNU @command{make}) propagate this
20263 override to subsidiary invocations of @command{make}. Some other
20264 implementations do not pass the substitution along to submakes.
20267 $ @kbd{cat Makefile}
20270 @@printf '%s\n' $(foo)
20273 @@printf '%s\n' $(foo)
20274 $ @kbd{make foo=bar} # GNU make 3.79.1
20277 make[1]: Entering directory `/home/adl'
20279 make[1]: Leaving directory `/home/adl'
20280 $ @kbd{pmake foo=bar} # BSD make
20286 You have a few possibilities if you do want the @code{foo=bar} override
20287 to propagate to submakes. One is to use the @option{-e}
20288 option, which causes all environment variables to have precedence over
20289 the makefile macro definitions, and declare foo as an environment
20293 $ @kbd{env foo=bar make -e}
20296 The @option{-e} option is propagated to submakes automatically,
20297 and since the environment is inherited between @command{make}
20298 invocations, the @code{foo} macro is overridden in
20299 submakes as expected.
20301 This syntax (@code{foo=bar make -e}) is portable only when used
20302 outside of a makefile, for instance from a script or from the
20303 command line. When run inside a @command{make} rule, GNU
20304 @command{make} 3.80 and prior versions forget to propagate the
20305 @option{-e} option to submakes.
20307 Moreover, using @option{-e} could have unexpected side effects if your
20308 environment contains some other macros usually defined by the
20309 makefile. (See also the note about @code{make -e} and @code{SHELL}
20312 If you can foresee all macros that a user might want to override, then
20313 you can propagate them to submakes manually, from your makefile:
20318 @@printf '%s\n' $(foo)
20319 $(MAKE) foo=$(foo) two
20321 @@printf '%s\n' $(foo)
20324 Another way to propagate a variable to submakes in a portable way is to
20325 expand an extra variable in every invocation of @samp{$(MAKE)} within
20331 @@printf '%s\n' $(foo)
20332 $(MAKE) $(SUBMAKEFLAGS) two
20334 @@printf '%s\n' $(foo)
20337 Users must be aware that this technique is in use to take advantage of
20338 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20339 allows any macro to be overridden. Makefiles generated by
20340 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20341 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20342 automake, GNU Automake}).
20344 @node The Make Macro MAKEFLAGS
20345 @section The Make Macro MAKEFLAGS
20346 @cindex @code{MAKEFLAGS} and @command{make}
20347 @cindex @command{make} and @code{MAKEFLAGS}
20349 POSIX requires @command{make} to use @code{MAKEFLAGS} to affect the
20350 current and recursive invocations of make, but allows implementations
20351 several formats for the variable. It is tricky to parse
20352 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20353 or @option{-k} for continued execution are in effect. For example, you
20354 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20355 contains single-letter options, since in the Cygwin version of
20356 GNU @command{make} it is either @option{--unix} or
20357 @option{--win32} with the second word containing single-letter options.
20360 $ @kbd{cat Makefile}
20362 @@printf 'MAKEFLAGS = %s\n' '$(MAKEFLAGS)'
20366 MAKEFLAGS = --unix -k
20369 @node The Make Macro SHELL
20370 @section The Make Macro @code{SHELL}
20371 @cindex @code{SHELL} and @command{make}
20372 @cindex @command{make} and @code{SHELL}
20374 Many @command{make} implementations use the the @code{$(SHELL)}
20375 macro to spawn shell processes and execute Make rules. This
20376 is a builtin macro with a default value upplied by @command{make};
20377 the default can be overridden by a makefile or by a command-line argument,
20378 though not by the environment.
20380 Other @command{make} implementations use other ways to spawn shell
20381 processes, and the POSIX standard for @command{make} says that portable
20382 makefiles should neither define nor use the @code{$(SHELL)} macro.
20384 Despite this prohibition, in practice it does not hurt to define and
20385 then possibly use @code{SHELL} in your makefiles and in some cases it
20386 can help your builds use a better shell to spawn shell processes.
20387 So it's a good idea to define @code{SHELL} in
20388 your makefiles. If you use Autoconf, you can use
20389 its standard output variable @code{SHELL} as follows:
20396 If you use Automake, this is done for you.
20398 Do not force @code{SHELL = /bin/sh} because that is not correct
20399 everywhere. Remember, @file{/bin/sh} is not POSIX compliant on some
20400 systems, such as Solaris 10.
20401 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20402 GNU @command{make} port sees such a setting it enters a
20403 special emulation mode where features like pipes and redirections are
20404 emulated on top of DOS's @command{command.com}. Unfortunately this
20405 emulation is incomplete; for instance it does not handle command
20406 substitutions. Using @code{@@SHELL@@} means that your makefile will
20407 benefit from the same improved shell, such as @command{bash} or
20408 @command{ksh}, that was discovered during @command{configure}, so that
20409 you aren't fighting two different sets of shell bugs between the two
20412 Do not rely on whether @command{make}'s @code{SHELL} settings are
20413 exported to subprocesses, as implementations differ:
20416 $ @kbd{cat Makefile}
20418 @@printf '%s\n' '$(SHELL)'
20420 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # BSD make, AIX make
20423 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # GNU make
20428 @node Parallel Make
20429 @section Parallel Make
20430 @cindex Parallel @command{make}
20432 Support for parallel execution in @command{make} implementation varies.
20433 Generally, using GNU make is your best bet.
20435 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20436 reuse the same shell for multiple commands within one recipe. This can
20437 have various unexpected consequences. For example, changes of directories
20438 or variables persist between recipes, so that:
20442 @@var=value; cd /; pwd; echo $$var; echo $$$$
20443 @@pwd; echo $$var; echo $$$$
20447 may output the following with @code{make -j1}, at least on NetBSD up to
20448 5.1 and FreeBSD up to 8.2:
20460 while without @option{-j1}, or with @option{-B}, the output looks less
20473 Another consequence is that, if one command in a recipe uses @code{exit 0}
20474 to indicate a successful exit, the shell will be gone and the remaining
20475 commands of this recipe will not be executed.
20477 The BSD @command{make} implementations, when run in parallel mode,
20478 will also pass the @command{Makefile} recipes to the shell through
20479 its standard input, thus making it unusable from the recipes:
20482 $ @kbd{cat Makefile}
20484 @@read line; echo LINE: $$line
20485 @c $$ @c restore font-lock
20486 $ @kbd{echo foo | make read}
20488 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20493 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20494 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20495 modifiers'' by dynamically modifying the active shell flags. This
20496 behavior has the effects of potentially clobbering the exit status
20497 of recipes silenced with the @code{@@} modifier if they also unset
20498 the @option{errexit} shell flag, and of mangling the output in
20502 $ @kbd{cat Makefile}
20504 @@echo $$-; set +e; false
20506 -echo $$-; false; echo set -
20507 $ @kbd{make a; echo status: $?}
20511 $ @kbd{make -j1 a; echo status: $?}
20515 echo $-; echo set -
20523 You can avoid all these issues by using the @option{-B} option to enable
20524 compatibility semantics. However, that will effectively also disable
20525 all parallelism as that will cause prerequisites to be updated in the
20526 order they are listed in a rule.
20528 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20529 @command{make}, and Solaris @command{dmake}), when invoked with a
20530 @option{-j@var{N}} option, connect the standard output and standard
20531 error of all their child processes to pipes or temporary regular
20532 files. This can lead to subtly different semantics in the behavior
20533 of the spawned processes. For example, even if the @command{make}
20534 standard output is connected to a tty, the recipe command will not be:
20537 $ @kbd{cat Makefile}
20539 @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20540 $ @kbd{make -j 2} # FreeBSD 8.2 make
20542 $ @kbd{make -j 2} # NetBSD 5.1 make
20545 $ @kbd{dmake -j 2} # Solaris 10 dmake
20546 @var{hostname} --> 1 job
20547 @var{hostname} --> Job output
20555 $ @kbd{make -j 2} # GNU make, Heirloom make
20560 The above examples also show additional status output produced in parallel
20561 mode for targets being updated by Solaris @command{dmake} and NetBSD
20562 @command{make} (but @emph{not} by FreeBSD @command{make}).
20564 Furthermore, parallel runs of those @command{make} implementations will
20565 route standard error from commands that they spawn into their own
20566 standard output, and may remove leading whitespace from output lines.
20569 @node Comments in Make Rules
20570 @section Comments in Make Rules
20571 @cindex Comments in @file{Makefile} rules
20572 @cindex @file{Makefile} rules and comments
20574 Do not try to put comments (lines beginning with @samp{#}) in a rule, as
20575 they end the rule. It is OK for a rule line to start with a tab
20576 followed by @samp{#}, as a comment passed to a shell that does nothing.
20578 To use the @samp{#} character in a command, put it in a rule not a
20579 macro, as the character cannot portably appear in macros
20580 (@pxref{Comments in Make Macros}). So for example, assuming the output
20581 variable @code{COMMENT_CHAR} stands for @samp{#}, the following replaces
20582 @samp{@@COMMENT_CHAR@@} by @samp{#} in a generated header:
20586 sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20587 '$(srcdir)/foo.h.in' > $@@
20590 The funny shell quoting avoids a substitution at @command{config.status}
20591 run time of the left-hand side of the @command{sed} @samp{s} command.
20593 @node Newlines in Make Rules
20594 @section Newlines in Make Rules
20595 @cindex Newlines in @file{Makefile} rules
20596 @cindex @file{Makefile} rules and newlines
20598 In shell scripts, newlines can be used inside string literals. But in
20599 the shell statements of @file{Makefile} rules, this is not possible:
20600 a newline not preceded by a backslash separates commands, whereas a
20601 newline preceded by a backslash becomes part of the shell statement.
20602 So, how can a newline be used in a string literal?
20604 The trick is to set up a shell variable @code{nl} that contains a newline.
20605 For example, the following uses a multi-line @samp{sed} expression that
20606 appends an empty line after every line of a file:
20610 eval "$$(printf 'nl="\n"\n')"; \
20611 sed "a\\$$nl" input >$@@
20614 @node Comments in Make Macros
20615 @section Comments in Make Macros
20616 @cindex Comments in @file{Makefile} macros
20617 @cindex @file{Makefile} macros and comments
20619 In macro definitions, text from @samp{#} until line end is ignored,
20620 which has the unfortunate effect of disallowing @samp{#} even in quotes.
20621 Thus, the following does not work:
20624 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20628 as @samp{CPPFLAGS} is expanded to @samp{"-DCOMMENT_CHAR='}.
20630 GNU @command{make}, when not in POSIX mode, lets you put
20631 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20632 @samp{\#}. However, this usage is not portable.
20633 @xref{Comments in Make Rules}, for a portable alternative.
20635 Even without quoting involved, comments can have surprising effects,
20636 because the whitespace before them is part of the variable value:
20639 foo = bar # trailing comment
20640 print: ; @@echo "$(foo)."
20644 prints @samp{bar .}, which is usually not intended, and can expose
20645 @command{make} bugs as described below.
20647 @node Trailing whitespace in Make Macros
20648 @section Trailing whitespace in Make Macros
20649 @cindex whitespace in @file{Makefile} macros
20650 @cindex @file{Makefile} macros and whitespace
20652 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20653 substitutions and appends another spurious suffix:
20658 print: ; @@echo $(foo:=.test)
20662 prints @samp{bar.test .test}.
20664 BSD and Solaris @command{make} implementations do not honor trailing
20665 whitespace in macro definitions as POSIX requires:
20668 foo = bar # Note the space after "bar".
20669 print: ; @@echo $(foo)t
20673 prints @samp{bart} instead of @samp{bar t}. To work around this, you
20674 can use a helper macro as in the previous example.
20677 @node Command-line Macros and whitespace
20678 @section Command-line Macros and whitespace
20679 @cindex whitespace in command-line macros
20680 @cindex command-line, macros set on
20681 @cindex environment, macros set from
20683 Some @command{make} implementations may strip trailing whitespace off
20684 of macros set on the command line in addition to leading whitespace.
20685 Further, some may strip leading whitespace off of macros set from
20686 environment variables:
20689 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20690 foo=' f f ' make -f - bar=' b b '}
20691 x f f xb b x # AIX, BSD, GNU make
20692 xf f xb b x # HP-UX
20693 x f f xb bx # Solaris make
20697 @node obj/ and Make
20698 @section The @file{obj/} Subdirectory and Make
20699 @cindex @file{obj/}, subdirectory
20700 @cindex BSD @command{make} and @file{obj/}
20702 Never name one of your subdirectories @file{obj/} if you don't like
20705 If an @file{obj/} directory exists, BSD @command{make} enters it
20706 before reading the makefile. Hence the makefile in the
20707 current directory is not read.
20710 $ @kbd{cat Makefile}
20713 $ @kbd{cat obj/Makefile}
20716 $ @kbd{make} # GNU make
20719 $ @kbd{pmake} # BSD make
20724 @node make -k Status
20725 @section Exit Status of @code{make -k}
20726 @cindex @code{make -k}
20728 Do not rely on the exit status of @code{make -k}. Some implementations
20729 reflect whether they encountered an error in their exit status; other
20730 implementations always succeed.
20733 $ @kbd{cat Makefile}
20736 $ @kbd{make -k; echo exit status: $?} # GNU make
20738 make: *** [all] Error 1
20740 $ @kbd{pmake -k; echo exit status: $?} # BSD make
20742 *** Error code 1 (continuing)
20746 @node VPATH and Make
20747 @section @code{VPATH} and Make
20748 @cindex @code{VPATH}
20750 POSIX does not specify the semantics of @code{VPATH}. Typically,
20751 @command{make} supports @code{VPATH}, but its implementation is not
20754 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20755 portable to recent-enough popular implementations of @command{make}, but
20756 to keep the resulting makefiles portable, a package's makefile
20757 prototypes must take the following issues into account. These issues
20758 are complicated and are often poorly understood, and installers who use
20759 @code{VPATH} should expect to find many bugs in this area. If you use
20760 @code{VPATH}, the simplest way to avoid these portability bugs is to
20761 stick with GNU @command{make}, since it is the most
20762 commonly-used @command{make} among Autoconf users.
20764 Here are some known issues with some @code{VPATH}
20768 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
20769 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
20770 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
20771 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
20772 * Make Target Lookup:: More details about @code{VPATH} lookup
20775 @node Variables listed in VPATH
20776 @subsection Variables listed in @code{VPATH}
20777 @cindex @code{VPATH} and variables
20778 @cindex variables and @code{VPATH}
20780 Do not set @code{VPATH} to the value of another variable, for example
20781 @samp{VPATH = $(srcdir)}, because some ancient versions of
20782 @command{make} do not do variable substitutions on the value of
20783 @code{VPATH}. For example, use this
20786 srcdir = @@srcdir@@
20791 rather than @samp{VPATH = $(srcdir)}. Note that with GNU
20792 Automake, there is no need to set this yourself.
20794 @node VPATH and Double-colon
20795 @subsection @code{VPATH} and Double-colon Rules
20796 @cindex @code{VPATH} and double-colon rules
20797 @cindex double-colon rules and @code{VPATH}
20799 With ancient versions of Sun @command{make},
20800 any assignment to @code{VPATH} causes @command{make} to execute only
20801 the first set of double-colon rules.
20802 However, this problem is no longer of practical concern.
20804 @node $< in Explicit Rules
20805 @subsection @code{$<} Not Supported in Explicit Rules
20806 @cindex explicit rules, @code{$<}, and @code{VPATH}
20807 @cindex @code{$<}, explicit rules, and @code{VPATH}
20808 @cindex @code{VPATH}, explicit rules, and @code{$<}
20810 Using @code{$<} in explicit rules is not portable.
20811 The prerequisite file must be named explicitly in the rule. If you want
20812 to find the prerequisite via a @code{VPATH} search, you have to code the
20813 whole thing manually. @xref{Build Directories}.
20815 @node Automatic Rule Rewriting
20816 @subsection Automatic Rule Rewriting
20817 @cindex @code{VPATH} and automatic rule rewriting
20818 @cindex automatic rule rewriting and @code{VPATH}
20820 Some @command{make} implementations, such as Solaris,
20821 search for prerequisites in @code{VPATH} and
20822 then rewrite each occurrence as a plain word in the rule.
20826 # This isn't portable to GNU make.
20833 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20834 found in @file{../pkg/src}.
20836 However, this rule leads to real problems in practice. For example, if
20837 the source directory contains an ordinary file named @file{test} that is
20838 used in a dependency, Solaris @command{make} rewrites commands like
20839 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20840 @dots{}}, which is typically undesirable. In fact, @command{make} is
20841 completely unaware of shell syntax used in the rules, so the VPATH
20842 rewrite can potentially apply to @emph{any} whitespace-separated word
20843 in a rule, including shell variables, functions, and keywords.
20846 $ @kbd{mkdir build}
20848 $ @kbd{cat > Makefile <<'END'}
20850 all: arg func for echo
20851 func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20854 $ @kbd{touch ../arg ../func ../for ../echo}
20856 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20857 ../func "hello world"
20858 sh: syntax error at line 1: `do' unexpected
20863 To avoid this problem, portable makefiles should never mention a source
20864 file or dependency whose name is that of a shell keyword like @file{for}
20865 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20866 @command{test}, or a shell function or variable used in the corresponding
20867 @command{Makefile} recipe.
20869 Because of these problems GNU @command{make} and many other @command{make}
20870 implementations do not rewrite commands, so portable makefiles should
20871 search @code{VPATH} manually. It is tempting to write this:
20874 # This isn't portable to Solaris make.
20877 cp `test -f if.c || echo $(VPATH)/`if.c f.c
20881 However, the ``prerequisite rewriting'' still applies here. So if
20882 @file{if.c} is in @file{../pkg/src}, Solaris @command{make}
20886 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20897 and thus fails. Oops.
20899 A simple workaround, and good practice anyway, is to use @samp{$?} and
20900 @samp{$@@} when possible:
20909 but this does not generalize well to commands with multiple
20910 prerequisites. A more general workaround is to rewrite the rule so that
20911 the prerequisite @file{if.c} never appears as a plain word. For
20912 example, these three rules would be safe, assuming @file{if.c} is in
20913 @file{../pkg/src} and the other files are in the working directory:
20918 cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20920 cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20922 cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20925 Things get worse when your prerequisites are in a macro.
20929 HEADERS = f.h g.h h.h
20930 install-HEADERS: $(HEADERS)
20931 for i in $(HEADERS); do \
20932 $(INSTALL) -m 644 \
20933 `test -f $$i || echo $(VPATH)/`$$i \
20934 $(DESTDIR)$(includedir)/$$i; \
20935 @c $$ restore font-lock
20939 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20940 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20941 where @code{f.h} and @code{g.h} are plain words and are hence
20942 subject to @code{VPATH} adjustments.
20944 If the three files are in @file{../pkg/src}, the rule is run as:
20947 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20949 `test -f $i || echo ../pkg/src/`$i \
20950 /usr/local/include/$i; \
20954 where the two first @command{install} calls fail. For instance,
20955 consider the @code{f.h} installation:
20959 `test -f ../pkg/src/f.h || \
20962 /usr/local/include/../pkg/src/f.h;
20971 /usr/local/include/../pkg/src/f.h;
20974 Note that the manual @code{VPATH} search did not cause any problems here;
20975 however this command installs @file{f.h} in an incorrect directory.
20977 Trying to quote @code{$(HEADERS)} in some way, as we did for
20978 @code{foo.c} a few makefiles ago, does not help:
20981 install-HEADERS: $(HEADERS)
20982 headers='$(HEADERS)'; \
20983 for i in $$headers; do \
20984 $(INSTALL) -m 644 \
20985 `test -f $$i || echo $(VPATH)/`$$i \
20986 $(DESTDIR)$(includedir)/$$i; \
20990 Now, @code{headers='$(HEADERS)'} macro-expands to:
20993 headers='f.h g.h h.h'
20997 but @code{g.h} is still a plain word. (As an aside, the idiom
20998 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20999 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
21000 syntax error on @code{for i in;}.)
21002 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
21006 HEADERS = f.h g.h h.h
21007 install-HEADERS: $(HEADERS)
21008 headers='$(HEADERS)'; \
21009 for i in $$headers; do \
21010 i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
21011 $(INSTALL) -m 644 \
21012 `test -f $$i || echo $(VPATH)/`$$i \
21013 $(DESTDIR)$(includedir)/$$i; \
21014 @c $$ restore font-lock
21019 Automake does something similar.
21021 @node Make Target Lookup
21022 @subsection Make Target Lookup
21023 @cindex @code{VPATH}, resolving target pathnames
21025 GNU @command{make} uses a complex algorithm to decide when it
21026 should use files found via a @code{VPATH} search. @xref{Search
21027 Algorithm, , How Directory Searches are Performed, make, The GNU Make
21030 If a target needs to be rebuilt, GNU @command{make} discards the
21031 file name found during the @code{VPATH} search for this target, and
21032 builds the file locally using the file name given in the makefile.
21033 If a target does not need to be rebuilt, GNU @command{make} uses the
21034 file name found during the @code{VPATH} search.
21036 Other @command{make} implementations, like NetBSD @command{make}, are
21037 easier to describe: the file name found during the @code{VPATH} search
21038 is used whether the target needs to be rebuilt or not. Therefore
21039 new files are created locally, but existing files are updated at their
21040 @code{VPATH} location.
21042 OpenBSD and FreeBSD @command{make}, however,
21044 @code{VPATH} search for a dependency that has an explicit rule.
21045 This is extremely annoying.
21047 When attempting a @code{VPATH} build for an autoconfiscated package
21048 (e.g., @code{mkdir build && cd build && ../configure}), this means
21050 @command{make} builds everything locally in the @file{build}
21051 directory, while BSD @command{make} builds new files locally and
21052 updates existing files in the source directory.
21055 $ @kbd{cat Makefile}
21058 foo.x bar.x: newer.x
21059 @@echo Building $@@
21060 $ @kbd{touch ../bar.x}
21061 $ @kbd{touch ../newer.x}
21062 $ @kbd{make} # GNU make
21065 $ @kbd{pmake} # NetBSD make
21068 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21071 $ @kbd{make} # GNU make
21073 $ @kbd{pmake} # NetBSD make
21075 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21080 Note how NetBSD @command{make} updates @file{../bar.x} in its
21081 VPATH location, and how FreeBSD and OpenBSD
21082 @command{make} always
21083 update @file{bar.x}, even when @file{../bar.x} is up to date.
21085 Another point worth mentioning is that once GNU @command{make} has
21086 decided to ignore a @code{VPATH} file name (e.g., it ignored
21087 @file{../bar.x} in the above example) it continues to ignore it when
21088 the target occurs as a prerequisite of another rule.
21090 The following example shows that GNU @command{make} does not look up
21091 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21092 because it ignored the @code{VPATH} result of @file{bar.x} while running
21093 the @code{bar.x: newer.x} rule.
21096 $ @kbd{cat Makefile}
21100 @@echo Building $@@
21104 $ @kbd{touch ../bar.x}
21105 $ @kbd{touch ../newer.x}
21106 $ @kbd{make} # GNU make
21109 cp: cannot stat 'bar.x': No such file or directory
21110 make: *** [bar.y] Error 1
21111 $ @kbd{pmake} # NetBSD make
21115 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21116 echo Building bar.x
21118 cp: cannot stat 'bar.x': No such file or directory
21122 Note that if you drop away the command from the @code{bar.x: newer.x}
21123 rule, GNU @command{make} magically starts to work: it
21124 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21125 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21126 uses. FreeBSD and OpenBSD still don't work, though.
21129 $ @kbd{cat Makefile}
21136 $ @kbd{touch ../bar.x}
21137 $ @kbd{touch ../newer.x}
21138 $ @kbd{make} # GNU make
21141 $ @kbd{pmake} # NetBSD make
21144 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21146 cp: cannot stat 'bar.x': No such file or directory
21150 It seems the sole solution that would please every @command{make}
21151 implementation is to never rely on @code{VPATH} searches for targets.
21152 In other words, @code{VPATH} should be reserved to sources that are not built.
21155 @node Single Suffix Rules
21156 @section Single Suffix Rules and Separated Dependencies
21157 @cindex Single Suffix Inference Rule
21158 @cindex Rule, Single Suffix Inference
21159 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21160 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21163 @cindex Separated Dependencies
21164 @dfn{Separated dependencies} simply refers to listing the prerequisite
21165 of a target, without defining a rule. Usually one can list on the one
21166 hand side, the rules, and on the other hand side, the dependencies.
21168 Solaris @command{make} does not support separated dependencies for
21169 targets defined by single suffix rules:
21172 $ @kbd{cat Makefile}
21177 $ @kbd{touch foo.in}
21184 while GNU Make does:
21190 Makefile foo foo.in
21193 Note it works without the @samp{foo: foo.in} dependency.
21196 $ @kbd{cat Makefile}
21205 and it works with double suffix inference rules:
21208 $ @kbd{cat Makefile}
21210 .SUFFIXES: .in .out
21217 As a result, in such a case, you have to write target rules.
21219 @node Timestamps and Make
21220 @section Timestamp Resolution and Make
21221 @cindex timestamp resolution
21222 Traditionally, file timestamps had 1-second resolution, and
21223 @command{make} used those timestamps to determine whether one file was
21224 newer than the other. However, many modern file systems have
21225 timestamps with 1-nanosecond resolution. Some @command{make}
21226 implementations look at the entire timestamp; others ignore the
21227 fractional part, which can lead to incorrect results. Normally this
21228 is not a problem, but in some extreme cases you may need to use tricks
21229 like @samp{sleep 1} to work around timestamp truncation bugs.
21231 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21232 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21233 Tools}). Hence you should be wary of rules like this:
21240 as @file{dest} often appears to be older than @file{src} after the
21241 timestamp is truncated, and this can cause @command{make} to do
21242 needless rework the next time it is invoked. To work around this
21243 problem, you can use a timestamp file, e.g.:
21251 Apart from timestamp resolution, there are also differences in handling
21252 equal timestamps. HP-UX @command{make} updates targets if it has the
21253 same timestamp as one of its prerequisites, in violation of POSIX rules.
21255 This can cause spurious rebuilds for repeated runs of @command{make}.
21256 This in turn can cause @command{make} to fail if it tries to rebuild
21257 generated files in a possibly read-only source tree with tools not
21258 present on the end-user machine. Use GNU @command{make} instead.
21262 @c ======================================== Portable C and C++ Programming
21264 @node Portable C and C++
21265 @chapter Portable C and C++ Programming
21266 @cindex Portable C and C++ programming
21268 C and C++ programs often use low-level features of the underlying
21269 system, and therefore are often more difficult to make portable to other
21272 Several standards have been developed to help make your programs more
21273 portable. If you write programs with these standards in mind, you can
21274 have greater confidence that your programs work on a wide variety
21277 @uref{https://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21278 Standards Supported by GCC}
21281 @xref{Standards, , Language Standards Supported by
21282 GCC, gcc, Using the GNU Compiler Collection
21285 for a list of C-related standards. Many programs also assume the
21286 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX standard}.
21289 @cindex C89, C99, C11, C17, and C23
21290 The first widely used C variant was K&R C, which predates any C
21291 standard. K&R C compilers are no longer of practical interest, though,
21292 and Autoconf assumes at least C89, the first C standard,
21293 which is sometimes called ``C90'' due to a delay in standardization.
21294 C has since gone through the standards C99, C11, C17, and C23, and
21295 Autoconf is compatible with all these standards.
21297 Program portability is a huge topic, and this section can only briefly
21298 introduce common pitfalls. @xref{System Portability, , Portability
21299 between System Types, standards, The GNU Coding Standards}, for
21303 * Varieties of Unportability:: How to make your programs unportable
21304 * Integer Overflow:: When integers get too large
21305 * Preprocessor Arithmetic:: @code{#if} expression problems
21306 * Null Pointers:: Properties of null pointers
21307 * Buffer Overruns:: Subscript errors and the like
21308 * Volatile Objects:: @code{volatile} and signals
21309 * Floating Point Portability:: Portable floating-point arithmetic
21310 * Exiting Portably:: Exiting and the exit status
21313 @node Varieties of Unportability
21314 @section Varieties of Unportability
21315 @cindex portability
21317 Autoconf tests and ordinary programs often need to test what is allowed
21318 on a system, and therefore they may need to deliberately exceed the
21319 boundaries of what the standards allow, if only to see whether an
21320 optional feature is present. When you write such a program, you should
21321 keep in mind the difference between constraints, unspecified behavior,
21322 and undefined behavior.
21324 In C, a @dfn{constraint} is a rule that the compiler must enforce. An
21325 example constraint is that C programs must not declare a bit-field with
21326 negative width. Tests can therefore reliably assume that programs with
21327 negative-width bit-fields are rejected by a compiler that conforms
21330 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21331 multiple possibilities. For example, the order of evaluation of
21332 function arguments is unspecified. Some unspecified behavior is
21333 @dfn{implementation-defined}, i.e., documented by the implementation,
21334 but since Autoconf tests cannot read the documentation they cannot
21335 distinguish between implementation-defined and other unspecified
21336 behavior. It is common for Autoconf tests to probe implementations to
21337 determine otherwise-unspecified behavior.
21339 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21340 the implementation to do anything it pleases. For example,
21341 dereferencing a null pointer leads to undefined behavior. If possible,
21342 test programs should avoid undefined behavior, since a program with
21343 undefined behavior might succeed on a test that should fail.
21345 The above rules apply to programs that are intended to conform to the
21346 standard. However, strictly-conforming programs are quite rare, since
21347 the standards are so limiting. A major goal of Autoconf is to support
21348 programs that use implementation features not described by the standard,
21349 and it is fairly common for test programs to violate the above rules, if
21350 the programs work well enough in practice.
21352 @node Integer Overflow
21353 @section Integer Overflow
21354 @cindex integer overflow
21355 @cindex overflow, signed integer
21356 @cindex signed integer overflow
21357 @cindex wraparound arithmetic
21359 Although some traditional C programs assume that signed integer overflow
21360 wraps around reliably using two's complement arithmetic, the C standard
21361 says that program behavior is undefined on overflow, and these C
21362 programs may not work on many modern implementations.
21365 * Integer Overflow Basics:: Why integer overflow is a problem
21366 * Signed Overflow Examples:: Examples of code assuming wraparound
21367 * Optimization and Wraparound:: Optimizations that break uses of wraparound
21368 * Signed Overflow Advice:: Practical advice for signed overflow issues
21369 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
21372 @node Integer Overflow Basics
21373 @subsection Basics of Integer Overflow
21374 @cindex integer overflow
21375 @cindex overflow, signed integer
21376 @cindex signed integer overflow
21377 @cindex wraparound arithmetic
21379 In languages like C, integer overflow wraps around for unsigned
21380 integer types that are at least as wide as @code{unsigned int};
21381 e.g., @code{UINT_MAX + 1} yields zero.
21382 This is guaranteed by the C standard and is
21383 portable in practice, unless you specify aggressive,
21384 nonstandard optimization options
21385 suitable only for special applications.
21387 In contrast, the C standard says that signed integer overflow leads to
21388 undefined behavior where a program can do anything, including dumping
21389 core or overrunning a buffer. The misbehavior can even precede the
21390 overflow. Such an overflow can occur during addition, subtraction,
21391 multiplication, division, and left shift. It can even occur for
21392 unsigned types like @code{unsigned short int} that are narrower
21393 than @code{int}, as values of these types are widened to @code{int}
21394 before computation.
21396 Despite this requirement of the standard, some C programs assume that
21397 signed integer overflow silently wraps around modulo a power of two,
21398 using two's complement arithmetic, so long as you convert the resulting
21399 value to a signed integer type. These programs can have problems,
21400 especially when optimization is enabled. If you assume a GCC-like
21401 compiler, you can work around the problems by compiling with GCC's
21402 @code{-fwrapv} option; however, this is not portable.
21404 For historical reasons C17 and earlier also allowed implementations with
21405 ones' complement or signed magnitude arithmetic, but C23 requires
21406 two's complement and it is safe to assume two's complement nowadays.
21408 Also, overflow can occur when converting an out-of-range value to a
21409 signed integer type. Here a standard implementation must define what
21410 happens, and this can include raising an exception. Although practical
21411 implementations typically wrap around silently in this case, a few
21412 debugging implementations trap instead.
21414 @node Signed Overflow Examples
21415 @subsection Examples of Code Assuming Wraparound Overflow
21416 @cindex integer overflow
21417 @cindex overflow, signed integer
21418 @cindex signed integer overflow
21419 @cindex wraparound arithmetic
21421 There was long a tension between what the C standard requires for signed
21422 integer overflow, and what traditional C programs commonly assumed. The
21423 standard allows aggressive optimizations based on assumptions that
21424 overflow never occurs, but traditionally many C programs relied on overflow
21425 wrapping around. Although these programs did not conform to the standard,
21426 they formerly worked in practice because traditionally compilers did not
21427 optimize in such a way that would break the programs. Nowadays, though,
21428 compilers do perform these optimizations, so portable programs can no
21429 longer assume reliable wraparound on signed integer overflow.
21431 The C Standard says that if a program has signed integer overflow its
21432 behavior is undefined, and the undefined behavior can even precede the
21433 overflow. To take an extreme example:
21435 @c Inspired by Robert Dewar's example in
21436 @c <https://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21438 if (password == expected_password)
21439 allow_superuser_privileges ();
21440 else if (counter++ == INT_MAX)
21443 printf ("%d password mismatches\n", counter);
21447 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21448 @code{counter++} must overflow and the behavior is undefined, so the C
21449 standard allows the compiler to optimize away the test against
21450 @code{INT_MAX} and the @code{abort} call.
21451 Worse, if an earlier bug in the program lets the compiler deduce that
21452 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21453 the C standard allows the compiler to optimize away the password test
21454 and generate code that allows superuser privileges unconditionally.
21456 Here is an example derived from the 7th Edition Unix implementation of
21457 @code{atoi} (1979-01-10):
21463 while (*p >= '0' && *p <= '9')
21464 n = n * 10 + *p++ - '0';
21465 return (f ? -n : n);
21469 Even if the input string is in range, on most modern machines this has
21470 signed overflow when computing the most negative integer (the @code{-n}
21471 overflows) or a value near an extreme integer (the @code{+}
21474 Here is another example, derived from the 7th Edition implementation of
21475 @code{rand} (1979-01-10). Here the programmer expects both
21476 multiplication and addition to wrap on overflow:
21479 static long int randx = 1;
21481 randx = randx * 1103515245 + 12345;
21482 return (randx >> 16) & 077777;
21485 In the following example, derived from the GNU C Library 2.15
21486 implementation of @code{mktime} (2012-03-21), the code assumes
21487 wraparound arithmetic in @code{+} to detect signed overflow:
21491 int sec_requested, sec_adjustment;
21493 t1 = t + sec_requested;
21494 t2 = t1 + sec_adjustment;
21495 if (((t1 < t) != (sec_requested < 0))
21496 | ((t2 < t1) != (sec_adjustment < 0)))
21500 Although some of these examples will likely behave as if signed integer
21501 overflow wraps around reliably, other examples are likely to misbehave
21502 when optimization is enabled. All these examples should be avoided in
21503 portable code because signed integer overflow is not reliable on modern
21504 systems, and it's not worth worrying about which of these examples
21505 happen to work on most platforms and which do not.
21507 @node Optimization and Wraparound
21508 @subsection Optimizations That Break Wraparound Arithmetic
21509 @cindex loop induction
21511 Compilers sometimes generate code that is incompatible with wraparound
21512 integer arithmetic. A simple example is an algebraic simplification: a
21513 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21514 because it assumes that @code{i * 2000} does not overflow. The
21515 translation is not equivalent to the original when overflow occurs:
21516 e.g., in the typical case of 32-bit signed two's complement wraparound
21517 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21518 the original expression returns @minus{}2147483 but the optimized
21519 version returns the mathematically correct value 2147484.
21521 More subtly, loop induction optimizations often exploit the undefined
21522 behavior of signed overflow. Consider the following contrived function
21527 sumc (int lo, int hi)
21530 for (int i = lo; i <= hi; i++)
21537 To avoid multiplying by 53 each time through the loop, an optimizing
21538 compiler might internally transform @code{sumc} to the equivalent of the
21543 transformed_sumc (int lo, int hi)
21547 for (int ic = lo * 53; ic <= hic; ic += 53)
21554 This transformation is allowed by the C standard, but it is invalid for
21555 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21556 overflow in computing expressions like @code{hi * 53} can cause the
21557 expression @code{i <= hi} to yield a different value from the
21558 transformed expression @code{ic <= hic}.
21560 For this reason, compilers that use loop induction and similar
21561 techniques often do not support reliable wraparound arithmetic when a
21562 loop induction variable like @code{ic} is involved. Since loop
21563 induction variables are generated by the compiler, and are not visible
21564 in the source code, it is not always trivial to say whether the problem
21567 Hardly any code actually depends on wraparound arithmetic in cases like
21568 these, so in practice these loop induction optimizations are almost
21569 always useful. However, edge cases in this area can cause problems.
21573 for (int j = 1; 0 < j; j *= 2)
21578 Here, the loop attempts to iterate through all powers of 2 that
21579 @code{int} can represent, but the C standard allows a compiler to
21580 optimize away the comparison and generate an infinite loop,
21581 under the argument that behavior is undefined on overflow. As of this
21582 writing this optimization is done on some platforms by
21583 GCC with @option{-O2}, so this code is not portable in practice.
21585 @node Signed Overflow Advice
21586 @subsection Practical Advice for Signed Overflow Issues
21587 @cindex integer overflow
21588 @cindex overflow, signed integer
21589 @cindex signed integer overflow
21590 @cindex wraparound arithmetic
21592 Ideally the safest approach is to avoid signed integer overflow
21593 entirely. For example, instead of multiplying two signed integers, you
21594 can convert them to double-width integers, multiply the wider values,
21595 then test whether the result is in the narrower range. Or you can use
21596 more-complicated code employing unsigned integers of the same width.
21598 Rewriting code in this way will be inconvenient, though, especially if
21599 the signed values might be negative and no wider type is available.
21600 Using unsigned arithmetic to check for overflow is
21601 particularly painful to do portably and efficiently when dealing with an
21602 integer type like @code{uid_t} whose width and signedness vary from
21603 platform to platform. Also, this approach may hurt performance.
21605 Hence it is often useful to maintain code that needs
21606 wraparound on overflow, instead of rewriting the code. The rest of this
21607 section attempts to give practical advice for this situation.
21609 To detect integer overflow portably when attempting operations like
21610 @code{sum = a + b}, you can use the C23 @code{<stdckdint.h>} macros
21611 @code{ckd_add}, @code{ckd_sub}, and @code{ckd_mul}.
21612 The following code adds two integers with overflow wrapping around
21613 reliably in the sum:
21616 #include <stdckdint.h>
21618 /* Set sum = a + b, with wraparound. */
21619 if (ckd_add (&sum, a, b))
21620 /* 'sum' has just the low order bits. */;
21622 /* 'sum' is the correct answer. */;
21625 To be portable to pre-C23 platforms you can use Gnulib's
21626 @code{stdckdint} module, which emulates this part of C23 (@pxref{Gnulib}).
21627 Invoking the @code{stdckdint} macros typically costs just one machine
21628 instruction for the arithmetic and another instruction for the rare
21629 branch on overflow.
21631 If your code uses a signed loop index, make sure that the index cannot
21632 overflow, along with all signed expressions derived from the index.
21633 Here is a contrived example of problematic code with two instances of
21637 for (int i = INT_MAX - 10; i <= INT_MAX; i++)
21640 report_overflow ();
21646 Because of the two overflows, a compiler might optimize away or
21647 transform the two comparisons in a way that is incompatible with the
21648 wraparound assumption.
21650 If your code is intended to be compiled only by GCC and
21651 assumes wraparound behavior, and you want to insulate it
21652 against any GCC optimizations that would fail to support that
21653 behavior, you should use GCC's @option{-fwrapv} option, which
21654 causes signed overflow to wrap around reliably (except for division and
21655 remainder, as discussed in the next section).
21657 If you need to write portable code and therefore cannot assume that
21658 signed integer overflow wraps around reliably, you should consider
21659 debugging with a GCC option that causes signed overflow to raise an
21660 exception. These options include @option{-fsanitize=undefined} and
21663 @node Signed Integer Division
21664 @subsection Signed Integer Division and Integer Overflow
21665 @cindex division, integer
21668 integer division is not always harmless: for example, on CPUs of the
21669 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21670 which by default terminates the program. Worse, taking the remainder
21671 of these two values typically yields the same signal on these CPUs,
21672 behavior that the C standard allows.
21674 @node Preprocessor Arithmetic
21675 @section Preprocessor Arithmetic
21676 @cindex preprocessor arithmetic
21678 In C99 and later, preprocessor arithmetic, used for @code{#if}
21680 be evaluated as if all signed values are of type @code{intmax_t} and all
21681 unsigned values of type @code{uintmax_t}. Many compilers are buggy in
21682 this area, though. For example, as of 2007, Sun C mishandles @code{#if
21683 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21684 @code{long long int}. Also, some older preprocessors mishandle
21685 constants ending in @code{LL}. To work around these problems, you can
21686 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21687 @code{configure}-time rather than at @code{#if}-time.
21689 @node Null Pointers
21690 @section Properties of Null Pointers
21691 @cindex null pointers
21693 Most modern hosts reliably fail when you attempt to dereference a null
21696 On almost all modern hosts, null pointers use an all-bits-zero internal
21697 representation, so you can reliably use @code{memset} with 0 to set all
21698 the pointers in an array to null values.
21700 If @code{p} is a null pointer to an object type, the C expression
21701 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21702 the standard says that it has undefined behavior.
21704 @node Buffer Overruns
21705 @section Buffer Overruns and Subscript Errors
21706 @cindex buffer overruns
21708 Buffer overruns and subscript errors are the most common dangerous
21709 errors in C programs. They result in undefined behavior because storing
21710 outside an array typically modifies storage that is used by some other
21711 object, and most modern systems lack runtime checks to catch these
21712 errors. Programs should not rely on buffer overruns being caught.
21714 There is one exception to the usual rule that a portable program cannot
21715 address outside an array. In C, it is valid to compute the address just
21716 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21717 so long as you do not dereference the resulting pointer. But it is not
21718 valid to compute the address just before an object, e.g., @code{&a[-1]};
21719 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}. On
21720 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21721 reliable in general, and it is usually easy enough to avoid the
21722 potential portability problem, e.g., by allocating an extra unused array
21723 element at the start or end.
21725 @uref{https://@/www.valgrind.org/, Valgrind} can catch many overruns.
21726 GCC users might also consider using the @option{-fsanitize=} options
21728 @xref{Instrumentation Options, , Program Instrumentation Options,
21729 gcc, Using the GNU Compiler Collection (GCC)}.
21731 Buffer overruns are usually caused by off-by-one errors, but there are
21732 more subtle ways to get them.
21734 Using @code{int} values to index into an array or compute array sizes
21735 causes problems on typical 64-bit hosts where an array index might
21736 be @math{2^{31}} or larger. Index values of type @code{size_t} avoid this
21737 problem, but cannot be negative. Index values of type @code{ptrdiff_t}
21738 are signed, and are wide enough in practice.
21740 If you add or multiply two numbers to calculate an array size, e.g.,
21741 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21742 multiplication overflows.
21744 Many implementations of the @code{alloca} function silently misbehave
21745 and can generate buffer overflows if given sizes that are too large.
21746 The size limits are implementation dependent, but are at least 4000
21747 bytes on all platforms that we know about.
21749 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21750 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21751 portable code should not use them unless the inputs are known to be
21752 within certain limits. The time-related functions can overflow their
21753 buffers if given timestamps out of range (e.g., a year less than -999
21754 or greater than 9999). Time-related buffer overflows cannot happen with
21755 recent-enough versions of the GNU C library, but are possible
21757 implementations. The @code{gets} function is the worst, since it almost
21758 invariably overflows its buffer when presented with an input line larger
21761 @node Volatile Objects
21762 @section Volatile Objects
21763 @cindex volatile objects
21765 The keyword @code{volatile} is often misunderstood in portable code.
21766 Its use inhibits some memory-access optimizations, but programmers often
21767 wish that it had a different meaning than it actually does.
21769 @code{volatile} was designed for code that accesses special objects like
21770 memory-mapped device registers whose contents spontaneously change.
21771 Such code is inherently low-level, and it is difficult to specify
21772 portably what @code{volatile} means in these cases. The C standard
21773 says, ``What constitutes an access to an object that has
21774 volatile-qualified type is implementation-defined,'' so in theory each
21775 implementation is supposed to fill in the gap by documenting what
21776 @code{volatile} means for that implementation. In practice, though,
21777 this documentation is usually absent or incomplete.
21779 One area of confusion is the distinction between objects defined with
21780 volatile types, and volatile lvalues. From the C standard's point of
21781 view, an object defined with a volatile type has externally visible
21782 behavior. You can think of such objects as having little oscilloscope
21783 probes attached to them, so that the user can observe some properties of
21784 accesses to them, just as the user can observe data written to output
21785 files. However, accesses via volatile lvalues to ordinary objects
21786 are merely side effects (i.e., changes to the state of the execution
21787 environment), and the implementation is not required to document
21788 their visibility any further. For example:
21791 /* Declare and access a volatile object.
21792 Accesses to X are "visible" to users. */
21793 static int volatile x;
21796 /* Access two ordinary objects via a volatile lvalue.
21797 Although each read and write is a side effect,
21798 the accesses are not directly "visible" to users. */
21800 int *z = malloc (sizeof *z);
21809 Programmers often wish that @code{volatile} meant ``Perform the memory
21810 access here and now, without merging several memory accesses, without
21811 changing the memory word size, and without reordering.'' But the C
21812 standard does not require this. For objects defined with a volatile
21813 type, accesses must be done before the next sequence point; but
21814 otherwise merging, reordering, and word-size change is allowed.
21816 Even when accessing objects defined with a volatile type,
21817 the C standard allows only
21818 extremely limited signal handlers: in C23 the behavior is undefined if a
21819 signal handler refers to any non-local object that is not a lock-free
21820 atomic object and that is not @code{constexpr} (other than by writing to
21821 a @code{sig_atomic_t volatile} object), or calls any standard library
21822 function other than from a small set that includes @code{abort},
21823 @code{_Exit}, @code{quick_exit}, some @code{<stdatomic.h>} functions,
21824 and @code{signal}. Hence C compilers need not worry about a signal
21825 handler disturbing ordinary computation. POSIX allows some additional
21826 behavior in a portable signal handler, but is still quite restrictive.
21827 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21828 GNU Compiler Collection (GCC)}, for some
21829 restrictions imposed by GCC. @xref{Defining Handlers, ,
21830 Defining Signal Handlers, libc, The GNU C Library}, for some
21831 restrictions imposed by the GNU C library. Restrictions
21832 differ on other platforms.
21834 If possible, it is best to use a signal handler that fits within the
21835 limits imposed by the C and POSIX standards.
21837 If this is not practical, you can try the following rules of thumb. A
21838 signal handler should access only volatile lvalues, preferably lvalues
21839 that refer to objects defined with a volatile type, and should not
21840 assume that the accessed objects have an internally consistent state
21841 if they are larger than a machine word. Furthermore, installers
21842 should employ compilers and compiler options that are commonly used
21843 for building operating system kernels, because kernels often need more
21844 from @code{volatile} than the C Standard requires, and installers who
21845 compile an application in a similar environment can sometimes benefit
21846 from the extra constraints imposed by kernels on compilers.
21847 Admittedly we are hand-waving somewhat here, as there are few
21848 guarantees in this area; the rules of thumb may help to fix some bugs
21849 but there is a good chance that they will not fix them all.
21851 For @code{volatile}, C++ has the same problems that C does.
21852 Multithreaded applications have even more problems with @code{volatile},
21853 but they are beyond the scope of this section.
21855 The bottom line is that using @code{volatile} typically hurts
21856 performance but should not hurt correctness. In some cases its use
21857 does help correctness, but these cases are often so poorly understood
21858 that all too often adding @code{volatile} to a data structure merely
21859 alleviates some symptoms of a bug while not fixing the bug in general.
21861 @node Floating Point Portability
21862 @section Floating Point Portability
21863 @cindex floating point
21865 Almost all modern systems use IEEE-754 floating point, and it is safe to
21866 assume IEEE-754 in most portable code these days. For more information,
21867 please see David Goldberg's classic paper
21868 @uref{https://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21869 Scientist Should Know About Floating-Point Arithmetic}.
21871 @node Exiting Portably
21872 @section Exiting Portably
21873 @cindex exiting portably
21875 A C or C++ program can exit with status @var{N} by returning
21876 @var{N} from the @code{main} function. Portable programs are supposed
21877 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21878 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21879 fail by exiting with status 1, and test programs that assume POSIX can
21880 fail by exiting with status values from 1 through 255.
21882 A program can also exit with status @var{N} by passing @var{N} to the
21883 @code{exit} function, and a program can fail by calling the @code{abort}
21884 function. If a program is specialized to just some platforms, it can fail
21885 by calling functions specific to those platforms, e.g., @code{_exit}
21886 (POSIX). However, like other functions, an exit
21887 function should be declared, typically by including a header. For
21888 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21889 either directly or via the default includes (@pxref{Default Includes}).
21891 A program can fail due to undefined behavior such as dereferencing a null
21892 pointer, but this is not recommended as undefined behavior allows an
21893 implementation to do whatever it pleases and this includes exiting
21897 @c ================================================== Manual Configuration
21899 @node Manual Configuration
21900 @chapter Manual Configuration
21902 A few kinds of features can't be guessed automatically by running test
21903 programs. For example, the details of the object-file format, or
21904 special options that need to be passed to the compiler or linker.
21905 Autoconf provides a uniform method for handling unguessable features,
21906 by giving each operating system a @dfn{canonical system type}, also
21907 known as a @dfn{canonical name} or @dfn{target triplet}.
21909 @prindex @command{config.guess}
21910 @prindex @command{config.sub}
21912 If you use any of the macros described in this chapter, you must
21913 distribute the helper scripts @command{config.guess} and
21914 @command{config.sub} along with your source code. Some Autoconf macros
21915 use these macros internally, so you may need to distribute these scripts
21916 even if you do not use any of these macros yourself. @xref{Input}, for
21917 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21918 to control in which directory @command{configure} looks for helper
21919 scripts, and where to get the scripts from.
21922 * Specifying Target Triplets:: Specifying target triplets
21923 * Canonicalizing:: Getting the canonical system type
21924 * Using System Type:: What to do with the system type
21927 @node Specifying Target Triplets
21928 @section Specifying target triplets
21929 @cindex System type
21930 @cindex Target triplet
21931 @c This node used to be named Specifying Names. The @anchor allows old
21932 @c links to still work.
21933 @anchor{Specifying Names}
21936 @command{configure} scripts can make decisions based on a canonical name
21937 for the system type, or @dfn{target triplet}, which has the form:
21938 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21939 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21941 @command{configure} can usually guess the canonical name for the type of
21942 system it's running on. To do so it runs a script called
21943 @command{config.guess}, which infers the name using the @code{uname}
21944 command or symbols predefined by the C preprocessor.
21946 Alternately, the user can specify the system type with command line
21947 arguments to @command{configure} (@pxref{System Types}. Doing so is
21949 cross-compiling. In the most complex case of cross-compiling, three
21950 system types are involved. The options to specify them are:
21953 @item --build=@var{build-type}
21954 the type of system on which the package is being configured and
21955 compiled. It defaults to the result of running @command{config.guess}.
21956 Specifying a @var{build-type} that differs from @var{host-type} enables
21957 cross-compilation mode.
21959 @item --host=@var{host-type}
21960 the type of system on which the package runs. By default it is the
21961 same as the build machine. The tools that get used to build and
21962 manipulate binaries will, by default, all be prefixed with
21963 @code{@var{host-type}-}, such as @code{@var{host-type}-gcc},
21964 @code{@var{host-type}-g++}, @code{@var{host-type}-ar}, and
21965 @code{@var{host-type}-nm}. If the binaries produced by these tools can
21966 be executed by the build system, the configure script will make use of
21967 it in @code{AC_RUN_IFELSE} invocations; otherwise, cross-compilation
21968 mode is enabled. Specifying a @var{host-type} that differs
21969 from @var{build-type}, when @var{build-type} was also explicitly
21970 specified, equally enables cross-compilation mode.
21972 @item --target=@var{target-type}
21973 the type of system for which any compiler tools in the package
21974 produce code (rarely needed). By default, it is the same as host.
21977 If you mean to override the result of @command{config.guess} but
21978 still produce binaries for the build machine, use @option{--build},
21979 not @option{--host}.
21981 So, for example, to produce binaries for 64-bit MinGW, use a command
21985 ./configure --host=x86_64-w64-mingw64
21988 If your system has the ability to execute MinGW binaries but you don't
21989 want to make use of this feature and instead prefer cross-compilation
21990 guesses, use a command like this:
21993 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
21997 Note that if you do not specify @option{--host}, @command{configure}
21998 fails if it can't run the code generated by the specified compiler. For
21999 example, configuring as follows fails:
22002 ./configure CC=x86_64-w64-mingw64-gcc
22005 When cross-compiling, @command{configure} will warn about any tools
22006 (compilers, linkers, assemblers) whose name is not prefixed with the
22007 host type. This is an aid to users performing cross-compilation.
22008 Continuing the example above, if a cross-compiler named @command{cc} is
22009 used with a native @command{pkg-config}, then libraries found by
22010 @command{pkg-config} will likely cause subtle build failures; but using
22011 the names @command{x86_64-w64-mingw64-gcc} and
22012 @command{x86_64-w64-mingw64-pkg-config}
22013 avoids any confusion. Avoiding the warning is as simple as creating the
22014 correct symlinks naming the cross tools.
22016 @cindex @command{config.sub}
22017 @command{configure} recognizes short aliases for some system types; for
22018 example, @samp{mingw64} can be used instead of
22019 @samp{x86_64-pc-mingw64}. @command{configure} runs a script called
22020 @command{config.sub} to canonicalize system type aliases.
22022 This section deliberately omits the description of the obsolete
22023 interface; see @ref{Hosts and Cross-Compilation}.
22026 @node Canonicalizing
22027 @section Getting the Canonical System Type
22028 @cindex System type
22029 @cindex Canonical system type
22031 The following macros make the system type available to @command{configure}
22034 @ovindex build_alias
22035 @ovindex host_alias
22036 @ovindex target_alias
22038 The variables @samp{build_alias}, @samp{host_alias}, and
22039 @samp{target_alias} are always exactly the arguments of @option{--build},
22040 @option{--host}, and @option{--target}; in particular, they are left empty
22041 if the user did not use them, even if the corresponding
22042 @code{AC_CANONICAL} macro was run. Any configure script may use these
22043 variables anywhere. These are the variables that should be used when in
22044 interaction with the user.
22046 If you need to recognize some special environments based on their system
22047 type, run the following macros to get canonical system names. These
22048 variables are not set before the macro call.
22050 @defmac AC_CANONICAL_BUILD
22051 @acindex{CANONICAL_BUILD}
22054 @ovindex build_vendor
22056 Compute the canonical build-system type variable, @code{build}, and its
22057 three individual parts @code{build_cpu}, @code{build_vendor}, and
22060 If @option{--build} was specified, then @code{build} is the
22061 canonicalization of @code{build_alias} by @command{config.sub},
22062 otherwise it is determined by the shell script @command{config.guess}.
22065 @defmac AC_CANONICAL_HOST
22066 @acindex{CANONICAL_HOST}
22069 @ovindex host_vendor
22071 Compute the canonical host-system type variable, @code{host}, and its
22072 three individual parts @code{host_cpu}, @code{host_vendor}, and
22075 If @option{--host} was specified, then @code{host} is the
22076 canonicalization of @code{host_alias} by @command{config.sub},
22077 otherwise it defaults to @code{build}.
22080 @defmac AC_CANONICAL_TARGET
22081 @acindex{CANONICAL_TARGET}
22083 @ovindex target_cpu
22084 @ovindex target_vendor
22086 Compute the canonical target-system type variable, @code{target}, and its
22087 three individual parts @code{target_cpu}, @code{target_vendor}, and
22090 If @option{--target} was specified, then @code{target} is the
22091 canonicalization of @code{target_alias} by @command{config.sub},
22092 otherwise it defaults to @code{host}.
22095 Note that there can be artifacts due to the backward compatibility
22096 code. @xref{Hosts and Cross-Compilation}, for more.
22098 @node Using System Type
22099 @section Using the System Type
22101 In @file{configure.ac} the system type is generally used by one or more
22102 @code{case} statements to select system-specifics. Shell wildcards can
22103 be used to match a group of system types.
22105 For example, an extra assembler code object file could be chosen, giving
22106 access to a CPU cycle counter register. @code{$(CYCLE_OBJ)} in the
22107 following would be used in a makefile to add the object to a
22108 program or library.
22112 [aarch64*-*-*], [CYCLE_OBJ=pmccntr.o],
22113 [i?86-*-*], [CYCLE_OBJ=rdtsc.o],
22115 AC_SUBST([CYCLE_OBJ])
22118 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22119 to select variant source files, for example optimized code for some
22120 CPUs. The configured CPU type doesn't always indicate exact CPU types,
22121 so some runtime capability checks may be necessary too.
22125 [aarch64*-*-*], [AC_CONFIG_LINKS([dither.c:aarch64/dither.c])],
22126 [powerpc*-*-*], [AC_CONFIG_LINKS([dither.c:powerpc/dither.c])],
22127 [AC_CONFIG_LINKS([dither.c:generic/dither.c])])
22130 The host system type can also be used to find cross-compilation tools
22131 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22133 The above examples all show @samp{$host}, since this is where the code
22134 is going to run. Only rarely is it necessary to test @samp{$build}
22135 (which is where the build is being done).
22137 Whenever you're tempted to use @samp{$host} it's worth considering
22138 whether some sort of probe would be better. New system types come along
22139 periodically or previously missing features are added. Well-written
22140 probes can adapt themselves to such things, but hard-coded lists of
22141 names can't. Here are some guidelines,
22145 Availability of libraries and library functions should always be checked
22148 Variant behavior of system calls is best identified with runtime tests
22149 if possible, but bug workarounds or obscure difficulties might have to
22150 be driven from @samp{$host}.
22152 Assembler code is inevitably highly CPU-specific and is best selected
22153 according to @samp{$host_cpu}.
22155 Assembler variations like underscore prefix on globals or ELF versus
22156 COFF type directives are however best determined by probing, perhaps
22157 even examining the compiler output.
22160 @samp{$target} is for use by a package creating a compiler or similar.
22161 For ordinary packages it's meaningless and should not be used. It
22162 indicates what the created compiler should generate code for, if it can
22163 cross-compile. @samp{$target} generally selects various hard-coded CPU
22164 and system conventions, since usually the compiler or tools under
22165 construction themselves determine how the target works.
22168 @c ===================================================== Site Configuration.
22170 @node Site Configuration
22171 @chapter Site Configuration
22173 @command{configure} scripts support several kinds of local configuration
22174 decisions. There are ways for users to specify where external software
22175 packages are, include or exclude optional features, install programs
22176 under modified names, and set default values for @command{configure}
22180 * Help Formatting:: Customizing @samp{configure --help}
22181 * External Software:: Working with other optional software
22182 * Package Options:: Selecting optional features
22183 * Pretty Help Strings:: Formatting help string
22184 * Option Checking:: Controlling checking of @command{configure} options
22185 * Site Details:: Configuring site details
22186 * Transforming Names:: Changing program names when installing
22187 * Site Defaults:: Giving @command{configure} local defaults
22190 @node Help Formatting
22191 @section Controlling Help Output
22193 Users consult @samp{configure --help} to learn of configuration
22194 decisions specific to your package. By default, @command{configure}
22195 breaks this output into sections for each type of option; within each
22196 section, help strings appear in the order @file{configure.ac} defines
22202 --enable-bar include bar
22209 @defmac AC_PRESERVE_HELP_ORDER
22210 @acindex{PRESERVE_HELP_ORDER}
22212 Request an alternate @option{--help} format, in which options of all
22213 types appear together, in the order defined. Call this macro before any
22214 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22217 Optional Features and Packages:
22219 --enable-bar include bar
22225 @node External Software
22226 @section Working With External Software
22227 @cindex External software
22229 Some packages require, or can optionally use, other software packages
22230 that are already installed. The user can give @command{configure}
22231 command line options to specify which such external software to use.
22232 The options have one of these forms:
22234 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22237 --with-@var{package}@r{[}=@var{arg}@r{]}
22238 --without-@var{package}
22241 For example, @option{--with-gnu-ld} means work with the GNU linker
22242 instead of some other linker. @option{--with-x} means work with The X
22245 The user can give an argument by following the package name with
22246 @samp{=} and the argument. Giving an argument of @samp{no} is for
22247 packages that are used by default; it says to @emph{not} use the
22248 package. An argument that is neither @samp{yes} nor @samp{no} could
22249 include a name or number of a version of the other package, to specify
22250 more precisely which other package this program is supposed to work
22251 with. If no argument is given, it defaults to @samp{yes}.
22252 @option{--without-@var{package}} is equivalent to
22253 @option{--with-@var{package}=no}.
22255 Normally @command{configure} scripts complain about
22256 @option{--with-@var{package}} options that they do not support.
22257 @xref{Option Checking}, for details, and for how to override the
22260 For each external software package that may be used, @file{configure.ac}
22261 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22262 user asked to use it. Whether each package is used or not by default,
22263 and which arguments are valid, is up to you.
22265 @anchor{AC_ARG_WITH}
22266 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22267 @ovar{action-if-given}, @ovar{action-if-not-given})
22269 If the user gave @command{configure} the option @option{--with-@var{package}}
22270 or @option{--without-@var{package}}, run shell commands
22271 @var{action-if-given}. If neither option was given, run shell commands
22272 @var{action-if-not-given}. The name @var{package} indicates another
22273 software package that this program should work with. It should consist
22274 only of alphanumeric characters, dashes, plus signs, and dots.
22276 The option's argument is available to the shell commands
22277 @var{action-if-given} in the shell variable @code{withval}, which is
22278 actually just the value of the shell variable named
22279 @code{with_@var{package}}, with any non-alphanumeric characters in
22280 @var{package} changed into @samp{_}. You may use that variable instead,
22283 Note that @var{action-if-not-given} is not expanded until the point that
22284 @code{AC_ARG_WITH} was expanded. If you need the value of
22285 @code{with_@var{package}} set to a default value by the time argument
22286 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22287 diversion (@pxref{m4_divert_text}) (if done as an argument to
22288 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22291 The argument @var{help-string} is a description of the option that
22294 --with-readline support fancy command line editing
22298 @var{help-string} may be more than one line long, if more detail is
22299 needed. Just make sure the columns line up in @samp{configure
22300 --help}. Avoid tabs in the help string. The easiest way to provide the
22301 proper leading whitespace is to format your @var{help-string} with the macro
22302 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22304 The following example shows how to use the @code{AC_ARG_WITH} macro in
22305 a common situation. You want to let the user decide whether to enable
22306 support for an external library (e.g., the readline library); if the user
22307 specified neither @option{--with-readline} nor @option{--without-readline},
22308 you want to enable support for readline only if the library is available
22311 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22313 AC_ARG_WITH([readline],
22314 [AS_HELP_STRING([--with-readline],
22315 [support fancy command line editing @@<:@@default=check@@:>@@])],
22317 [: m4_divert_text([DEFAULTS], [with_readline=check])])
22320 AS_IF([test "x$with_readline" != xno],
22321 [AC_CHECK_LIB([readline], [main],
22322 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22323 AC_DEFINE([HAVE_LIBREADLINE], [1],
22324 [Define if you have libreadline])
22326 [if test "x$with_readline" != xcheck; then
22328 [--with-readline was given, but test for readline failed])
22333 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22334 possibility to enable support for the readline library, in case it is still
22335 experimental and not well tested, and is therefore disabled by default.
22337 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22339 AC_ARG_WITH([readline],
22340 [AS_HELP_STRING([--with-readline],
22341 [enable experimental support for readline])],
22343 [with_readline=no])
22346 AS_IF([test "x$with_readline" != xno],
22347 [AC_CHECK_LIB([readline], [main],
22348 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22349 AC_DEFINE([HAVE_LIBREADLINE], [1],
22350 [Define if you have libreadline])
22353 [--with-readline was given, but test for readline failed])],
22357 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22358 possibility to disable support for the readline library, given that it is
22359 an important feature and that it should be enabled by default.
22361 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22363 AC_ARG_WITH([readline],
22364 [AS_HELP_STRING([--without-readline],
22365 [disable support for readline])],
22367 [with_readline=yes])
22370 AS_IF([test "x$with_readline" != xno],
22371 [AC_CHECK_LIB([readline], [main],
22372 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22373 AC_DEFINE([HAVE_LIBREADLINE], [1],
22374 [Define if you have libreadline])
22377 [readline test failed (--without-readline to disable)])],
22381 These three examples can be easily adapted to the case where
22382 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22383 @ref{Package Options}).
22386 @node Package Options
22387 @section Choosing Package Options
22388 @cindex Package options
22389 @cindex Options, package
22391 If a software package has optional compile-time features, the user can
22392 give @command{configure} command line options to specify whether to
22393 compile them. The options have one of these forms:
22395 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22398 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22399 --disable-@var{feature}
22402 These options allow users to choose which optional features to build and
22403 install. @option{--enable-@var{feature}} options should never make a
22404 feature behave differently or cause one feature to replace another.
22405 They should only cause parts of the program to be built rather than left
22408 The user can give an argument by following the feature name with
22409 @samp{=} and the argument. Giving an argument of @samp{no} requests
22410 that the feature @emph{not} be made available. A feature with an
22411 argument looks like @option{--enable-debug=stabs}. If no argument is
22412 given, it defaults to @samp{yes}. @option{--disable-@var{feature}} is
22413 equivalent to @option{--enable-@var{feature}=no}.
22415 Normally @command{configure} scripts complain about
22416 @option{--enable-@var{package}} options that they do not support.
22417 @xref{Option Checking}, for details, and for how to override the
22420 For each optional feature, @file{configure.ac} should call
22421 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22422 to include it. Whether each feature is included or not by default, and
22423 which arguments are valid, is up to you.
22425 @anchor{AC_ARG_ENABLE}
22426 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22427 @ovar{action-if-given}, @ovar{action-if-not-given})
22428 @acindex{ARG_ENABLE}
22429 If the user gave @command{configure} the option
22430 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22431 shell commands @var{action-if-given}. If neither option was given, run
22432 shell commands @var{action-if-not-given}. The name @var{feature}
22433 indicates an optional user-level facility. It should consist only of
22434 alphanumeric characters, dashes, plus signs, and dots.
22436 The option's argument is available to the shell commands
22437 @var{action-if-given} in the shell variable @code{enableval}, which is
22438 actually just the value of the shell variable named
22439 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22440 @var{feature} changed into @samp{_}. You may use that variable instead,
22441 if you wish. The @var{help-string} argument is like that of
22442 @code{AC_ARG_WITH} (@pxref{External Software}).
22444 Note that @var{action-if-not-given} is not expanded until the point that
22445 @code{AC_ARG_ENABLE} was expanded. If you need the value of
22446 @code{enable_@var{feature}} set to a default value by the time argument
22447 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22448 diversion (@pxref{m4_divert_text}) (if done as an argument to
22449 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22452 You should format your @var{help-string} with the macro
22453 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22455 See the examples suggested with the definition of @code{AC_ARG_WITH}
22456 (@pxref{External Software}) to get an idea of possible applications of
22457 @code{AC_ARG_ENABLE}.
22460 @node Pretty Help Strings
22461 @section Making Your Help Strings Look Pretty
22462 @cindex Help strings
22464 Properly formatting the @samp{help strings} which are used in
22465 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22466 (@pxref{Package Options}) can be challenging. Specifically, you want
22467 your own @samp{help strings} to line up in the appropriate columns of
22468 @samp{configure --help} just like the standard Autoconf @samp{help
22469 strings} do. This is the purpose of the @code{AS_HELP_STRING} macro.
22471 @anchor{AS_HELP_STRING}
22472 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22473 @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22474 @asindex{HELP_STRING}
22476 Expands into a help string that looks pretty when the user executes
22477 @samp{configure --help}. It is typically used in @code{AC_ARG_WITH}
22478 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22479 Options}). The following example makes this clearer.
22483 [AS_HELP_STRING([--with-foo],
22484 [use foo (default is no)])],
22485 [use_foo=$withval],
22489 Then the last few lines of @samp{configure --help} appear like
22493 --enable and --with options recognized:
22494 --with-foo use foo (default is no)
22497 Macro expansion is performed on the first argument. However, the second
22498 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22499 list of text to be reformatted, and is not subject to macro expansion.
22500 Since it is not expanded, it should not be double quoted.
22501 @xref{Autoconf Language}, for a more detailed explanation.
22503 The @code{AS_HELP_STRING} macro is particularly helpful when the
22504 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22505 arguments, as shown in the following example. Be aware that
22506 @var{left-hand-side} may not expand to unbalanced quotes,
22507 although quadrigraphs can be used.
22510 AC_DEFUN([MY_ARG_WITH],
22511 [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22512 [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22513 [use $1 (default is $2)])],
22514 [use_[]$1=$withval],
22516 MY_ARG_WITH([a_b], [no])
22519 Here, the last few lines of @samp{configure --help} will include:
22522 --enable and --with options recognized:
22523 --with-a-b use a_b (default is no)
22526 The parameters @var{indent-column} and @var{wrap-column} were introduced
22527 in Autoconf 2.62. Generally, they should not be specified; they exist
22528 for fine-tuning of the wrapping.
22530 AS_HELP_STRING([--option], [description of option])
22531 @result{} --option description of option
22532 AS_HELP_STRING([--option], [description of option], [15], [30])
22533 @result{} --option description of
22539 @node Option Checking
22540 @section Controlling Checking of @command{configure} Options
22541 @cindex Options, Package
22543 The @command{configure} script checks its command-line options against a
22544 list of known options, like @option{--help} or @option{--config-cache}.
22545 An unknown option ordinarily indicates a mistake by the user and
22546 @command{configure} halts with an error. However, by default unknown
22547 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22548 options elicit only a warning, to support configuring entire source
22551 Source trees often contain multiple packages with a top-level
22552 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22553 (@pxref{Subdirectories}). Because the packages generally support
22554 different @option{--with-@var{package}} and
22555 @option{--enable-@var{feature}} options, the GNU Coding
22556 Standards say they must accept unrecognized options without halting.
22557 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22558 automatically disables the warnings.
22560 This default behavior may be modified in two ways. First, the installer
22561 can invoke @code{configure --disable-option-checking} to disable
22562 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22563 options to turn them into fatal errors, respectively. Second, the
22564 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22566 @defmac AC_DISABLE_OPTION_CHECKING
22567 @acindex{DISABLE_OPTION_CHECKING}
22569 By default, disable warnings related to any unrecognized
22570 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22571 options. This is implied by @code{AC_CONFIG_SUBDIRS}.
22573 The installer can override this behavior by passing
22574 @option{--enable-option-checking} (enable warnings) or
22575 @option{--enable-option-checking=fatal} (enable errors) to
22576 @command{configure}.
22581 @section Configuring Site Details
22582 @cindex Site details
22584 Some software packages require complex site-specific information. Some
22585 examples are host names to use for certain services, company names, and
22586 email addresses to contact. Since some configuration scripts generated
22587 by Metaconfig ask for such information interactively, people sometimes
22588 wonder how to get that information in Autoconf-generated configuration
22589 scripts, which aren't interactive.
22591 Such site configuration information should be put in a file that is
22592 edited @emph{only by users}, not by programs. The location of the file
22593 can either be based on the @code{prefix} variable, or be a standard
22594 location such as the user's home directory. It could even be specified
22595 by an environment variable. The programs should examine that file at
22596 runtime, rather than at compile time. Runtime configuration is more
22597 convenient for users and makes the configuration process simpler than
22598 getting the information while configuring. @xref{Directory Variables, ,
22599 Variables for Installation Directories, standards, The GNU Coding
22600 Standards}, for more information on where to put data files.
22602 @node Transforming Names
22603 @section Transforming Program Names When Installing
22604 @cindex Transforming program names
22605 @cindex Program names, transforming
22607 Autoconf supports changing the names of programs when installing them.
22608 In order to use these transformations, @file{configure.ac} must call the
22609 macro @code{AC_ARG_PROGRAM}.
22611 @defmac AC_ARG_PROGRAM
22612 @acindex{ARG_PROGRAM}
22613 @ovindex program_transform_name
22614 Place in output variable @code{program_transform_name} a sequence of
22615 @code{sed} commands for changing the names of installed programs.
22617 If any of the options described below are given to @command{configure},
22618 program names are transformed accordingly. Otherwise, if
22619 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22620 is given, the target type followed by a dash is used as a prefix.
22621 Otherwise, no program name transformation is done.
22625 * Transformation Options:: @command{configure} options to transform names
22626 * Transformation Examples:: Sample uses of transforming names
22627 * Transformation Rules:: Makefile uses of transforming names
22630 @node Transformation Options
22631 @subsection Transformation Options
22633 You can specify name transformations by giving @command{configure} these
22634 command line options:
22637 @item --program-prefix=@var{prefix}
22638 prepend @var{prefix} to the names;
22640 @item --program-suffix=@var{suffix}
22641 append @var{suffix} to the names;
22643 @item --program-transform-name=@var{expression}
22644 perform @code{sed} substitution @var{expression} on the names.
22647 @node Transformation Examples
22648 @subsection Transformation Examples
22650 These transformations are useful with programs that can be part of a
22651 cross-compilation development environment. For example, a
22652 cross-assembler running on x86-64 configured with
22653 @option{--target=aarch64-linux-gnu} is normally installed as
22654 @file{aarch64-linux-gnu-as}, rather than @file{as}, which could be confused
22655 with a native x86-64 assembler.
22657 You can force a program name to begin with @file{g}, if you don't want
22658 GNU programs installed on your system to shadow other programs with
22659 the same name. For example, if you configure GNU @code{diff} with
22660 @option{--program-prefix=g}, then when you run @samp{make install} it is
22661 installed as @file{/usr/local/bin/gdiff}.
22663 As a more sophisticated example, you could use
22666 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22670 to prepend @samp{g} to most of the program names in a source tree,
22671 excepting those like @code{gdb} that already have one and those like
22672 @code{less} and @code{lesskey} that aren't GNU programs. (That is
22673 assuming that you have a source tree containing those programs that is
22674 set up to use this feature.)
22676 One way to install multiple versions of some programs simultaneously is
22677 to append a version number to the name of one or both. For example, if
22678 you want to keep Autoconf version 1 around for awhile, you can configure
22679 Autoconf version 2 using @option{--program-suffix=2} to install the
22680 programs as @file{/usr/local/bin/autoconf2},
22681 @file{/usr/local/bin/autoheader2}, etc. Nevertheless, pay attention
22682 that only the binaries are renamed, therefore you'd have problems with
22683 the library files which might overlap.
22685 @node Transformation Rules
22686 @subsection Transformation Rules
22688 Here is how to use the variable @code{program_transform_name} in a
22689 @file{Makefile.in}:
22692 PROGRAMS = cp ls rm
22693 transform = @@program_transform_name@@
22695 for p in $(PROGRAMS); do \
22696 $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22697 sed '$(transform)'`; \
22701 for p in $(PROGRAMS); do \
22702 rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22703 @c $$ restore font-lock
22707 It is guaranteed that @code{program_transform_name} is never empty, and
22708 that there are no useless separators. Therefore you may safely embed
22709 @code{program_transform_name} within a sed program using @samp{;}:
22712 transform = @@program_transform_name@@
22713 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22716 Whether to do the transformations on documentation files (Texinfo or
22717 @code{man}) is a tricky question; there seems to be no perfect answer,
22718 due to the several reasons for name transforming. Documentation is not
22719 usually particular to a specific architecture, and Texinfo files do not
22720 conflict with system documentation. But they might conflict with
22721 earlier versions of the same files, and @code{man} pages sometimes do
22722 conflict with system documentation. As a compromise, it is probably
22723 best to do name transformations on @code{man} pages but not on Texinfo
22726 @node Site Defaults
22727 @section Setting Site Defaults
22728 @cindex Site defaults
22729 @cindex config.site
22731 Autoconf-generated @command{configure} scripts allow your site to provide
22732 default values for some configuration values. You do this by creating
22733 site- and system-wide initialization files.
22735 @evindex CONFIG_SITE
22736 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22737 uses its value as a space-separated list of shell scripts to read;
22738 it is recommended that these be absolute file names. Otherwise, it
22739 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22740 then @file{@var{prefix}/etc/config.site} if it exists. Thus,
22741 settings in machine-specific files override those in machine-independent
22742 ones in case of conflict.
22744 Site files can be arbitrary shell scripts, but only certain kinds of
22745 code are really appropriate to be in them. Because @command{configure}
22746 reads any cache file after it has read any site files, a site file can
22747 define a default cache file to be shared between all Autoconf-generated
22748 @command{configure} scripts run on that system (@pxref{Cache Files}). If
22749 you set a default cache file in a site file, it is a good idea to also
22750 set the output variable @code{CC} in that site file, because the cache
22751 file is only valid for a particular compiler, but many systems have
22754 You can examine or override the value set by a command line option to
22755 @command{configure} in a site file; options set shell variables that have
22756 the same names as the options, with any dashes turned into underscores.
22757 The exceptions are that @option{--without-} and @option{--disable-} options
22758 are like giving the corresponding @option{--with-} or @option{--enable-}
22759 option and the value @samp{no}. Thus, @option{--cache-file=localcache}
22760 sets the variable @code{cache_file} to the value @samp{localcache};
22761 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22762 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22763 variable @code{prefix} to the value @samp{/usr}; etc.
22765 Site files are also good places to set default values for other output
22766 variables, such as @code{CFLAGS}, if you need to give them non-default
22767 values: anything you would normally do, repetitively, on the command
22768 line. If you use non-default values for @var{prefix} or
22769 @var{exec_prefix} (wherever you locate the site file), you can set them
22770 in the site file if you specify it with the @code{CONFIG_SITE}
22771 environment variable.
22773 You can set some cache values in the site file itself. Doing this is
22774 useful if you are cross-compiling, where it is impossible to check features
22775 that require running a test program. You could ``prime the cache'' by
22776 setting those values correctly for that system in
22777 @file{@var{prefix}/etc/config.site}. To find out the names of the cache
22778 variables you need to set, see the documentation of the respective
22779 Autoconf macro. If the variables or their semantics are undocumented,
22780 you may need to look for shell variables with @samp{_cv_} in their names
22781 in the affected @command{configure} scripts, or in the Autoconf M4
22782 source code for those macros; but in that case, their name or semantics
22783 may change in a future Autoconf version.
22785 The cache file is careful to not override any variables set in the site
22786 files. Similarly, you should not override command-line options in the
22787 site files. Your code should check that variables such as @code{prefix}
22788 and @code{cache_file} have their default values (as set near the top of
22789 @command{configure}) before changing them.
22791 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}. The
22792 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22793 file (if @code{CONFIG_SITE} is not set to a different file).
22796 # /usr/share/local/gnu/share/config.site for configure
22798 # Change some defaults.
22799 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22800 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22801 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22802 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22803 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
22805 # Give Autoconf 2.x generated configure scripts a shared default
22806 # cache file for feature test results, architecture-specific.
22807 if test "$cache_file" = /dev/null; then
22808 cache_file="$prefix/var/config.cache"
22809 # A cache file is only valid for one C compiler.
22814 @c Leave this use of "File system" rendered as one word, but
22815 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22816 @cindex File@/system Hierarchy Standard
22819 Another use of @file{config.site} is for priming the directory variables
22820 @c "File system", but slightly obfuscated, as above.
22821 in a manner consistent with the File@/system Hierarchy Standard
22822 (FHS). Once the following file is installed at
22823 @file{/usr/share/config.site}, a user can execute simply
22824 @code{./configure --prefix=/usr} to get all the directories chosen in
22825 the locations recommended by FHS.
22828 # /usr/share/config.site for FHS defaults when installing below /usr,
22829 # and the respective settings were not changed on the command line.
22830 if test "$prefix" = /usr; then
22831 test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22832 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22833 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22837 @cindex @file{lib64}
22838 @cindex 64-bit libraries
22839 Likewise, on platforms where 64-bit libraries are built by default, then
22840 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22841 it is appropriate to install @file{/usr/local/@/share/config.site}:
22844 # /usr/local/share/config.site for platforms that prefer
22845 # the directory /usr/local/lib64 over /usr/local/lib.
22846 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22850 @c ============================================== Running configure Scripts.
22852 @node Running configure Scripts
22853 @chapter Running @command{configure} Scripts
22854 @cindex @command{configure}
22856 Below are instructions on how to configure a package that uses a
22857 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22858 file in the package. A plain-text version of @file{INSTALL} which you
22859 may use comes with Autoconf.
22862 * Basic Installation:: Instructions for typical cases
22863 * Compilers and Options:: Selecting compilers and optimization
22864 * Multiple Architectures:: Compiling for multiple architectures at once
22865 * Installation Names:: Installing in different directories
22866 * Optional Features:: Selecting optional features
22867 * System Types:: Specifying a system type
22868 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
22869 * Defining Variables:: Specifying the compiler etc.
22870 * configure Invocation:: Changing how @command{configure} runs
22874 @include install.texi
22877 @c ============================================== config.status Invocation
22879 @node config.status Invocation
22880 @chapter config.status Invocation
22881 @cindex @command{config.status}
22883 The @command{configure} script creates a file named @file{config.status},
22884 which actually configures, @dfn{instantiates}, the template files. It
22885 also records the configuration options that were specified when the
22886 package was last configured in case reconfiguring is needed.
22890 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22893 It configures each @var{tag}; if none are specified, all the templates
22894 are instantiated. A @var{tag} refers to a file or other tag associated
22895 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22896 macro (@pxref{Configuration Actions}). The files must be specified
22897 without their dependencies, as in
22900 ./config.status foobar
22907 ./config.status foobar:foo.in:bar.in
22910 The supported options are:
22915 Print a summary of the command line options, the list of the template
22920 Print the version number of Autoconf and the configuration settings,
22924 Print the configuration settings in reusable way, quoted for the shell,
22925 and exit. For example, for a debugging build that otherwise reuses the
22926 configuration from a different build directory @var{build-dir} of a
22927 package in @var{src-dir}, you could use the following:
22930 args=`@var{build-dir}/config.status --config`
22931 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22935 Note that it may be necessary to override a @option{--srcdir} setting
22936 that was saved in the configuration, if the arguments are used in a
22937 different build directory.
22942 Do not print progress messages.
22946 Don't remove the temporary files.
22948 @item --file=@var{file}[:@var{template}]
22949 Require that @var{file} be instantiated as if
22950 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used. Both
22951 @var{file} and @var{template} may be @samp{-} in which case the standard
22952 output and/or standard input, respectively, is used. If a
22953 @var{template} file name is relative, it is first looked for in the build
22954 tree, and then in the source tree. @xref{Configuration Actions}, for
22957 This option and the following ones provide one way for separately
22958 distributed packages to share the values computed by @command{configure}.
22959 Doing so can be useful if some of the packages need a superset of the
22960 features that one of them, perhaps a common library, does. These
22961 options allow a @file{config.status} file to create files other than the
22962 ones that its @file{configure.ac} specifies, so it can be used for a
22963 different package, or for extracting a subset of values. For example,
22966 echo '@@CC@@' | ./config.status --file=-
22970 provides the value of @code{@@CC@@} on standard output.
22972 @item --header=@var{file}[:@var{template}]
22973 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22976 Ask @file{config.status} to update itself and exit (no instantiation).
22977 This option is useful if you change @command{configure}, so that the
22978 results of some tests might be different from the previous run. The
22979 @option{--recheck} option reruns @command{configure} with the same arguments
22980 you used before, plus the @option{--no-create} option, which prevents
22981 @command{configure} from running @file{config.status} and creating
22982 @file{Makefile} and other files, and the @option{--no-recursion} option,
22983 which prevents @command{configure} from running other @command{configure}
22984 scripts in subdirectories. (This is so other Make rules can
22985 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22989 @file{config.status} checks several optional environment variables that
22990 can alter its behavior:
22992 @anchor{CONFIG_SHELL}
22993 @defvar CONFIG_SHELL
22994 @evindex CONFIG_SHELL
22995 The shell with which to run @command{configure}. It must be
22996 Bourne-compatible, and the absolute name of the shell should be passed.
22997 The default is a shell that supports @code{LINENO} if available, and
22998 @file{/bin/sh} otherwise.
23001 @defvar CONFIG_STATUS
23002 @evindex CONFIG_STATUS
23003 The file name to use for the shell script that records the
23004 configuration. The default is @file{./config.status}. This variable is
23005 useful when one package uses parts of another and the @command{configure}
23006 scripts shouldn't be merged because they are maintained separately.
23009 You can use @file{./config.status} in your makefiles. For example, in
23010 the dependencies given above (@pxref{Automatic Remaking}),
23011 @file{config.status} is run twice when @file{configure.ac} has changed.
23012 If that bothers you, you can make each run only regenerate the files for
23017 stamp-h: config.h.in config.status
23018 ./config.status config.h
23021 Makefile: Makefile.in config.status
23022 ./config.status Makefile
23026 The calling convention of @file{config.status} has changed; see
23027 @ref{Obsolete config.status Use}, for details.
23030 @c =================================================== Obsolete Constructs
23032 @node Obsolete Constructs
23033 @chapter Obsolete Constructs
23034 @cindex Obsolete constructs
23036 Autoconf changes, and throughout the years some constructs have been
23037 obsoleted. Most of the changes involve the macros, but in some cases
23038 the tools themselves, or even some concepts, are now considered
23041 You may completely skip this chapter if you are new to Autoconf. Its
23042 intention is mainly to help maintainers updating their packages by
23043 understanding how to move to more modern constructs.
23046 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
23047 * acconfig Header:: Additional entries in @file{config.h.in}
23048 * autoupdate Invocation:: Automatic update of @file{configure.ac}
23049 * Obsolete Macros:: Backward compatibility macros
23050 * Autoconf 1:: Tips for upgrading your files
23051 * Autoconf 2.13:: Some fresher tips
23054 @node Obsolete config.status Use
23055 @section Obsolete @file{config.status} Invocation
23057 @file{config.status} now supports arguments to specify the files to
23058 instantiate; see @ref{config.status Invocation}, for more details.
23059 Before, environment variables had to be used.
23061 @defvar CONFIG_COMMANDS
23062 @evindex CONFIG_COMMANDS
23063 The tags of the commands to execute. The default is the arguments given
23064 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23065 @file{configure.ac}.
23068 @defvar CONFIG_FILES
23069 @evindex CONFIG_FILES
23070 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23071 The default is the arguments given to @code{AC_OUTPUT} and
23072 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23075 @defvar CONFIG_HEADERS
23076 @evindex CONFIG_HEADERS
23077 The files in which to substitute C @code{#define} statements. The
23078 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23079 macro was not called, @file{config.status} ignores this variable.
23082 @defvar CONFIG_LINKS
23083 @evindex CONFIG_LINKS
23084 The symbolic links to establish. The default is the arguments given to
23085 @code{AC_CONFIG_LINKS}; if that macro was not called,
23086 @file{config.status} ignores this variable.
23089 In @ref{config.status Invocation}, using this old interface, the example
23095 stamp-h: config.h.in config.status
23096 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23097 CONFIG_HEADERS=config.h ./config.status
23100 Makefile: Makefile.in config.status
23101 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23102 CONFIG_FILES=Makefile ./config.status
23107 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23108 no need to set @code{CONFIG_HEADERS} in the @command{make} rules. Equally
23109 for @code{CONFIG_COMMANDS}, etc.)
23112 @node acconfig Header
23113 @section @file{acconfig.h}
23115 @cindex @file{acconfig.h}
23116 @cindex @file{config.h.top}
23117 @cindex @file{config.h.bot}
23119 In order to produce @file{config.h.in}, @command{autoheader} needs to
23120 build or to find templates for each symbol. Modern releases of Autoconf
23121 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23122 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23123 list of needed templates. @command{autoheader} copied comments and
23124 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23125 the current directory, if present. This file used to be mandatory if
23126 you @code{AC_DEFINE} any additional symbols.
23128 Modern releases of Autoconf also provide @code{AH_TOP} and
23129 @code{AH_BOTTOM} if you need to prepend/append some information to
23130 @file{config.h.in}. Ancient versions of Autoconf had a similar feature:
23131 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23132 @command{autoheader} copies the lines before the line containing
23133 @samp{@@TOP@@} into the top of the file that it generates. Similarly,
23134 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23135 @command{autoheader} copies the lines after that line to the end of the
23136 file it generates. Either or both of those strings may be omitted. An
23137 even older alternate way to produce the same effect in ancient versions
23138 of Autoconf is to create the files @file{@var{file}.top} (typically
23139 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23140 directory. If they exist, @command{autoheader} copies them to the
23141 beginning and end, respectively, of its output.
23143 In former versions of Autoconf, the files used in preparing a software
23144 package for distribution were:
23147 configure.ac --. .------> autoconf* -----> configure
23149 [aclocal.m4] --+ `---.
23151 +--> [autoheader*] -> [config.h.in]
23152 [acconfig.h] ----. |
23159 Using only the @code{AH_} macros, @file{configure.ac} should be
23160 self-contained, and should not depend upon @file{acconfig.h} etc.
23163 @node autoupdate Invocation
23164 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23165 @cindex @command{autoupdate}
23167 The @command{autoupdate} program updates a @file{configure.ac} file that
23168 calls Autoconf macros by their old names to use the current macro names.
23169 In version 2 of Autoconf, most of the macros were renamed to use a more
23170 uniform and descriptive naming scheme. @xref{Macro Names}, for a
23171 description of the new scheme. Although the old names still work
23172 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23173 new names), you can make your @file{configure.ac} files more readable
23174 and make it easier to use the current Autoconf documentation if you
23175 update them to use the new macro names.
23177 @evindex SIMPLE_BACKUP_SUFFIX
23178 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23179 backing up the original version with the suffix @file{~} (or the value
23180 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23181 set). If you give @command{autoupdate} an argument, it reads that file
23182 instead of @file{configure.ac} and writes the updated file to the
23186 @command{autoupdate} accepts the following options:
23191 Print a summary of the command line options and exit.
23195 Print the version number of Autoconf and exit.
23199 Report processing steps.
23203 Don't remove the temporary files.
23207 Force the update even if the file has not changed. Disregard the cache.
23209 @item --include=@var{dir}
23210 @itemx -I @var{dir}
23211 Also look for input files in @var{dir}. Multiple invocations accumulate.
23212 Directories are browsed from last to first.
23214 @item --prepend-include=@var{dir}
23215 @itemx -B @var{dir}
23216 Prepend directory @var{dir} to the search path. This is used to include
23217 the language-specific files before any third-party macros.
23220 @node Obsolete Macros
23221 @section Obsolete Macros
23223 Several macros are obsoleted in Autoconf, for various reasons (typically
23224 they failed to quote properly, couldn't be extended for more recent
23225 issues, etc.). They are still supported, but deprecated: their use
23228 During the jump from Autoconf version 1 to version 2, most of the
23229 macros were renamed to use a more uniform and descriptive naming scheme,
23230 but their signature did not change. @xref{Macro Names}, for a
23231 description of the new naming scheme. Below, if there is just the mapping
23232 from old names to new names for these macros, the reader is invited to
23233 refer to the definition of the new macro for the signature and the
23238 @cvindex _ALL_SOURCE
23239 This macro is a platform-specific subset of
23240 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23245 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23248 @defmac AC_ARG_ARRAY
23249 @acindex{ARG_ARRAY}
23250 Removed because of limited usefulness.
23255 This macro is obsolete; it does nothing.
23258 @defmac AC_C_LONG_DOUBLE
23259 @acindex{C_LONG_DOUBLE}
23260 @cvindex HAVE_LONG_DOUBLE
23261 If the C compiler supports a working @code{long double} type with more
23262 range or precision than the @code{double} type, define
23263 @code{HAVE_LONG_DOUBLE}.
23265 You should use @code{AC_TYPE_LONG_DOUBLE} or
23266 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23269 @defmac AC_CANONICAL_SYSTEM
23270 @acindex{CANONICAL_SYSTEM}
23271 Determine the system type and set output variables to the names of the
23272 canonical system types. @xref{Canonicalizing}, for details about the
23273 variables this macro sets.
23275 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23276 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23277 the needs. Using @code{AC_CANONICAL_TARGET} is enough to run the two
23278 other macros (@pxref{Canonicalizing}).
23281 @defmac AC_CHAR_UNSIGNED
23282 @acindex{CHAR_UNSIGNED}
23283 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23286 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23287 @acindex{CHECK_TYPE}
23288 Autoconf, up to 2.13, used to provide this version of
23289 @code{AC_CHECK_TYPE}, deprecated because of its flaws. First, although
23290 it is a member of the @code{CHECK} clan, it does
23291 more than just checking. Secondly, missing types are defined
23292 using @code{#define}, not @code{typedef}, and this can lead to
23293 problems in the case of pointer types.
23295 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23296 @ref{Generic Types}, for the description of the current macro.
23298 If the type @var{type} is not defined, define it to be the C (or C++)
23299 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23301 This macro is equivalent to:
23304 AC_CHECK_TYPE([@var{type}], [],
23305 [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23306 [Define to '@var{default}'
23307 if <sys/types.h> does not define.])])
23310 In order to keep backward compatibility, the two versions of
23311 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23315 If there are three or four arguments, the modern version is used.
23318 If the second argument appears to be a C or C++ type, then the
23319 obsolete version is used. This happens if the argument is a C or C++
23320 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23321 followed by one of @samp{[(* } and then by a string of zero or more
23322 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23325 If the second argument is spelled with the alphabet of valid C and C++
23326 types, the user is warned and the modern version is used.
23329 Otherwise, the modern version is used.
23333 You are encouraged either to use a valid builtin type, or to use the
23334 equivalent modern code (see above), or better yet, to use
23335 @code{AC_CHECK_TYPES} together with
23338 #ifndef HAVE_LOFF_T
23339 typedef loff_t off_t;
23343 @c end of AC_CHECK_TYPE
23345 @defmac AC_CHECKING (@var{feature-description})
23350 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23354 @xref{AC_MSG_NOTICE}.
23357 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23358 @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23359 @acindex{COMPILE_CHECK}
23360 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23361 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23362 addition that it prints @samp{checking for @var{echo-text}} to the
23363 standard output first, if @var{echo-text} is non-empty. Use
23364 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23365 messages (@pxref{Printing Messages}).
23370 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23373 @defmac AC_CROSS_CHECK
23374 @acindex{CROSS_CHECK}
23375 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23382 Check for the Cygwin environment in which case the shell variable
23383 @code{CYGWIN} is set to @samp{yes}. Don't use this macro, the dignified
23384 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23385 (@pxref{Canonicalizing}). As a matter of fact this macro is defined as:
23388 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23390 *cygwin* ) CYGWIN=yes;;
23395 Beware that the variable @env{CYGWIN} has a special meaning when
23396 running Cygwin, and should not be changed. That's yet another reason
23397 not to use this macro.
23400 @defmac AC_DECL_SYS_SIGLIST
23401 @acindex{DECL_SYS_SIGLIST}
23402 @cvindex SYS_SIGLIST_DECLARED
23406 AC_CHECK_DECLS([sys_siglist], [], [],
23407 [#include <signal.h>
23408 /* NetBSD declares sys_siglist in unistd.h. */
23409 #ifdef HAVE_UNISTD_H
23410 # include <unistd.h>
23416 @xref{AC_CHECK_DECLS}.
23419 @defmac AC_DECL_YYTEXT
23420 @acindex{DECL_YYTEXT}
23421 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23424 @defmac AC_DIAGNOSE (@var{category}, @var{message})
23426 Replaced by @code{m4_warn} (@pxref{m4_warn}).
23429 @defmac AC_DIR_HEADER
23430 @acindex{DIR_HEADER}
23435 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23436 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23437 (@pxref{AC_HEADER_DIRENT}),
23438 but defines a different set of C preprocessor macros to indicate which
23439 header file is found:
23441 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23442 @item Header @tab Old Symbol @tab New Symbol
23443 @item @file{dirent.h} @tab @code{DIRENT} @tab @code{HAVE_DIRENT_H}
23444 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23445 @item @file{sys/dir.h} @tab @code{SYSDIR} @tab @code{HAVE_SYS_DIR_H}
23446 @item @file{ndir.h} @tab @code{NDIR} @tab @code{HAVE_NDIR_H}
23450 @defmac AC_DYNIX_SEQ
23451 @acindex{DYNIX_SEQ}
23452 If on DYNIX/ptx, add @option{-lseq} to output variable
23453 @code{LIBS}. This macro used to be defined as
23456 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23460 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23466 Defined the output variable @code{EXEEXT} based on the output of the
23467 compiler, which is now done automatically. Typically set to empty
23468 string if POSIX and @samp{.exe} if a DOS variant.
23473 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23474 and sets @code{EMXOS2}. Don't use this macro, the dignified means to
23475 check the nature of the host is using @code{AC_CANONICAL_HOST}
23476 (@pxref{Canonicalizing}).
23479 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23480 @ovar{action-if-not-given})
23482 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23483 support providing a help string (@pxref{AC_ARG_ENABLE}).
23488 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23491 @defmac AC_FATAL (@var{message})
23493 Replaced by @code{m4_fatal} (@pxref{m4_fatal}).
23498 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23501 @defmac AC_FIND_XTRA
23502 @acindex{FIND_XTRA}
23503 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23508 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23511 @defmac AC_FUNC_CHECK
23512 @acindex{FUNC_CHECK}
23513 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23516 @anchor{AC_FUNC_SETVBUF_REVERSED}
23517 @defmac AC_FUNC_SETVBUF_REVERSED
23518 @acindex{FUNC_SETVBUF_REVERSED}
23519 @cvindex SETVBUF_REVERSED
23520 @c @fuindex setvbuf
23521 @prindex @code{setvbuf}
23522 Do nothing. Formerly, this macro checked whether @code{setvbuf} takes
23523 the buffering type as its second argument and the buffer pointer as the
23524 third, instead of the other way around, and defined
23525 @code{SETVBUF_REVERSED}. However, the last systems to have the problem
23526 were those based on SVR2, which became obsolete in 1987, and the macro
23527 is no longer needed.
23530 @defmac AC_FUNC_WAIT3
23531 @acindex{FUNC_WAIT3}
23532 @cvindex HAVE_WAIT3
23534 @prindex @code{wait3}
23535 If @code{wait3} is found and fills in the contents of its third argument
23536 (a @samp{struct rusage *}), which HP-UX does not do, define
23539 These days portable programs should use @code{waitpid}, not
23540 @code{wait3}, as @code{wait3} has been removed from POSIX.
23543 @defmac AC_GCC_TRADITIONAL
23544 @acindex{GCC_TRADITIONAL}
23545 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}),
23546 which is itself obsolete.
23549 @defmac AC_GETGROUPS_T
23550 @acindex{GETGROUPS_T}
23551 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23554 @defmac AC_GETLOADAVG
23555 @acindex{GETLOADAVG}
23556 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23559 @defmac AC_GNU_SOURCE
23560 @acindex{GNU_SOURCE}
23561 @cvindex _GNU_SOURCE
23562 This macro is a platform-specific subset of
23563 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23566 @defmac AC_HAVE_FUNCS
23567 @acindex{HAVE_FUNCS}
23568 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23571 @defmac AC_HAVE_HEADERS
23572 @acindex{HAVE_HEADERS}
23573 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23576 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23577 @ovar{action-if-not-found}, @ovar{other-libraries})
23578 @acindex{HAVE_LIBRARY}
23579 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23580 @var{function} argument of @code{main}. In addition, @var{library} can
23581 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}. In
23582 all of those cases, the compiler is passed @option{-lfoo}. However,
23583 @var{library} cannot be a shell variable; it must be a literal name.
23584 @xref{AC_CHECK_LIB}.
23587 @defmac AC_HAVE_POUNDBANG
23588 @acindex{HAVE_POUNDBANG}
23589 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23592 @defmac AC_HEADER_CHECK
23593 @acindex{HEADER_CHECK}
23594 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23597 @defmac AC_HEADER_EGREP
23598 @acindex{HEADER_EGREP}
23599 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23602 @anchor{AC_HEADER_TIME}
23603 @defmac AC_HEADER_TIME
23604 @acindex{HEADER_TIME}
23605 @cvindex TIME_WITH_SYS_TIME
23607 @hdrindex{sys/time.h}
23608 @caindex header_time
23609 This macro used to check whether it was possible to include
23610 @file{time.h} and @file{sys/time.h} in the same source file,
23611 defining @code{TIME_WITH_SYS_TIME} if so.
23613 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23614 although it does still define @code{TIME_WITH_SYS_TIME} for
23615 compatibility's sake. @file{time.h} is universally present, and the
23616 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23620 @defmac AC_HELP_STRING
23621 @acindex{HELP_STRING}
23622 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23625 @defmac AC_INIT (@var{unique-file-in-source-dir})
23627 Formerly @code{AC_INIT} used to have a single argument, and was
23632 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23634 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23639 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23642 @defmac AC_INT_16_BITS
23643 @acindex{INT_16_BITS}
23644 @cvindex INT_16_BITS
23645 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23646 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23649 @defmac AC_IRIX_SUN
23651 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23652 @code{LIBS}. If you were using it to get @code{getmntent}, use
23653 @code{AC_FUNC_GETMNTENT} instead. If you used it for the NIS versions
23654 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23655 getpwnam)}. Up to Autoconf 2.13, it used to be
23658 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23662 now it is defined as
23666 AC_CHECK_LIB([sun], [getpwnam])
23670 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23673 @defmac AC_ISC_POSIX
23674 @acindex{ISC_POSIX}
23676 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23677 necessary for POSIX facilities. Sun dropped support for the obsolete
23678 INTERACTIVE Systems Corporation Unix on 2006-07-23. New programs
23679 need not use this macro. It is implemented as
23680 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23685 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23688 @defmac AC_LANG_CPLUSPLUS
23689 @acindex{LANG_CPLUSPLUS}
23690 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23693 @defmac AC_LANG_FORTRAN77
23694 @acindex{LANG_FORTRAN77}
23695 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23698 @defmac AC_LANG_RESTORE
23699 @acindex{LANG_RESTORE}
23700 Select the @var{language} that is saved on the top of the stack, as set
23701 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23702 @code{AC_LANG(@var{language})}. @xref{Language Choice}, for the
23703 preferred way to change languages.
23706 @defmac AC_LANG_SAVE
23707 @acindex{LANG_SAVE}
23708 Remember the current language (as set by @code{AC_LANG}) on a stack.
23709 The current language does not change. @code{AC_LANG_PUSH} is preferred
23710 (@pxref{AC_LANG_PUSH}).
23713 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23714 @acindex{LINK_FILES}
23715 This is an obsolete version of @code{AC_CONFIG_LINKS}
23716 (@pxref{AC_CONFIG_LINKS}. An updated version of:
23719 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23727 AC_CONFIG_LINKS([host.h:config/$machine.h
23728 object.h:config/$obj_format.h])
23734 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23737 @defmac AC_LONG_64_BITS
23738 @acindex{LONG_64_BITS}
23739 @cvindex LONG_64_BITS
23740 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23741 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23742 (@pxref{AC_CHECK_SIZEOF}).
23745 @defmac AC_LONG_DOUBLE
23746 @acindex{LONG_DOUBLE}
23747 If the C compiler supports a working @code{long double} type with more
23748 range or precision than the @code{double} type, define
23749 @code{HAVE_LONG_DOUBLE}.
23751 You should use @code{AC_TYPE_LONG_DOUBLE} or
23752 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23755 @defmac AC_LONG_FILE_NAMES
23756 @acindex{LONG_FILE_NAMES}
23759 AC_SYS_LONG_FILE_NAMES
23762 @xref{AC_SYS_LONG_FILE_NAMES}.
23765 @defmac AC_MAJOR_HEADER
23766 @acindex{MAJOR_HEADER}
23767 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23770 @defmac AC_MEMORY_H
23772 @cvindex NEED_MEMORY_H
23773 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23774 defined in @file{memory.h}. Today it is equivalent to
23775 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}). Adjust
23776 your code to get the @code{mem} functions from @file{string.h} instead.
23781 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23782 environment and sets @code{MINGW32}. Don't use this macro, the
23783 dignified means to check the nature of the host is using
23784 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23790 @cvindex _POSIX_SOURCE
23791 @cvindex _POSIX_1_SOURCE
23792 This macro is a platform-specific subset of
23793 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23796 @defmac AC_MINUS_C_MINUS_O
23797 @acindex{MINUS_C_MINUS_O}
23798 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23803 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23808 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23814 Defined the output variable @code{OBJEXT} based on the output of the
23815 compiler, after .c files have been excluded. Typically set to @samp{o}
23816 if POSIX, @samp{obj} if a DOS variant.
23817 Now the compiler checking macros handle
23818 this automatically.
23821 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23823 Make M4 print a message to the standard error output warning that
23824 @var{this-macro-name} is obsolete, and giving the file and line number
23825 where it was called. @var{this-macro-name} should be the name of the
23826 macro that is calling @code{AC_OBSOLETE}. If @var{suggestion} is given,
23827 it is printed at the end of the warning message; for example, it can be
23828 a suggestion for what to use instead of @var{this-macro-name}.
23833 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23837 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23838 services to the user (@pxref{AU_DEFUN}).
23843 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23846 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23848 The use of @code{AC_OUTPUT} with arguments is deprecated. This obsoleted
23849 interface is equivalent to:
23853 AC_CONFIG_FILES(@var{file}@dots{})
23854 AC_CONFIG_COMMANDS([default],
23855 @var{extra-cmds}, @var{init-cmds})
23861 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23864 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23865 @acindex{OUTPUT_COMMANDS}
23866 Specify additional shell commands to run at the end of
23867 @file{config.status}, and shell commands to initialize any variables
23868 from @command{configure}. This macro may be called multiple times. It is
23869 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23871 Here is an unrealistic example:
23875 AC_OUTPUT_COMMANDS(
23876 [AS_ECHO(["this is extra $fubar, and so on."])],
23878 AC_OUTPUT_COMMANDS(
23879 [AS_ECHO(["this is another, extra, bit"])],
23880 [AS_ECHO(["init bit"])])
23883 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23884 additional key, an important difference is that
23885 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23886 @code{AC_CONFIG_COMMANDS}. This means that @code{AC_CONFIG_COMMANDS}
23887 can safely be given macro calls as arguments:
23890 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23894 Conversely, where one level of quoting was enough for literal strings
23895 with @code{AC_OUTPUT_COMMANDS}, you need two with
23896 @code{AC_CONFIG_COMMANDS}. The following lines are equivalent:
23900 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23901 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23908 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23913 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23916 @defmac AC_PROG_CC_C89
23917 @acindex{PROG_CC_C89}
23918 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23921 @defmac AC_PROG_CC_C99
23922 @acindex{PROG_CC_C99}
23923 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23926 @defmac AC_PROG_CC_STDC
23927 @acindex{PROG_CC_STDC}
23928 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23931 @anchor{AC_PROG_GCC_TRADITIONAL}
23932 @defmac AC_PROG_GCC_TRADITIONAL
23933 @acindex{PROG_GCC_TRADITIONAL}
23934 Used to put GCC into ``traditional'' (pre-ISO C) compilation mode,
23935 on systems with headers that did not work correctly with a
23936 standard-compliant compiler. GCC has not supported traditional
23937 compilation in many years, and all of the systems that required this are
23938 long obsolete themselves. This macro is now a compatibility synonym for
23939 @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23943 @defmac AC_PROGRAMS_CHECK
23944 @acindex{PROGRAMS_CHECK}
23945 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23948 @defmac AC_PROGRAMS_PATH
23949 @acindex{PROGRAMS_PATH}
23950 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23953 @defmac AC_PROGRAM_CHECK
23954 @acindex{PROGRAM_CHECK}
23955 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23958 @defmac AC_PROGRAM_EGREP
23959 @acindex{PROGRAM_EGREP}
23960 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23963 @defmac AC_PROGRAM_PATH
23964 @acindex{PROGRAM_PATH}
23965 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23968 @defmac AC_REMOTE_TAPE
23969 @acindex{REMOTE_TAPE}
23970 Removed because of limited usefulness.
23973 @defmac AC_RESTARTABLE_SYSCALLS
23974 @acindex{RESTARTABLE_SYSCALLS}
23975 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}. However,
23976 these days portable programs should use @code{sigaction} with
23977 @code{SA_RESTART} if they want restartable system calls. They should
23978 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23979 system call is restartable is a dynamic issue, not a configuration-time
23983 @defmac AC_RETSIGTYPE
23984 @acindex{RETSIGTYPE}
23985 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23991 Removed because of limited usefulness.
23994 @defmac AC_SCO_INTL
23997 Equivalent to the obsolescent macro @code{AC_FUNC_STRFTIME}.
23998 @xref{AC_FUNC_STRFTIME}.
24001 @defmac AC_SETVBUF_REVERSED
24002 @acindex{SETVBUF_REVERSED}
24005 AC_FUNC_SETVBUF_REVERSED
24008 @xref{AC_FUNC_SETVBUF_REVERSED}.
24011 @defmac AC_SET_MAKE
24013 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
24016 @defmac AC_SIZEOF_TYPE
24017 @acindex{SIZEOF_TYPE}
24018 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
24023 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
24026 @defmac AC_STAT_MACROS_BROKEN
24027 @acindex{STAT_MACROS_BROKEN}
24028 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
24031 @defmac AC_STDC_HEADERS
24032 @acindex{STDC_HEADERS}
24033 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
24034 is itself obsolete. Nowadays it is safe to assume the facilities of C89
24040 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
24043 @defmac AC_STRUCT_ST_BLKSIZE
24044 @acindex{STRUCT_ST_BLKSIZE}
24045 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
24046 @cvindex HAVE_ST_BLKSIZE
24047 If @code{struct stat} contains an @code{st_blksize} member, define
24048 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}. The former name,
24049 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
24050 the future. This macro is obsoleted, and should be replaced by
24053 AC_CHECK_MEMBERS([struct stat.st_blksize])
24056 @xref{AC_CHECK_MEMBERS}.
24059 @defmac AC_STRUCT_ST_RDEV
24060 @acindex{STRUCT_ST_RDEV}
24061 @cvindex HAVE_ST_RDEV
24062 @cvindex HAVE_STRUCT_STAT_ST_RDEV
24063 If @code{struct stat} contains an @code{st_rdev} member, define
24064 @code{HAVE_STRUCT_STAT_ST_RDEV}. The former name for this macro,
24065 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24066 in the future. Actually, even the new macro is obsolete and should be
24069 AC_CHECK_MEMBERS([struct stat.st_rdev])
24072 @xref{AC_CHECK_MEMBERS}.
24075 @defmac AC_ST_BLKSIZE
24076 @acindex{ST_BLKSIZE}
24077 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24080 @defmac AC_ST_BLOCKS
24081 @acindex{ST_BLOCKS}
24082 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24087 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24090 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24091 @acindex{SYS_RESTARTABLE_SYSCALLS}
24092 @cvindex HAVE_RESTARTABLE_SYSCALLS
24093 If the system automatically restarts a system call that is interrupted
24094 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}. This macro does
24095 not check whether system calls are restarted in general---it checks whether a
24096 signal handler installed with @code{signal} (but not @code{sigaction})
24097 causes system calls to be restarted. It does not check whether system calls
24098 can be restarted when interrupted by signals that have no handler.
24100 These days portable programs should use @code{sigaction} with
24101 @code{SA_RESTART} if they want restartable system calls. They should
24102 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24103 system call is restartable is a dynamic issue, not a configuration-time
24107 @defmac AC_SYS_SIGLIST_DECLARED
24108 @acindex{SYS_SIGLIST_DECLARED}
24109 This macro was renamed @code{AC_DECL_SYS_SIGLIST}. However, even that
24110 name is obsolete, as the same functionality is now achieved via
24111 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24114 @defmac AC_TEST_CPP
24116 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24117 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24120 @defmac AC_TEST_PROGRAM
24121 @acindex{TEST_PROGRAM}
24122 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24123 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24126 @defmac AC_TIMEZONE
24128 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24131 @defmac AC_TIME_WITH_SYS_TIME
24132 @acindex{TIME_WITH_SYS_TIME}
24133 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24134 itself obsolete; nowadays one need only do
24135 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24138 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24139 @ovar{action-if-true}, @ovar{action-if-false})
24140 @acindex{TRY_COMPILE}
24145 [AC_LANG_PROGRAM([[@var{includes}]],
24146 [[@var{function-body}]])],
24147 [@var{action-if-true}],
24148 [@var{action-if-false}])
24152 @xref{Running the Compiler}.
24154 This macro double quotes both @var{includes} and @var{function-body}.
24156 For C and C++, @var{includes} is any @code{#include} statements needed
24157 by the code in @var{function-body} (@var{includes} is ignored if
24158 the currently selected language is Fortran or Fortran 77). The compiler
24159 and compilation flags are determined by the current language
24160 (@pxref{Language Choice}).
24163 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24169 [AC_LANG_SOURCE([[@var{input}]])],
24170 [@var{action-if-true}],
24171 [@var{action-if-false}])
24175 @xref{Running the Preprocessor}.
24177 This macro double quotes the @var{input}.
24180 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24181 @ovar{action-if-true}, @ovar{action-if-false})
24187 [AC_LANG_PROGRAM([[@var{includes}]],
24188 [[@var{function-body}]])],
24189 [@var{action-if-true}],
24190 [@var{action-if-false}])
24194 @xref{Running the Linker}.
24196 This macro double quotes both @var{includes} and @var{function-body}.
24198 Depending on the current language (@pxref{Language Choice}), create a
24199 test program to see whether a function whose body consists of
24200 @var{function-body} can be compiled and linked. If the file compiles
24201 and links successfully, run shell commands @var{action-if-found},
24202 otherwise run @var{action-if-not-found}.
24204 This macro double quotes both @var{includes} and @var{function-body}.
24206 For C and C++, @var{includes} is any @code{#include} statements needed
24207 by the code in @var{function-body} (@var{includes} is ignored if
24208 the currently selected language is Fortran or Fortran 77). The compiler
24209 and compilation flags are determined by the current language
24210 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24211 @code{LIBS} are used for linking.
24214 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24215 @ovar{action-if-not-found})
24216 @acindex{TRY_LINK_FUNC}
24217 This macro is equivalent to
24219 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24220 [@var{action-if-found}], [@var{action-if-not-found}])
24223 @xref{Running the Linker}.
24226 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24227 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24233 [AC_LANG_SOURCE([[@var{program}]])],
24234 [@var{action-if-true}],
24235 [@var{action-if-false}],
24236 [@var{action-if-cross-compiling}])
24243 @anchor{AC_TYPE_SIGNAL}
24244 @defmac AC_TYPE_SIGNAL
24245 @acindex{TYPE_SIGNAL}
24246 @cvindex RETSIGTYPE
24247 @hdrindex{signal.h}
24248 If @file{signal.h} declares @code{signal} as returning a pointer to a
24249 function returning @code{void}, define @code{RETSIGTYPE} to be
24250 @code{void}; otherwise, define it to be @code{int}. These days, it is
24251 portable to assume C89, and that signal handlers return @code{void},
24252 without needing to use this macro or @code{RETSIGTYPE}.
24257 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24260 @defmac AC_UNISTD_H
24262 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24263 which is one of the tests done as a side effect by
24264 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24265 unnecessary to write explicitly.
24271 Define @code{USG} if the BSD string functions (@code{bcopy},
24272 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24273 in @file{strings.h}. Modern code should assume @file{string.h} exists
24274 and should use the standard C string functions (@code{memmove}, @code{memset},
24275 @code{strchr}, @code{strrchr}, etc) unconditionally.
24277 @file{strings.h} may be the only header that declares @code{strcasecmp},
24278 @code{strncasecmp}, and @code{ffs}. @code{AC_INCLUDES_DEFAULT} checks
24279 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24282 @defmac AC_UTIME_NULL
24283 @acindex{UTIME_NULL}
24284 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24287 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24288 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24289 If the cache file is inconsistent with the current host, target and
24290 build system types, it used to execute @var{cmd} or print a default
24291 error message. This is now handled by default.
24294 @defmac AC_VERBOSE (@var{result-description})
24296 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24301 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24306 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24311 This macro was renamed @code{AC_FUNC_WAIT3}. However, these days
24312 portable programs should use @code{waitpid}, not @code{wait3}, as
24313 @code{wait3} has been removed from POSIX.
24318 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24321 @defmac AC_WARNING (@var{message})
24323 Replaced by @code{m4_warn} (@pxref{m4_warn}).
24326 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24327 @ovar{action-if-not-given})
24329 This is an obsolete version of @code{AC_ARG_WITH} that does not
24330 support providing a help string (@pxref{AC_ARG_WITH}).
24333 @defmac AC_WORDS_BIGENDIAN
24334 @acindex{WORDS_BIGENDIAN}
24335 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24338 @defmac AC_XENIX_DIR
24339 @acindex{XENIX_DIR}
24341 This macro is equivalent to the obsolescent @code{AC_HEADER_DIRENT}
24342 macro, plus it also sets the shell variable @code{XENIX}.
24343 Don't use this macro, the dignified means to check the nature of the
24344 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24347 @defmac AC_YYTEXT_POINTER
24348 @acindex{YYTEXT_POINTER}
24349 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24350 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24354 @section Upgrading From Version 1
24355 @cindex Upgrading autoconf
24356 @cindex Autoconf upgrading
24358 Autoconf version 2 is mostly backward compatible with version 1.
24359 However, it introduces better ways to do some things, and doesn't
24360 support some of the ugly things in version 1. So, depending on how
24361 sophisticated your @file{configure.ac} files are, you might have to do
24362 some manual work in order to upgrade to version 2. This chapter points
24363 out some problems to watch for when upgrading. Also, perhaps your
24364 @command{configure} scripts could benefit from some of the new features in
24365 version 2; the changes are summarized in the file @file{NEWS} in the
24366 Autoconf distribution.
24369 * Changed File Names:: Files you might rename
24370 * Changed Makefiles:: New things to put in @file{Makefile.in}
24371 * Changed Macros:: Macro calls you might replace
24372 * Changed Results:: Changes in how to check test results
24373 * Changed Macro Writing:: Better ways to write your own macros
24376 @node Changed File Names
24377 @subsection Changed File Names
24379 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24380 in a particular package's source directory), you must rename it to
24381 @file{acsite.m4}. @xref{autoconf Invocation}.
24383 If you distribute @file{install.sh} with your package, rename it to
24384 @file{install-sh} so @command{make} builtin rules don't inadvertently
24385 create a file called @file{install} from it. @code{AC_PROG_INSTALL}
24386 looks for the script under both names, but it is best to use the new name.
24388 If you were using @file{config.h.top}, @file{config.h.bot}, or
24389 @file{acconfig.h}, you still can, but you have less clutter if you
24390 use the @code{AH_} macros. @xref{Autoheader Macros}.
24392 @node Changed Makefiles
24393 @subsection Changed Makefiles
24395 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24396 your @file{Makefile.in} files, so they can take advantage of the values
24397 of those variables in the environment when @command{configure} is run.
24398 Doing this isn't necessary, but it's a convenience for users.
24400 Also add @samp{@@configure_input@@} in a comment to each input file for
24401 @code{AC_OUTPUT}, so that the output files contain a comment saying
24402 they were produced by @command{configure}. Automatically selecting the
24403 right comment syntax for all the kinds of files that people call
24404 @code{AC_OUTPUT} on became too much work.
24406 Add @file{config.log} and @file{config.cache} to the list of files you
24407 remove in @code{distclean} targets.
24409 If you have the following in @file{Makefile.in}:
24412 prefix = /usr/local
24413 exec_prefix = $(prefix)
24417 you must change it to:
24420 prefix = @@prefix@@
24421 exec_prefix = @@exec_prefix@@
24425 The old behavior of replacing those variables without @samp{@@}
24426 characters around them has been removed.
24428 @node Changed Macros
24429 @subsection Changed Macros
24431 Many of the macros were renamed in Autoconf version 2. You can still
24432 use the old names, but the new ones are clearer, and it's easier to find
24433 the documentation for them. @xref{Obsolete Macros}, for a table showing the
24434 new names for the old macros. Use the @command{autoupdate} program to
24435 convert your @file{configure.ac} to using the new macro names.
24436 @xref{autoupdate Invocation}.
24438 Some macros have been superseded by similar ones that do the job better,
24439 but are not call-compatible. If you get warnings about calling obsolete
24440 macros while running @command{autoconf}, you may safely ignore them, but
24441 your @command{configure} script generally works better if you follow
24442 the advice that is printed about what to replace the obsolete macros with. In
24443 particular, the mechanism for reporting the results of tests has
24444 changed. If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24445 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24446 looks better if you switch to @code{AC_MSG_CHECKING} and
24447 @code{AC_MSG_RESULT}. @xref{Printing Messages}. Those macros work best
24448 in conjunction with cache variables. @xref{Caching Results}.
24452 @node Changed Results
24453 @subsection Changed Results
24455 If you were checking the results of previous tests by examining the
24456 shell variable @code{DEFS}, you need to switch to checking the values of
24457 the cache variables for those tests. @code{DEFS} no longer exists while
24458 @command{configure} is running; it is only created when generating output
24459 files. This difference from version 1 is because properly quoting the
24460 contents of that variable turned out to be too cumbersome and
24461 inefficient to do every time @code{AC_DEFINE} is called. @xref{Cache
24464 For example, here is a @file{configure.ac} fragment written for Autoconf
24468 AC_HAVE_FUNCS(syslog)
24470 *-DHAVE_SYSLOG*) ;;
24471 *) # syslog is not in the default libraries. See if it's in some other.
24473 for lib in bsd socket inet; do
24474 AC_CHECKING(for syslog in -l$lib)
24475 LIBS="-l$lib $saved_LIBS"
24476 AC_HAVE_FUNCS(syslog)
24478 *-DHAVE_SYSLOG*) break ;;
24486 Here is a way to write it for version 2:
24489 AC_CHECK_FUNCS([syslog])
24490 AS_IF([test "x$ac_cv_func_syslog" = xno],
24491 [# syslog is not in the default libraries. See if it's in some other.
24492 for lib in bsd socket inet; do
24493 AC_CHECK_LIB([$lib], [syslog],
24494 [AC_DEFINE([HAVE_SYSLOG])
24495 LIBS="-l$lib $LIBS"; break])
24499 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24500 backslashes before quotes, you need to remove them. It now works
24501 predictably, and does not treat quotes (except back quotes) specially.
24502 @xref{Setting Output Variables}.
24504 All of the Boolean shell variables set by Autoconf macros now use
24505 @samp{yes} for the true value. Most of them use @samp{no} for false,
24506 though for backward compatibility some use the empty string instead. If
24507 you were relying on a shell variable being set to something like 1 or
24508 @samp{t} for true, you need to change your tests.
24510 @node Changed Macro Writing
24511 @subsection Changed Macro Writing
24513 When defining your own macros, you should now use @code{AC_DEFUN}
24514 instead of @code{define}. @code{AC_DEFUN} automatically calls
24515 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24516 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24517 messages on the screen. There's no actual harm in continuing to use the
24518 older way, but it's less convenient and attractive. @xref{Macro
24521 You probably looked at the macros that came with Autoconf as a guide for
24522 how to do things. It would be a good idea to take a look at the new
24523 versions of them, as the style is somewhat improved and they take
24524 advantage of some new features.
24526 If you were doing tricky things with undocumented Autoconf internals
24527 (macros, variables, diversions), check whether you need to change
24528 anything to account for changes that have been made. Perhaps you can
24529 even use an officially supported technique in version 2 instead of
24530 kludging. Or perhaps not.
24532 To speed up your locally written feature tests, add caching to them.
24533 See whether any of your tests are of general enough usefulness to
24534 encapsulate them into macros that you can share.
24537 @node Autoconf 2.13
24538 @section Upgrading From Version 2.13
24539 @cindex Upgrading autoconf
24540 @cindex Autoconf upgrading
24542 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24543 suits this section@enddots{}
24546 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24547 However, it introduces better ways to do some things, and doesn't
24548 support some of the ugly things in version 2.13. So, depending on how
24549 sophisticated your @file{configure.ac} files are, you might have to do
24550 some manual work in order to upgrade to version 2.50. This chapter
24551 points out some problems to watch for when upgrading. Also, perhaps
24552 your @command{configure} scripts could benefit from some of the new
24553 features in version 2.50; the changes are summarized in the file
24554 @file{NEWS} in the Autoconf distribution.
24558 * Changed Quotation:: Broken code which used to work
24559 * New Macros:: Interaction with foreign macros
24560 * Hosts and Cross-Compilation:: Bugward compatibility kludges
24561 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
24562 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
24565 @node Changed Quotation
24566 @subsection Changed Quotation
24568 The most important changes are invisible to you: the implementation of
24569 most macros have completely changed. This allowed more factorization of
24570 the code, better error messages, a higher uniformity of the user's
24571 interface etc. Unfortunately, as a side effect, some construct which
24572 used to (miraculously) work might break starting with Autoconf 2.50.
24573 The most common culprit is bad quotation.
24575 For instance, in the following example, the message is not properly
24580 AC_CHECK_HEADERS(foo.h, ,
24581 AC_MSG_ERROR(cannot find foo.h, bailing out))
24586 Autoconf 2.13 simply ignores it:
24589 $ @kbd{autoconf-2.13; ./configure --silent}
24590 creating cache ./config.cache
24591 configure: error: cannot find foo.h
24596 while Autoconf 2.50 produces a broken @file{configure}:
24599 $ @kbd{autoconf-2.50; ./configure --silent}
24600 configure: error: cannot find foo.h
24601 ./configure: exit: bad non-numeric arg `bailing'
24602 ./configure: exit: bad non-numeric arg `bailing'
24606 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24610 AC_INIT([Example], [1.0], [bug-example@@example.org])
24611 AC_CHECK_HEADERS([foo.h], [],
24612 [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24616 Many many (and many more) Autoconf macros were lacking proper quotation,
24617 including no less than@dots{} @code{AC_DEFUN} itself!
24620 $ @kbd{cat configure.in}
24621 AC_DEFUN([AC_PROG_INSTALL],
24622 [# My own much better version
24627 $ @kbd{autoconf-2.13}
24628 autoconf: Undefined macros:
24629 ***BUG in Autoconf--please report*** AC_FD_MSG
24630 ***BUG in Autoconf--please report*** AC_EPI
24631 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24632 configure.in:5:AC_PROG_INSTALL
24633 $ @kbd{autoconf-2.50}
24639 @subsection New Macros
24641 @cindex undefined macro
24642 @cindex @code{_m4_divert_diversion}
24644 While Autoconf was relatively dormant in the late 1990s, Automake
24645 provided Autoconf-like macros for a while. Starting with Autoconf 2.50
24646 in 2001, Autoconf provided
24647 versions of these macros, integrated in the @code{AC_} namespace,
24648 instead of @code{AM_}. But in order to ease the upgrading via
24649 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24651 Unfortunately older versions of Automake (e.g., Automake 1.4)
24652 did not quote the names of these macros.
24653 Therefore, when @command{m4} finds something like
24654 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24655 @code{AM_TYPE_PTRDIFF_T} is
24656 expanded, replaced with its Autoconf definition.
24658 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24659 complains, in its own words:
24662 $ @kbd{cat configure.ac}
24663 AC_INIT([Example], [1.0], [bug-example@@example.org])
24665 $ @kbd{aclocal-1.4}
24667 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24668 aclocal.m4:17: the top level
24669 autom4te: m4 failed with exit status: 1
24673 Modern versions of Automake no longer define most of these
24674 macros, and properly quote the names of the remaining macros.
24675 If you must use an old Automake, do not depend upon macros from Automake
24676 as it is simply not its job
24677 to provide macros (but the one it requires itself):
24680 $ @kbd{cat configure.ac}
24681 AC_INIT([Example], [1.0], [bug-example@@example.org])
24683 $ @kbd{rm aclocal.m4}
24685 autoupdate: 'configure.ac' is updated
24686 $ @kbd{cat configure.ac}
24687 AC_INIT([Example], [1.0], [bug-example@@example.org])
24688 AC_CHECK_TYPES([ptrdiff_t])
24689 $ @kbd{aclocal-1.4}
24695 @node Hosts and Cross-Compilation
24696 @subsection Hosts and Cross-Compilation
24697 @cindex Cross compilation
24699 Based on the experience of compiler writers, and after long public
24700 debates, many aspects of the cross-compilation chain have changed:
24704 the relationship between the build, host, and target architecture types,
24707 the command line interface for specifying them to @command{configure},
24710 the variables defined in @command{configure},
24713 the enabling of cross-compilation mode.
24718 The relationship between build, host, and target have been cleaned up:
24719 the chain of default is now simply: target defaults to host, host to
24720 build, and build to the result of @command{config.guess}. Nevertheless,
24721 in order to ease the transition from 2.13 to 2.50, the following
24722 transition scheme is implemented. @emph{Do not rely on it}, as it will
24723 be completely disabled in a couple of releases (we cannot keep it, as it
24724 proves to cause more problems than it cures).
24726 They all default to the result of running @command{config.guess}, unless
24727 you specify either @option{--build} or @option{--host}. In this case,
24728 the default becomes the system type you specified. If you specify both,
24729 and they're different, @command{configure} enters cross compilation
24730 mode, so it doesn't run any tests that require execution.
24732 Hint: if you mean to override the result of @command{config.guess},
24733 prefer @option{--build} over @option{--host}.
24737 For backward compatibility, @command{configure} accepts a system
24738 type as an option by itself. Such an option overrides the
24739 defaults for build, host, and target system types. The following
24740 configure statement configures a cross toolchain that runs on
24741 NetBSD/aarch64 but generates code for GNU Hurd/riscv64,
24742 which is also the build platform.
24745 ./configure --host=aarch64-netbsd riscv64-gnu
24750 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24751 and @code{target} had a different semantics before and after the
24752 invocation of @code{AC_CANONICAL_BUILD} etc. Now, the argument of
24753 @option{--build} is strictly copied into @code{build_alias}, and is left
24754 empty otherwise. After the @code{AC_CANONICAL_BUILD}, @code{build} is
24755 set to the canonicalized build type. To ease the transition, before,
24756 its contents is the same as that of @code{build_alias}. Do @emph{not}
24757 rely on this broken feature.
24759 For consistency with the backward compatibility scheme exposed above,
24760 when @option{--host} is specified but @option{--build} isn't, the build
24761 system is assumed to be the same as @option{--host}, and
24762 @samp{build_alias} is set to that value. Eventually, this
24763 historically incorrect behavior will go away.
24767 The former scheme to enable cross-compilation proved to cause more harm
24768 than good, in particular, it used to be triggered too easily, leaving
24769 regular end users puzzled in front of cryptic error messages.
24770 @command{configure} could even enter cross-compilation mode only
24771 because the compiler was not functional. This is mainly because
24772 @command{configure} used to try to detect cross-compilation, instead of
24773 waiting for an explicit flag from the user.
24775 Now, @command{configure} enters cross-compilation mode if and only if
24776 @option{--host} is passed.
24778 That's the short documentation. To ease the transition between 2.13 and
24779 its successors, a more complicated scheme is implemented. @emph{Do not
24780 rely on the following}, as it will be removed in the near future.
24782 If you specify @option{--host}, but not @option{--build}, when
24783 @command{configure} performs the first compiler test it tries to run
24784 an executable produced by the compiler. If the execution fails, it
24785 enters cross-compilation mode. This is fragile. Moreover, by the time
24786 the compiler test is performed, it may be too late to modify the
24787 build-system type: other tests may have already been performed.
24788 Therefore, whenever you specify @option{--host}, be sure to specify
24789 @option{--build} too.
24792 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
24796 enters cross-compilation mode. The former interface, which
24797 consisted in setting the compiler to a cross-compiler without informing
24798 @command{configure} is obsolete. For instance, @command{configure}
24799 fails if it can't run the code generated by the specified compiler if you
24800 configure as follows:
24803 ./configure CC=x86_64-w64-mingw64-gcc
24807 @node AC_LIBOBJ vs LIBOBJS
24808 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24810 Up to Autoconf 2.13, the replacement of functions was triggered via the
24811 variable @code{LIBOBJS}. Since Autoconf 2.50, the macro
24812 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24813 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24815 This change is mandated by the unification of the GNU Build System
24816 components. In particular, the various fragile techniques used to parse
24817 a @file{configure.ac} are all replaced with the use of traces. As a
24818 consequence, any action must be traceable, which obsoletes critical
24819 variable assignments. Fortunately, @code{LIBOBJS} was the only problem,
24820 and it can even be handled gracefully (read, ``without your having to
24821 change something'').
24823 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24824 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24828 As for function replacement, the fix is immediate: use
24829 @code{AC_LIBOBJ}. For instance:
24832 LIBOBJS="$LIBOBJS fnmatch.o"
24833 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24837 should be replaced with:
24840 AC_LIBOBJ([fnmatch])
24841 AC_LIBOBJ([malloc])
24847 When used with Automake 1.10 or newer, a suitable value for
24848 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24849 can be referenced from any @file{Makefile.am}. Even without Automake,
24850 arranging for @code{LIBOBJDIR} to be set correctly enables
24851 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24852 The @code{LIBOBJDIR} feature is experimental.
24855 @node AC_ACT_IFELSE vs AC_TRY_ACT
24856 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24857 @c the anchor keeps the old node name, to try to avoid breaking links
24858 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24860 @acindex{@var{ACT}_IFELSE}
24861 @acindex{TRY_@var{ACT}}
24862 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24863 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24864 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24865 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24866 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24867 @code{AC_TRY_RUN}. The motivations where:
24870 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24871 quoting their arguments;
24874 the combinatorial explosion is solved by decomposing on the one hand the
24875 generation of sources, and on the other hand executing the program;
24878 this scheme helps supporting more languages than plain C and C++.
24881 In addition to the change of syntax, the philosophy has changed too:
24882 while emphasis was put on speed at the expense of accuracy, today's
24883 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24887 As a perfect example of what is @emph{not} to be done, here is how to
24888 find out whether a header file contains a particular declaration, such
24889 as a typedef, a structure, a structure member, or a function. Use
24890 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24891 header file; on some systems the symbol might be defined in another
24892 header file that the file you are checking includes.
24894 As a (bad) example, here is how you should not check for C preprocessor
24895 symbols, either defined by header files or predefined by the C
24896 preprocessor: using @code{AC_EGREP_CPP}:
24904 ], is_aix=yes, is_aix=no)
24908 The above example, properly written would (i) use
24909 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24913 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24915 error: This isn't AIX!
24924 @c ============================= Generating Test Suites with Autotest
24926 @node Using Autotest
24927 @chapter Generating Test Suites with Autotest
24932 @strong{N.B.: This section describes a feature which is still
24933 stabilizing. Although we believe that Autotest is useful as-is, this
24934 documentation describes an interface which might change in the future:
24935 do not depend upon Autotest without subscribing to the Autoconf mailing
24939 It is paradoxical that portable projects depend on nonportable tools
24940 to run their test suite. Autoconf by itself is the paragon of this
24941 problem: although it aims at perfectly portability, up to 2.13 its
24942 test suite was using DejaGNU, a rich and complex testing
24943 framework, but which is far from being standard on POSIX systems.
24944 Worse yet, it was likely to be missing on the most fragile platforms,
24945 the very platforms that are most likely to torture Autoconf and
24946 exhibit deficiencies.
24948 To circumvent this problem, many package maintainers have developed their
24949 own testing framework, based on simple shell scripts whose sole outputs
24950 are exit status values describing whether the test succeeded. Most of
24951 these tests share common patterns, and this can result in lots of
24952 duplicated code and tedious maintenance.
24954 Following exactly the same reasoning that yielded to the inception of
24955 Autoconf, Autotest provides a test suite generation framework, based on
24956 M4 macros building a portable shell script. The suite itself is
24957 equipped with automatic logging and tracing facilities which greatly
24958 diminish the interaction with bug reporters, and simple timing reports.
24960 Autoconf itself has been using Autotest for years, and we do attest that
24961 it has considerably improved the strength of the test suite and the
24962 quality of bug reports. Other projects are known to use some generation
24963 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
24964 them with different needs, and this usage has validated Autotest as a general
24967 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24968 interactive tool testing, which is probably its main limitation.
24971 * Using an Autotest Test Suite:: Autotest and the user
24972 * Writing Testsuites:: Autotest macros
24973 * testsuite Invocation:: Running @command{testsuite} scripts
24974 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
24977 @node Using an Autotest Test Suite
24978 @section Using an Autotest Test Suite
24981 * testsuite Scripts:: The concepts of Autotest
24982 * Autotest Logs:: Their contents
24985 @node testsuite Scripts
24986 @subsection @command{testsuite} Scripts
24988 @cindex @command{testsuite}
24990 Generating testing or validation suites using Autotest is rather easy.
24991 The whole validation suite is held in a file to be processed through
24992 @command{autom4te}, itself using GNU M4 under the hood, to
24993 produce a stand-alone Bourne shell script which then gets distributed.
24994 Neither @command{autom4te} nor GNU M4 are needed at
24995 the installer's end.
24998 Each test of the validation suite should be part of some test group. A
24999 @dfn{test group} is a sequence of interwoven tests that ought to be
25000 executed together, usually because one test in the group creates data
25001 files that a later test in the same group needs to read. Complex test
25002 groups make later debugging more tedious. It is much better to
25003 keep only a few tests per test group. Ideally there is only one test
25006 For all but the simplest packages, some file such as @file{testsuite.at}
25007 does not fully hold all test sources, as these are often easier to
25008 maintain in separate files. Each of these separate files holds a single
25009 test group, or a sequence of test groups all addressing some common
25010 functionality in the package. In such cases, @file{testsuite.at}
25011 merely initializes the validation suite, and sometimes does elementary
25012 health checking, before listing include statements for all other test
25013 files. The special file @file{package.m4}, containing the
25014 identification of the package, is automatically included if found.
25016 A convenient alternative consists in moving all the global issues
25017 (local Autotest macros, elementary health checking, and @code{AT_INIT}
25018 invocation) into the file @code{local.at}, and making
25019 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
25020 suites. In such case, generating the whole test suite or pieces of it
25021 is only a matter of choosing the @command{autom4te} command line
25024 The validation scripts that Autotest produces are by convention called
25025 @command{testsuite}. When run, @command{testsuite} executes each test
25026 group in turn, producing only one summary line per test to say if that
25027 particular test succeeded or failed. At end of all tests, summarizing
25028 counters get printed. One debugging directory is left for each test
25029 group which failed, if any: such directories are named
25030 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
25031 the test group, and they include:
25034 @item a debugging script named @file{run} which reruns the test in
25035 @dfn{debug mode} (@pxref{testsuite Invocation}). The automatic generation
25036 of debugging scripts has the purpose of easing the chase for bugs.
25038 @item all the files created with @code{AT_DATA}
25040 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25042 @item a log of the run, named @file{testsuite.log}
25045 In the ideal situation, none of the tests fail, and consequently no
25046 debugging directory is left behind for validation.
25048 It often happens in practice that individual tests in the validation
25049 suite need to get information coming out of the configuration process.
25050 Some of this information, common for all validation suites, is provided
25051 through the file @file{atconfig}, automatically created by
25052 @code{AC_CONFIG_TESTDIR}. For configuration information which your
25053 testing environment specifically needs, you might prepare an optional
25054 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25055 The configuration process produces @file{atconfig} and @file{atlocal}
25056 out of these two input files, and these two produced files are
25057 automatically read by the @file{testsuite} script.
25059 Here is a diagram showing the relationship between files.
25062 Files used in preparing a software package for distribution:
25067 subfile-1.at ->. [local.at] ---->+
25069 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25075 Files used in configuring a software package:
25080 [atlocal.in] --> config.status* --<
25086 Files created during test suite execution:
25089 atconfig -->. .--> testsuite.log
25093 [atlocal] ->' `--> [testsuite.dir]
25097 @node Autotest Logs
25098 @subsection Autotest Logs
25100 When run, the test suite creates a log file named after itself, e.g., a
25101 test suite named @command{testsuite} creates @file{testsuite.log}. It
25102 contains a lot of information, usually more than maintainers actually
25103 need, but therefore most of the time it contains all that is needed:
25106 @item command line arguments
25107 A bad but unfortunately widespread habit consists of
25108 setting environment variables before the command, such as in
25109 @samp{CC=my-home-grown-cc ./testsuite}. The test suite does not
25110 know this change, hence (i) it cannot report it to you, and (ii)
25111 it cannot preserve the value of @code{CC} for subsequent runs.
25112 Autoconf faced exactly the same problem, and solved it by asking
25113 users to pass the variable definitions as command line arguments.
25114 Autotest requires this rule, too, but has no means to enforce it; the log
25115 then contains a trace of the variables that were changed by the user.
25117 @item @file{ChangeLog} excerpts
25118 The topmost lines of all the @file{ChangeLog} files found in the source
25119 hierarchy. This is especially useful when bugs are reported against
25120 development versions of the package, since the version string does not
25121 provide sufficient information to know the exact state of the sources
25122 the user compiled. Of course, this relies on the use of a
25125 @item build machine
25126 Running a test suite in a cross-compile environment is not an easy task,
25127 since it would mean having the test suite run on a machine @var{build},
25128 while running programs on a machine @var{host}. It is much simpler to
25129 run both the test suite and the programs on @var{host}, but then, from
25130 the point of view of the test suite, there remains a single environment,
25131 @var{host} = @var{build}. The log contains relevant information on the
25132 state of the @var{build} machine, including some important environment
25134 @c FIXME: How about having an M4sh macro to say "hey, log the value
25135 @c of '@dots{}'"? This would help both Autoconf and Autotest.
25137 @item tested programs
25138 The absolute file name and answers to @option{--version} of the tested
25139 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25141 @item configuration log
25142 The contents of @file{config.log}, as created by @command{configure},
25143 are appended. It contains the configuration flags and a detailed report
25144 on the configuration itself.
25148 @node Writing Testsuites
25149 @section Writing @file{testsuite.at}
25151 The @file{testsuite.at} is a Bourne shell script making use of special
25152 Autotest M4 macros. It often contains a call to @code{AT_INIT} near
25153 its beginning followed by one call to @code{m4_include} per source file
25154 for tests. Each such included file, or the remainder of
25155 @file{testsuite.at} if include files are not used, contain a sequence of
25156 test groups. Each test group begins with a call to @code{AT_SETUP},
25157 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25158 and then completes with a call to @code{AT_CLEANUP}. Multiple test
25159 groups can be categorized by a call to @code{AT_BANNER}.
25161 All of the public Autotest macros have all-uppercase names in the
25162 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25163 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25164 internal macros. All shell variables used in the testsuite for internal
25165 purposes have mostly-lowercase names starting with @samp{at_}. Autotest
25166 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25167 makes use of the file system namespace @samp{^at-}.
25169 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25170 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25171 of those namespaces (@samp{^_?\(m4\|AS\)_}). In general, you
25172 @emph{should not use} the namespace of a package that does not own the
25173 macro or shell code you are writing.
25175 @defmac AT_INIT (@ovar{name})
25177 @c FIXME: Not clear, plus duplication of the information.
25178 Initialize Autotest. Giving a @var{name} to the test suite is
25179 encouraged if your package includes several test suites. Before this
25180 macro is called, @code{AT_PACKAGE_STRING} and
25181 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25182 information about the testsuite to the user. Typically, these macros
25183 are provided by a file @file{package.m4} built by @command{make}
25184 (@pxref{Making testsuite Scripts}), in order to inherit the package
25185 name, version, and bug reporting address from @file{configure.ac}.
25188 @defmac AT_COPYRIGHT (@var{copyright-notice})
25189 @atindex{COPYRIGHT}
25190 @cindex Copyright Notice
25191 State that, in addition to the Free Software Foundation's copyright on
25192 the Autotest macros, parts of your test suite are covered by
25193 @var{copyright-notice}.
25195 The @var{copyright-notice} shows up in both the head of
25196 @command{testsuite} and in @samp{testsuite --version}.
25199 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25200 @ovar{action-if-given}, @ovar{action-if-not-given})
25201 @atindex{ARG_OPTION}
25202 @vrindex at_arg_@var{option}
25203 Accept options from the space-separated list @var{options}, a list that
25204 has leading dashes removed from the options. Long options will be
25205 prefixed with @samp{--}, single-character options with @samp{-}. The
25206 first word in this list is the primary @var{option}, any others are
25207 assumed to be short-hand aliases. The variable associated with it
25208 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25211 If the user passes @option{--@var{option}} to the @command{testsuite},
25212 the variable will be set to @samp{:}. If the user does not pass the
25213 option, or passes @option{--no-@var{option}}, then the variable will be
25214 set to @samp{false}.
25217 @vrindex at_optarg_@var{option}
25218 @var{action-if-given} is run each time the option is encountered; here,
25219 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25220 appropriate. @code{at_optarg} is actually just a copy of
25221 @code{at_arg_@var{option}}.
25223 @var{action-if-not-given} will be run once after option parsing is
25224 complete and if no option from @var{options} was used.
25226 @var{help-text} is added to the end of the list of options shown in
25227 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25229 It is recommended that you use a package-specific prefix to @var{options}
25230 names in order to avoid clashes with future Autotest built-in options.
25233 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25234 @ovar{action-if-given}, @ovar{action-if-not-given})
25235 @atindex{ARG_OPTION_ARG}
25236 @vrindex at_arg_@var{option}
25237 Accept options with arguments from the space-separated list
25238 @var{options}, a list that has leading dashes removed from the options.
25239 Long options will be prefixed with @samp{--}, single-character options
25240 with @samp{-}. The first word in this list is the primary @var{option},
25241 any others are assumed to be short-hand aliases. The variable associated
25242 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25243 replaced with underscores.
25245 If the user passes @option{--@var{option}=@var{arg}} or
25246 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25247 variable will be set to @samp{@var{arg}}.
25250 @var{action-if-given} is run each time the option is encountered; here,
25251 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25252 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25254 @var{action-if-not-given} will be run once after option parsing is
25255 complete and if no option from @var{options} was used.
25257 @var{help-text} is added to the end of the list of options shown in
25258 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25260 It is recommended that you use a package-specific prefix to @var{options}
25261 names in order to avoid clashes with future Autotest built-in options.
25264 @defmac AT_COLOR_TESTS
25265 @atindex{COLOR_TESTS}
25266 Enable colored test results by default when the output is connected to
25270 @defmac AT_TESTED (@var{executables})
25272 Log the file name and answer to @option{--version} of each program in
25273 space-separated list @var{executables}. Several invocations register
25274 new executables, in other words, don't fear registering one program
25277 Autotest test suites rely on @env{PATH} to find the tested program.
25278 This avoids the need to generate absolute names of the various tools, and
25279 makes it possible to test installed programs. Therefore, knowing which
25280 programs are being exercised is crucial to understanding problems in
25281 the test suite itself, or its occasional misuses. It is a good idea to
25282 also subscribe foreign programs you depend upon, to avoid incompatible
25285 @var{executables} is implicitly wrapped in shell double quotes, but it
25286 will still use shell variable expansion (@samp{$}), command substitution
25287 (@samp{`}), and backslash escaping (@samp{\}). In particular, the
25288 @env{EXEEXT} variable is available if it is passed to the testsuite
25289 via @file{atlocal} or @file{atconfig}.
25292 @defmac AT_PREPARE_TESTS (@var{shell-code})
25293 @atindex{PREPARE_TESTS}
25294 Execute @var{shell-code} in the main testsuite process,
25295 after initializing the test suite and processing command-line options,
25296 but before running any tests. If this macro is used several times,
25297 all of the @var{shell-code}s will be executed,
25298 in the order they appeared in @file{testsuite.at}.
25300 One reason to use @code{AT_PREPARE_TESTS} is when the programs under
25301 test are sensitive to environment variables: you can unset all these
25302 variables or reset them to safe values in @var{shell-code}.
25304 @var{shell-code} is only executed if at least one test is going to be
25305 run. In particular, it will not be executed if any of the @option{--help},
25306 @option{--version}, @option{--list}, or @option{--clean} options are
25307 given to @command{testsuite} (@pxref{testsuite Invocation}).
25310 @defmac AT_PREPARE_EACH_TEST (@var{shell-code})
25311 @atindex{AT_PREPARE_EACH_TEST}
25312 Execute @var{shell-code} in each test group's subshell, at the point of
25313 the @code{AT_SETUP} that starts the test group.
25316 @defmac AT_TEST_HELPER_FN (@var{name}, @var{args}, @var{description}, @var{code})
25317 Define a shell function that will be available to the code for each test
25318 group. Its name will be @code{ath_fn_@var{name}}, and its body will be
25319 @var{code}. (The prefix prevents name conflicts with shell functions
25320 defined by M4sh and Autotest.)
25322 @var{args} should describe the function's arguments and @var{description}
25323 what it does; these are used only for documentation comments in the
25324 generated testsuite script.
25329 @defmac AT_BANNER (@var{test-category-name})
25331 This macro identifies the start of a category of related test groups.
25332 When the resulting @file{testsuite} is invoked with more than one test
25333 group to run, its output will include a banner containing
25334 @var{test-category-name} prior to any tests run from that category. The
25335 banner should be no more than about 40 or 50 characters. A blank banner
25336 indicates uncategorized tests; an empty line will be inserted after
25337 tests from an earlier category, effectively ending that category.
25340 @defmac AT_SETUP (@var{test-group-name})
25342 This macro starts a group of related tests, all to be executed in the
25343 same subshell. It accepts a single argument, which holds a few words
25344 (no more than about 30 or 40 characters) quickly describing the purpose
25345 of the test group being started. @var{test-group-name} must not expand
25346 to unbalanced quotes, although quadrigraphs can be used.
25349 @defmac AT_KEYWORDS (@var{keywords})
25351 Associate the space-separated list of @var{keywords} to the enclosing
25352 test group. This makes it possible to run ``slices'' of the test suite.
25353 For instance, if some of your test groups exercise some @samp{foo}
25354 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25355 @samp{./testsuite -k foo} to run exclusively these test groups. The
25356 @var{test-group-name} of the test group is automatically recorded to
25357 @code{AT_KEYWORDS}.
25359 Several invocations within a test group accumulate new keywords. In
25360 other words, don't fear registering the same keyword several times in a
25364 @defmac AT_CAPTURE_FILE (@var{file})
25365 @atindex{CAPTURE_FILE}
25366 If the current test group fails, log the contents of @var{file}.
25367 Several identical calls within one test group have no additional effect.
25370 @defmac AT_FAIL_IF (@var{shell-condition})
25372 Make the test group fail and skip the rest of its execution, if
25373 @var{shell-condition} is true. @var{shell-condition} is a shell expression
25374 such as a @code{test} command. Tests before @command{AT_FAIL_IF}
25375 will be executed and may still cause the test group to be skipped.
25376 You can instantiate this macro many times from within the same test group.
25378 You should use this macro only for very simple failure conditions. If the
25379 @var{shell-condition} could emit any kind of output you should instead
25380 use @command{AT_CHECK} like
25382 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25385 so that such output is properly recorded in the @file{testsuite.log}
25389 @defmac AT_SKIP_IF (@var{shell-condition})
25391 Determine whether the test should be skipped because it requires
25392 features that are unsupported on the machine under test.
25393 @var{shell-condition} is a shell expression such as a @code{test}
25394 command. Tests before @command{AT_SKIP_IF} will be executed
25395 and may still cause the test group to fail. You can instantiate this
25396 macro many times from within the same test group.
25398 You should use this macro only for very simple skip conditions. If the
25399 @var{shell-condition} could emit any kind of output you should instead
25400 use @command{AT_CHECK} like
25402 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25405 so that such output is properly recorded in the @file{testsuite.log}
25409 @defmac AT_XFAIL_IF (@var{shell-condition})
25411 Determine whether the test is expected to fail because it is a known
25412 bug (for unsupported features, you should skip the test).
25413 @var{shell-condition} is a shell expression such as a @code{test}
25414 command; you can instantiate this macro many times from within the
25415 same test group, and one of the conditions is enough to turn
25416 the test into an expected failure.
25421 End the current test group.
25426 @defmac AT_DATA (@var{file}, @var{contents})
25427 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25429 Initialize an input data @var{file} with given @var{contents}. Of
25430 course, the @var{contents} have to be properly quoted between square
25431 brackets to protect against included commas or spurious M4
25432 expansion. @var{contents} must be empty or end with a newline.
25434 be a single shell word that expands into a single file name.
25436 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25437 that only the latter performs shell variable expansion (@samp{$}),
25438 command substitution (@samp{`}), and backslash escaping (@samp{\})
25442 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25443 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25444 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25445 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25447 @atindex{CHECK_UNQUOTED}
25449 Perform a test, by running the shell @var{commands} in a subshell.
25450 @var{commands} is output as-is, so shell expansions are honored.
25451 These commands are expected to have a final exit status of @var{status},
25452 and to produce output as described by @var{stdout} and @var{stderr}
25455 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25457 If @var{commands} exit with unexpected status 77, then the rest of the
25458 test group is skipped. If @var{commands} exit with unexpected status
25459 99, then the test group is immediately failed; this is called a
25460 @emph{hard failure}. Otherwise, the test is considered to have
25461 succeeded if all of the status, stdout, and stderr expectations were
25464 If @var{run-if-fail} is nonempty, it provides extra shell commands to
25465 run when the test fails; if @var{run-if-pass} is nonempty, it provides
25466 extra shell commands to run when the test succeeds. These commands are
25467 @emph{not} run in a subshell, and they are not run when the test group
25468 is skipped (exit code 77) or hard-failed (exit code 99). They may
25469 change whether the test group is considered to have succeeded, by
25470 modifying the shell variable @code{at_failed}; set it to @code{:} to
25471 indicate that the test group has failed, or @code{false} to indicate
25472 that it has succeeded.
25474 The exit status of @var{commands} is available to @var{run-if-fail} and
25475 @var{run-if-pass} commands in the @code{at_status} shell variable. The
25476 output from @var{commands} is also available, in the files named by the
25477 @code{at_stdout} and @code{at_stderr} variables.
25479 If @var{status} is the literal @samp{ignore}, then the exit status of
25480 @var{commands} is not checked, except for the special cases of 77 (skip)
25481 and 99 (hard failure). The existence of hard failures allows one to
25482 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25483 feature has not yet been implemented, but to still distinguish between
25484 gracefully handling the missing feature and dumping core.
25486 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25487 literals in the following table, then the test treats the output
25488 according to the rules of that literal.
25492 The content of the output is ignored, but still captured in the test
25493 group log (if the testsuite is run with the @option{-v} option, the test
25494 group log is displayed as the test is run; if the test group later
25495 fails, the test group log is also copied into the overall testsuite
25496 log). This action is valid for both @var{stdout} and @var{stderr}.
25499 The content of the output is ignored, and nothing is captured in the log
25500 files. If @var{commands} are likely to produce binary output (including
25501 long lines) or large amounts of output, then logging the output can make
25502 it harder to locate details related to subsequent tests within the
25503 group, and could potentially corrupt terminal display of a user running
25504 @command{testsuite -v}. This action is valid for both @var{stdout} and
25508 Only valid as the @var{stdout} parameter. Capture the content of
25509 standard output in both a file named @file{stdout} and the test group log.
25510 Subsequent commands in the test group can then post-process the file.
25511 This action is often used when it is desired to use @command{grep} to
25512 look for a substring in the output, or when the output must be
25513 post-processed to normalize error messages into a common form.
25516 Only valid as the @var{stderr} parameter. Capture the content of
25517 standard error in both a file named @file{stderr} and the test group log.
25520 @itemx stderr-nolog
25521 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25522 not duplicated into the test group log. This action is particularly
25523 useful for an intermediate check that produces large amounts of data,
25524 which will be followed by another check that filters down to the
25525 relevant data, as it makes it easier to locate details in the log.
25528 Only valid as the @var{stdout} parameter. Compare standard output with
25529 the previously created file @file{expout}, and list any differences in
25533 Only valid as the @var{stderr} parameter. Compare standard error with
25534 the previously created file @file{experr}, and list any differences in
25538 Otherwise, the values of the @var{stdout} and @var{stderr} parameters
25539 are treated as text that must exactly match the output given by
25540 @var{commands} on standard output and standard error (including an empty
25541 parameter for no output); any differences are captured in the testsuite
25542 log and the test is failed (unless an unexpected exit status of 77
25543 skipped the test instead).
25545 @code{AT_CHECK_UNQUOTED} performs shell variable expansion (@samp{$}),
25546 command substitution (@samp{`}), and backslash escaping (@samp{\}) on
25547 comparison text given in the @var{stdout} and @var{stderr} parameters;
25548 @code{AT_CHECK} does not. There is no difference in the interpretation
25552 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25553 @ovar{run-if-fail}, @ovar{run-if-pass})
25554 @atindex{CHECK_EUNIT}
25555 Initialize and execute an Erlang module named @var{module} that performs
25556 tests following the @var{test-spec} EUnit test specification.
25557 @var{test-spec} must be a valid EUnit test specification, as defined in
25558 the @uref{https://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25559 Reference Manual}. @var{erlflags} are optional command-line options
25560 passed to the Erlang interpreter to execute the test Erlang module.
25561 Typically, @var{erlflags} defines at least the paths to directories
25562 containing the compiled Erlang modules under test, as @samp{-pa path1
25565 For example, the unit tests associated with Erlang module @samp{testme},
25566 which compiled code is in subdirectory @file{src}, can be performed
25570 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25571 [-pa "$@{abs_top_builddir@}/src"])
25574 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25576 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25577 must be defined as the path of the Erlang interpreter, the path of the
25578 Erlang compiler, and the command-line flags to pass to the compiler,
25579 respectively. Those variables should be configured in
25580 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25581 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25582 variables are automatically defined in the testsuite. If @code{ERL} or
25583 @code{ERLC} is not defined, the test group is skipped.
25585 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25586 be loaded, the test group is skipped. Otherwise, if @var{test-spec} is
25587 an invalid EUnit test specification, the test group fails. Otherwise,
25588 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25589 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25590 executed and the test group fails.
25592 Only the generated test Erlang module is automatically compiled and
25593 executed. If @var{test-spec} involves testing other Erlang modules,
25594 e.g. module @samp{testme} in the example above, those modules must be
25597 If the testsuite is run in verbose mode and with the @option{--verbose} option,
25598 EUnit is also run in verbose mode to output more details about
25599 individual unit tests.
25603 @node testsuite Invocation
25604 @section Running @command{testsuite} Scripts
25605 @cindex @command{testsuite}
25607 Autotest test suites support the following options:
25612 Display the list of options and exit successfully.
25616 Display the version of the test suite and exit successfully.
25618 @item --directory=@var{dir}
25619 @itemx -C @var{dir}
25620 Change the current directory to @var{dir} before creating any files.
25621 Useful for running the testsuite in a subdirectory from a top-level
25624 @item --jobs@r{[}=@var{n}@r{]}
25626 Run @var{n} tests in parallel, if possible. If @var{n} is not given,
25627 run all given tests in parallel. Note that there should be no space
25628 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25629 the separate arguments @option{-j} and @option{@var{number}}, see below.
25631 In parallel mode, the standard input device of the testsuite script is
25632 not available to commands inside a test group. Furthermore, banner
25633 lines are not printed, and the summary line for each test group is
25634 output after the test group completes. Summary lines may appear
25635 unordered. If verbose and trace output are enabled (see below), they
25636 may appear intermixed from concurrently running tests.
25638 Parallel mode requires the @command{mkfifo} command to work, and will be
25639 silently disabled otherwise.
25643 Remove all the files the test suite might have created and exit. Meant
25644 for @code{clean} Make targets.
25648 List all the tests (or only the selection), including their possible
25654 By default all tests are performed (or described with @option{--list})
25655 silently in the default environment, but the environment, set of tests,
25656 and verbosity level can be tuned:
25659 @item @var{variable}=@var{value}
25660 Set the environment @var{variable} to @var{value}. Use this rather
25661 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25662 different environment.
25664 @cindex @code{AUTOTEST_PATH}
25665 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25666 to @env{PATH}. Relative directory names (not starting with
25667 @samp{/}) are considered to be relative to the top level of the
25668 package being built. All directories are made absolute, first
25669 starting from the top level @emph{build} tree, then from the
25670 @emph{source} tree. For instance @samp{./testsuite
25671 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25672 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25673 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25677 @itemx @var{number}-@var{number}
25678 @itemx @var{number}-
25679 @itemx -@var{number}
25680 Add the corresponding test groups, with obvious semantics, to the
25683 @item --keywords=@var{keywords}
25684 @itemx -k @var{keywords}
25685 Add to the selection the test groups with title or keywords (arguments
25686 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25687 of the comma separated list @var{keywords}, case-insensitively. Use
25688 @samp{!} immediately before the keyword to invert the selection for this
25689 keyword. By default, the keywords match whole words; enclose them in
25690 @samp{.*} to also match parts of words.
25692 For example, running
25695 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25699 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25700 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25704 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25708 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25709 containing @samp{FUNC}.
25713 If any test fails, immediately abort testing. This implies
25714 @option{--debug}: post test group clean up, and top-level logging
25715 are inhibited. This option is meant for the full test
25716 suite, it is not really useful for generated debugging scripts.
25717 If the testsuite is run in parallel mode using @option{--jobs},
25718 then concurrently running tests will finish before exiting.
25722 Force more verbosity in the detailed output of what is being done. This
25723 is the default for debugging scripts.
25726 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25727 Enable colored test results. Without an argument, or with @samp{always},
25728 test results will be colored. With @samp{never}, color mode is turned
25729 off. Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25730 the testsuite author, or the argument @samp{auto} is given, then test
25731 results are colored if standard output is connected to a terminal.
25735 Do not remove the files after a test group was performed---but they are
25736 still removed @emph{before}, therefore using this option is sane when
25737 running several test groups. Create debugging scripts. Do not
25738 overwrite the top-level
25739 log (in order to preserve a supposedly existing full log file). This is
25740 the default for debugging scripts, but it can also be useful to debug
25741 the testsuite itself.
25744 Add to the selection all test groups that failed or passed unexpectedly
25745 during the last non-debugging test run.
25749 Trigger shell tracing of the test groups.
25752 Besides these options accepted by every Autotest testsuite, the
25753 testsuite author might have added package-specific options
25754 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25755 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25756 the package documentation for details.
25759 @node Making testsuite Scripts
25760 @section Making @command{testsuite} Scripts
25762 For putting Autotest into movement, you need some configuration and
25763 makefile machinery. We recommend, at least if your package uses deep or
25764 shallow hierarchies, that you use @file{tests/} as the name of the
25765 directory holding all your tests and their makefile. Here is a
25766 check list of things to do, followed by an example, taking into
25767 consideration whether you are also using Automake.
25772 @cindex @file{package.m4}
25773 @atindex{PACKAGE_STRING}
25774 @atindex{PACKAGE_BUGREPORT}
25775 @atindex{PACKAGE_NAME}
25776 @atindex{PACKAGE_TARNAME}
25777 @atindex{PACKAGE_VERSION}
25778 @atindex{PACKAGE_URL}
25779 Make sure to create the file @file{package.m4}, which defines the
25780 identity of the package. It must define @code{AT_PACKAGE_STRING}, the
25781 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25782 address to which bug reports should be sent. For sake of completeness,
25783 we suggest that you also define @code{AT_PACKAGE_NAME},
25784 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25785 @code{AT_PACKAGE_URL}.
25786 @xref{Initializing configure}, for a description of these variables.
25787 Be sure to distribute @file{package.m4} and to put it into the source
25788 hierarchy: the test suite ought to be shipped! See below for an example.
25791 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25793 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25794 @acindex{CONFIG_TESTDIR}
25795 An Autotest test suite is to be configured in @var{directory}. This
25796 macro causes @file{@var{directory}/atconfig} to be created by
25797 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25798 @var{test-path} (@pxref{testsuite Invocation}).
25802 Still within @file{configure.ac}, as appropriate, ensure that some
25803 @code{AC_CONFIG_FILES} command includes substitution for
25804 @file{tests/atlocal}.
25807 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25808 variable to be set.
25811 The appropriate @file{Makefile} should be modified so the validation in
25812 your package is triggered by @samp{make check}.
25815 The following example demonstrates the above checklist, first by
25816 assuming that you are using Automake (see below for tweaks to make to
25817 get the same results without Automake). Begin by adding the following
25818 lines to your @file{configure.ac}:
25821 # Initialize the test suite.
25822 AC_CONFIG_TESTDIR([tests])
25823 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25824 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25827 Next, add the following lines to your @file{tests/Makefile.am}, in order
25828 to link @samp{make check} with a validation suite.
25831 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25832 printf >'$@@' '%s\n' \
25833 '# Signature of the current package.' \
25834 'm4_define([AT_PACKAGE_NAME], [$(PACKAGE_NAME)])' \
25835 'm4_define([AT_PACKAGE_TARNAME], [$(PACKAGE_TARNAME)])' \
25836 'm4_define([AT_PACKAGE_VERSION], [$(PACKAGE_VERSION)])' \
25837 'm4_define([AT_PACKAGE_STRING], [$(PACKAGE_STRING)])' \
25838 'm4_define([AT_PACKAGE_URL], [$(PACKAGE_URL)])' \
25839 'm4_define([AT_PACKAGE_BUGREPORT], [$(PACKAGE_BUGREPORT)])'
25841 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25842 TESTSUITE = $(srcdir)/testsuite
25844 check-local: atconfig atlocal $(TESTSUITE)
25845 $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25847 installcheck-local: atconfig atlocal $(TESTSUITE)
25848 $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25852 test ! -f '$(TESTSUITE)' || \
25853 $(SHELL) '$(TESTSUITE)' --clean
25855 AUTOTEST = $(AUTOM4TE) --language=autotest
25856 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25857 $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25861 Note that the built testsuite is distributed; this is necessary because
25862 users might not have Autoconf installed, and thus would not be able to
25863 rebuild it. Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25864 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25865 provide the user with
25866 a nicer error message if they modify a source file to the testsuite, and
25867 accidentally trigger the rebuild rules.
25869 You might want to list explicitly the dependencies, i.e., the list of
25870 the files @file{testsuite.at} includes.
25872 If you don't use Automake, you should make the following tweaks. In
25873 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25874 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}. You are
25875 welcome to also try using the @command{missing} script from the Automake
25876 project instead of @command{false}, to try to get a nicer error message
25877 when the user modifies prerequisites but did not have Autoconf
25878 installed, but at that point you may be better off using Automake.
25879 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25880 place it in your @file{tests/@/Makefile.in} instead. Add code to your
25881 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25882 distributed, as well as adding the following additional lines to prepare
25883 the set of needed Makefile variables:
25887 PACKAGE_NAME = @@PACKAGE_NAME@@
25888 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25889 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25890 PACKAGE_STRING = @@PACKAGE_STRING@@
25891 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25892 PACKAGE_URL = @@PACKAGE_URL@@
25893 AUTOM4TE = @@AUTOM4TE@@
25895 atconfig: $(top_builddir)/config.status
25896 cd $(top_builddir) && \
25897 $(SHELL) ./config.status $(subdir)/$@@
25899 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25900 cd $(top_builddir) && \
25901 $(SHELL) ./config.status $(subdir)/$@@
25904 Using the above example (with or without Automake), and assuming you
25905 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25906 makefile, you can now fine-tune test suite execution at runtime by
25907 altering this variable, for example:
25910 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25915 @c =============================== Frequent Autoconf Questions, with answers
25918 @chapter Frequent Autoconf Questions, with answers
25920 Several questions about Autoconf come up occasionally. Here some of them
25924 * Distributing:: Distributing @command{configure} scripts
25925 * Why GNU M4:: Why not use the standard M4?
25926 * Bootstrapping:: Autoconf and GNU M4 require each other?
25927 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
25928 * Defining Directories:: Passing @code{datadir} to program
25929 * Autom4te Cache:: What is it? Can I remove it?
25930 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
25931 * Expanded Before Required:: Expanded Before Required
25932 * Debugging:: Debugging @command{configure} scripts
25936 @section Distributing @command{configure} Scripts
25940 What are the restrictions on distributing @command{configure}
25941 scripts that Autoconf generates? How does that affect my
25942 programs that use them?
25945 There are no restrictions on how the configuration scripts that Autoconf
25946 produces may be distributed or used. In Autoconf version 1, they were
25947 covered by the GNU General Public License. We still encourage
25948 software authors to distribute their work under terms like those of the
25949 GPL, but doing so is not required to use Autoconf.
25951 Of the other files that might be used with @command{configure},
25952 @file{config.h.in} is under whatever copyright you use for your
25953 @file{configure.ac}. @file{config.sub} and @file{config.guess} have an
25954 exception to the GPL when they are used with an Autoconf-generated
25955 @command{configure} script, which permits you to distribute them under the
25956 same terms as the rest of your package. @file{install-sh} is from the X
25957 Consortium and is not copyrighted.
25960 @section Why Require GNU M4?
25963 Why does Autoconf require GNU M4?
25966 Many M4 implementations have hard-coded limitations on the size and
25967 number of macros that Autoconf exceeds. They also lack several
25968 builtin macros that it would be difficult to get along without in a
25969 sophisticated application like Autoconf, including:
25979 Autoconf requires version 1.4.8 or later of GNU M4.
25980 It works better with version 1.4.16 or later.
25982 Since only software maintainers need to use Autoconf, and since GNU
25983 M4 is simple to configure and install, it seems reasonable to require
25984 GNU M4 to be installed also. Many maintainers of GNU and
25985 other free software already have most of the GNU utilities
25986 installed, since they prefer them.
25988 @node Bootstrapping
25989 @section How Can I Bootstrap?
25993 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25994 @command{configure} script, how do I bootstrap? It seems like a chicken
25998 This is a misunderstanding. Although GNU M4 does come with a
25999 @command{configure} script produced by Autoconf, Autoconf is not required
26000 in order to run the script and install GNU M4. Autoconf is only
26001 required if you want to change the M4 @command{configure} script, which few
26002 people have to do (mainly its maintainer).
26004 @node Why Not Imake
26005 @section Why Not Imake?
26009 Why not use Imake instead of @command{configure} scripts?
26012 Several people have written addressing this question, so
26013 adaptations of their explanations are included here.
26015 The following answer is based on one written by Richard Pixley:
26018 Autoconf generated scripts frequently work on machines that it has
26019 never been set up to handle before. That is, it does a good job of
26020 inferring a configuration for a new system. Imake cannot do this.
26022 Imake uses a common database of host specific data. For X11, this makes
26023 sense because the distribution is made as a collection of tools, by one
26024 central authority who has control over the database.
26026 GNU tools are not released this way. Each GNU tool has a
26027 maintainer; these maintainers are scattered across the world. Using a
26028 common database would be a maintenance nightmare. Autoconf may appear
26029 to be this kind of database, but in fact it is not. Instead of listing
26030 host dependencies, it lists program requirements.
26032 If you view the GNU suite as a collection of native tools, then the
26033 problems are similar. But the GNU development tools can be
26034 configured as cross tools in almost any host+target permutation. All of
26035 these configurations can be installed concurrently. They can even be
26036 configured to share host independent files across hosts. Imake doesn't
26037 address these issues.
26039 Imake templates are a form of standardization. The GNU coding
26040 standards address the same issues without necessarily imposing the same
26045 Here is some further explanation, written by Per Bothner:
26048 One of the advantages of Imake is that it is easy to generate large
26049 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
26050 However, @code{cpp} is not programmable: it has limited conditional
26051 facilities, and no looping. And @code{cpp} cannot inspect its
26054 All of these problems are solved by using @code{sh} instead of
26055 @code{cpp}. The shell is fully programmable, has macro substitution,
26056 can execute (or source) other shell scripts, and can inspect its
26061 Paul Eggert elaborates more:
26064 With Autoconf, installers need not assume that Imake itself is already
26065 installed and working well. This may not seem like much of an advantage
26066 to people who are accustomed to Imake. But on many hosts Imake is not
26067 installed or the default installation is not working well, and requiring
26068 Imake to install a package hinders the acceptance of that package on
26069 those hosts. For example, the Imake template and configuration files
26070 might not be installed properly on a host, or the Imake build procedure
26071 might wrongly assume that all source files are in one big directory
26072 tree, or the Imake configuration might assume one compiler whereas the
26073 package or the installer needs to use another, or there might be a
26074 version mismatch between the Imake expected by the package and the Imake
26075 supported by the host. These problems are much rarer with Autoconf,
26076 where each package comes with its own independent configuration
26079 Also, Imake often suffers from unexpected interactions between
26080 @command{make} and the installer's C preprocessor. The fundamental problem
26081 here is that the C preprocessor was designed to preprocess C programs,
26082 not makefiles. This is much less of a problem with Autoconf,
26083 which uses the general-purpose preprocessor M4, and where the
26084 package's author (rather than the installer) does the preprocessing in a
26089 Finally, Mark Eichin notes:
26092 Imake isn't all that extensible, either. In order to add new features to
26093 Imake, you need to provide your own project template, and duplicate most
26094 of the features of the existing one. This means that for a sophisticated
26095 project, using the vendor-provided Imake templates fails to provide any
26096 leverage---since they don't cover anything that your own project needs
26097 (unless it is an X11 program).
26099 On the other side, though:
26101 The one advantage that Imake has over @command{configure}:
26102 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26103 than @file{Makefile.in} files. There is a fix to this, however---at least
26104 for the Kerberos V5 tree, we've modified things to call in common
26105 @file{post.in} and @file{pre.in} makefile fragments for the
26106 entire tree. This means that a lot of common things don't have to be
26107 duplicated, even though they normally are in @command{configure} setups.
26111 @node Defining Directories
26112 @section How Do I @code{#define} Installation Directories?
26115 My program needs library files, installed in @code{datadir} and
26119 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26120 [Define to the read-only architecture-independent
26128 #define DATADIR "$@{prefix@}/share"
26132 As already explained, this behavior is on purpose, mandated by the
26133 GNU Coding Standards, see @ref{Installation Directory
26134 Variables}. There are several means to achieve a similar goal:
26138 Do not use @code{AC_DEFINE} but use your makefile to pass the
26139 actual value of @code{datadir} via compilation flags.
26140 @xref{Installation Directory Variables}, for the details.
26143 This solution can be simplified when compiling a program: you may either
26144 extend the @code{CPPFLAGS}:
26147 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26151 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26154 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26158 Alternatively, create a dedicated header file:
26161 DISTCLEANFILES = myprog-paths.h
26162 myprog-paths.h: Makefile
26163 printf '%s\n' '#define DATADIR "$(datadir)"' >$@@
26167 The Gnulib module @samp{configmake} provides such a header with all the
26168 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26172 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26173 value of @code{datadir} and others. Many people have wrapped macros to
26174 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26175 the @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26178 This solution does not conform to the GNU Coding Standards.
26181 Note that all the previous solutions hard wire the absolute name of
26182 these directories in the executables, which is not a good property. You
26183 may try to compute the names relative to @code{prefix}, and try to
26184 find @code{prefix} at runtime, this way your package is relocatable.
26188 @node Autom4te Cache
26189 @section What is @file{autom4te.cache}?
26192 What is this directory @file{autom4te.cache}? Can I safely remove it?
26195 In the GNU Build System, @file{configure.ac} plays a central
26196 role and is read by many tools: @command{autoconf} to create
26197 @file{configure}, @command{autoheader} to create @file{config.h.in},
26198 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26199 check the completeness of @file{configure.ac}, @command{autoreconf} to
26200 check the GNU Build System components that are used. To
26201 ``read @file{configure.ac}'' actually means to compile it with M4,
26202 which can be a long process for complex @file{configure.ac}.
26204 This is why all these tools, instead of running directly M4, invoke
26205 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26206 a specific demand, stores additional information in
26207 @file{autom4te.cache} for future runs. For instance, if you run
26208 @command{autoconf}, behind the scenes, @command{autom4te} also
26209 stores information for the other tools, so that when you invoke
26210 @command{autoheader} or @command{automake} etc., reprocessing
26211 @file{configure.ac} is not needed. The speed up is frequently 30%,
26212 and is increasing with the size of @file{configure.ac}.
26214 But it is and remains being simply a cache: you can safely remove it.
26219 Can I permanently get rid of it?
26222 The creation of this cache can be disabled from
26223 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26224 details. You should be aware that disabling the cache slows down the
26225 Autoconf test suite by 40%. The more GNU Build System
26226 components are used, the more the cache is useful; for instance
26227 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26228 the cache @emph{although @option{--force} implies that the cache is
26229 not fully exploited}, and eight times slower than without
26233 @node Present But Cannot Be Compiled
26234 @section Header Present But Cannot Be Compiled
26236 The most important guideline to bear in mind when checking for
26237 features is to mimic as much as possible the intended use.
26238 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26239 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26240 the preprocessor, instead of the compiler, to check for headers. As a
26241 result, incompatibilities between headers went unnoticed during
26242 configuration, and maintainers finally had to deal with this issue
26245 The transition began with Autoconf 2.56. As of Autoconf 2.64 both
26246 checks are performed, and @command{configure} complains loudly if the
26247 compiler and the preprocessor do not agree. However, only the compiler
26248 result is considered. As of Autoconf 2.70, only the compiler check is
26251 Consider the following example:
26254 $ @kbd{cat number.h}
26255 typedef int number;
26257 const number pi = 3;
26258 $ @kbd{cat configure.ac}
26259 AC_INIT([Example], [1.0], [bug-example@@example.org])
26260 AC_CHECK_HEADERS([pi.h])
26261 $ @kbd{autoconf -Wall}
26262 $ @kbd{./configure CPPFLAGS='-I.'}
26263 checking for gcc... gcc
26264 checking whether the C compiler works... yes
26265 checking for C compiler default output file name... a.out
26266 checking for suffix of executables...
26267 checking whether we are cross compiling... no
26268 checking for suffix of object files... o
26269 checking whether the compiler supports GNU C... yes
26270 checking whether gcc accepts -g... yes
26271 checking for gcc option to enable C23 features... -std=gnu23
26272 checking for sys/types.h... yes
26273 checking for sys/stat.h... yes
26274 checking for strings.h... yes
26275 checking for inttypes.h... yes
26276 checking for stdint.h... yes
26277 checking for unistd.h... yes
26278 checking for pi.h... no
26282 The proper way to handle this case is using the fourth argument
26283 (@pxref{Generic Headers}):
26286 $ @kbd{cat configure.ac}
26287 AC_INIT([Example], [1.0], [bug-example@@example.org])
26288 AC_CHECK_HEADERS([number.h pi.h], [], [],
26289 [[#ifdef HAVE_NUMBER_H
26290 # include <number.h>
26293 $ @kbd{autoconf -Wall}
26294 $ @kbd{./configure CPPFLAGS='-I.'}
26295 checking for gcc... gcc
26296 checking whether the C compiler works... yes
26297 checking for C compiler default output file name... a.out
26298 checking for suffix of executables...
26299 checking whether we are cross compiling... no
26300 checking for suffix of object files... o
26301 checking whether the compiler supports GNU C... yes
26302 checking whether gcc accepts -g... yes
26303 checking for gcc option to enable C23 features... -std=gnu23
26304 checking for number.h... yes
26305 checking for pi.h... yes
26308 See @ref{Particular Headers}, for a list of headers with their
26311 @node Expanded Before Required
26312 @section Expanded Before Required
26314 @cindex expanded before required
26315 Older versions of Autoconf silently built files with incorrect ordering
26316 between dependent macros if an outer macro first expanded, then later
26317 indirectly required, an inner macro. Starting with Autoconf 2.64, this
26318 situation no longer generates out-of-order code, but results in
26319 duplicate output and a syntax warning:
26322 $ @kbd{cat configure.ac}
26323 @result{}AC_DEFUN([TESTA], [[echo in A
26324 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26325 @result{}SEEN_A=:]])
26326 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26327 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26328 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26329 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26336 @result{}configure.ac:11: warning: AC_REQUIRE:
26337 @result{} 'TESTA' was expanded before it was required
26338 @result{}configure.ac:4: TESTB is expanded from...
26339 @result{}configure.ac:6: TESTC is expanded from...
26340 @result{}configure.ac:7: OUTER is expanded from...
26341 @result{}configure.ac:11: the top level
26345 To avoid this warning, decide what purpose the macro in question serves.
26346 If it only needs to be expanded once (for example, if it provides
26347 initialization text used by later macros), then the simplest fix is to
26348 change the macro to be declared with @code{AC_DEFUN_ONCE}
26349 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26350 newer. A more portable fix is to change all
26351 instances of direct calls to instead go through @code{AC_REQUIRE}
26352 (@pxref{Prerequisite Macros}). If, instead, the macro is parameterized
26353 by arguments or by the current definition of other macros in the m4
26354 environment, then the macro should always be directly expanded instead
26357 For another case study, consider this example trimmed down from an
26358 actual package. Originally, the package contained shell code and
26359 multiple macro invocations at the top level of @file{configure.ac}:
26362 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26369 but that was getting complex, so the author wanted to offload some of
26370 the text into a new macro in another file included via
26371 @file{aclocal.m4}. The naïve approach merely wraps the text in a new
26375 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26385 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26386 before the single compiler check, as the author intended. But with
26387 Autoconf 2.64, this issues the ``expanded before it was required''
26388 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26389 check, one before @samp{foobar=}, and one after. To understand why this
26390 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26391 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood. According to
26392 the documented semantics of @code{AC_REQUIRE}, this means that
26393 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26394 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26395 use of @samp{foobar=}. The older versions of Autoconf were broken with
26396 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26397 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26398 autoconf. In other words, the author was unknowingly relying on a bug
26399 exploit to get the desired results, and that exploit broke once the bug
26402 So, what recourse does the author have, to restore their intended
26403 semantics of setting @samp{foobar=} prior to a single compiler check,
26404 regardless of whether Autoconf 2.63 or 2.64 is used? One idea is to
26405 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26406 there is always the possibility of using the lower-level
26410 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26420 This works great if everything is in the same file. However, it does
26421 not help in the case where the author wants to have @command{aclocal}
26422 find the definition of @code{BAR} from its own file, since
26423 @command{aclocal} requires the use of @code{AC_DEFUN}. In this case, a
26424 better fix is to recognize that if @code{BAR} also uses
26425 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26426 to a subsequent require. Then, by creating yet another helper macro,
26427 the author can once again guarantee a single invocation of
26428 @code{AC_PROG_CC}, which will still occur after @code{foobar=}. The
26429 author can also use @code{AC_BEFORE} to make sure no other macro
26430 appearing before @code{BAR} has triggered an unwanted expansion of
26434 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26435 AC_DEFUN([BEFORE_CC], [
26439 AC_BEFORE([$0], [AC_PROG_CC])dnl
26440 AC_REQUIRE([BEFORE_CC])dnl
26441 AC_REQUIRE([AC_PROG_CC])dnl
26449 @section Debugging @command{configure} scripts
26451 While in general, @command{configure} scripts generated by Autoconf
26452 strive to be fairly portable to various systems, compilers, shells, and
26453 other tools, it may still be necessary to debug a failing test, broken
26454 script or makefile, or fix or override an incomplete, faulty, or erroneous
26455 test, especially during macro development. Failures can occur at all levels,
26456 in M4 syntax or semantics, shell script issues, or due to bugs in the
26457 test or the tools invoked by @command{configure}. Together with the
26458 rather arcane error message that @command{m4} and @command{make} may
26459 produce when their input contains syntax errors, this can make debugging
26462 Nevertheless, here is a list of hints and strategies that may help:
26466 When @command{autoconf} fails, common causes for error include:
26470 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26473 @item under- or over-quoted macro arguments (@pxref{Autoconf
26474 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26477 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26481 Typically, it helps to go back to the last working version of the input
26482 and compare the differences for each of these errors. Another
26483 possibility is to sprinkle pairs of @code{m4_traceon} and
26484 @code{m4_traceoff} judiciously in the code, either without a parameter
26485 or listing some macro names and watch @command{m4} expand its input
26486 verbosely (@pxref{Debugging via autom4te}).
26489 Sometimes @command{autoconf} succeeds but the generated
26490 @command{configure} script has invalid shell syntax. You can detect this
26491 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26492 If this command fails, the same tips apply, as if @command{autoconf} had
26496 Debugging @command{configure} script execution may be done by sprinkling
26497 pairs of @code{set -x} and @code{set +x} into the shell script before
26498 and after the region that contains a bug. Running the whole script with
26499 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26500 @var{shell} may work, but produces lots of output. Here, it can help to
26501 search for markers like @samp{checking for} a particular test in the
26505 Alternatively, you might use a shell with debugging capabilities like
26506 @uref{https://bashdb.sourceforge.net/, bashdb}.
26509 When @command{configure} tests produce invalid results for your system,
26510 it may be necessary to override them:
26514 For programs, tools or libraries variables, preprocessor, compiler, or
26515 linker flags, it is often sufficient to override them at @command{make}
26516 run time with some care (@pxref{Macros and Submakes}). Since this
26517 normally won't cause @command{configure} to be run again with these
26518 changed settings, it may fail if the changed variable would have caused
26519 different test results from @command{configure}, so this may work only
26520 for simple differences.
26523 Most tests which produce their result in a substituted variable allow to
26524 override the test by setting the variable on the @command{configure}
26525 command line (@pxref{Compilers and Options}, @pxref{Defining Variables}).
26528 Many tests store their result in a cache variable (@pxref{Caching
26529 Results}). This lets you override them either on the
26530 @command{configure} command line as above, or through a primed cache or
26531 site file (@pxref{Cache Files}, @pxref{Site Defaults}). The name of a
26532 cache variable is documented with a test macro or may be inferred from
26533 @ref{Cache Variable Names}; the precise semantics of undocumented
26534 variables are often internal details, subject to change.
26538 Alternatively, @command{configure} may produce invalid results because
26539 of uncaught programming errors, in your package or in an upstream
26540 library package. For example, when @code{AC_CHECK_LIB} fails to find a
26541 library with a specified function, always check @file{config.log}. This
26542 will reveal the exact error that produced the failing result: the
26543 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26546 Conversely, as macro author, you can make it easier for users of your
26551 by minimizing dependencies between tests and between test results as far
26555 by using @command{make} variables to factorize and allow
26556 override of settings at @command{make} run time,
26559 by honoring the GNU Coding Standards and not overriding flags
26560 reserved for the user except temporarily during @command{configure}
26564 by not requiring users of your macro to use the cache variables.
26565 Instead, expose the result of the test via @var{run-if-true} and
26566 @var{run-if-false} parameters. If the result is not a boolean,
26567 then provide it through documented shell variables.
26571 @c ===================================================== History of Autoconf.
26574 @chapter History of Autoconf
26575 @cindex History of autoconf
26577 @emph{This chapter was written by the original author, David MacKenzie.}
26579 You may be wondering, Why was Autoconf originally written? How did it
26580 get into its present form? (Why does it look like gorilla spit?) If
26581 you're not wondering, then this chapter contains no information useful
26582 to you, and you might as well skip it. If you @emph{are} wondering,
26583 then let there be light@enddots{}
26586 * Genesis:: Prehistory and naming of @command{configure}
26587 * Exodus:: The plagues of M4 and Perl
26588 * Leviticus:: The priestly code of portability arrives
26589 * Numbers:: Growth and contributors
26590 * Deuteronomy:: Approaching the promises of easy configuration
26596 In June 1991 I was maintaining many of the GNU utilities for the
26597 Free Software Foundation. As they were ported to more platforms and
26598 more programs were added, the number of @option{-D} options that users
26599 had to select in the makefile (around 20) became burdensome.
26600 Especially for me---I had to test each new release on a bunch of
26601 different systems. So I wrote a little shell script to guess some of
26602 the correct settings for the fileutils package, and released it as part
26603 of fileutils 2.0. That @command{configure} script worked well enough that
26604 the next month I adapted it (by hand) to create similar @command{configure}
26605 scripts for several other GNU utilities packages. Brian Berliner
26606 also adapted one of my scripts for his CVS revision control system.
26608 Later that summer, I learned that Richard Stallman and Richard Pixley
26609 were developing similar scripts to use in the GNU compiler tools;
26610 so I adapted my @command{configure} scripts to support their evolving
26611 interface: using the file name @file{Makefile.in} as the templates;
26612 adding @samp{+srcdir}, the first option (of many); and creating
26613 @file{config.status} files.
26618 As I got feedback from users, I incorporated many improvements, using
26619 Emacs to search and replace, cut and paste, similar changes in each of
26620 the scripts. As I adapted more GNU utilities packages to use
26621 @command{configure} scripts, updating them all by hand became impractical.
26622 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26623 mail saying that the @command{configure} scripts were great, and asking if
26624 I had a tool for generating them that I could send him. No, I thought,
26625 but I should! So I started to work out how to generate them. And the
26626 journey from the slavery of hand-written @command{configure} scripts to the
26627 abundance and ease of Autoconf began.
26629 Cygnus @command{configure}, which was being developed at around that time,
26630 is table driven; it is meant to deal mainly with a discrete number of
26631 system types with a small number of mainly unguessable features (such as
26632 details of the object file format). The automatic configuration system
26633 that Brian Fox had developed for Bash takes a similar approach. For
26634 general use, it seems to me a hopeless cause to try to maintain an
26635 up-to-date database of which features each variant of each operating
26636 system has. It's easier and more reliable to check for most features on
26637 the fly---especially on hybrid systems that people have hacked on
26638 locally or that have patches from vendors installed.
26640 I considered using an architecture similar to that of Cygnus
26641 @command{configure}, where there is a single @command{configure} script that
26642 reads pieces of @file{configure.in} when run. But I didn't want to have
26643 to distribute all of the feature tests with every package, so I settled
26644 on having a different @command{configure} made from each
26645 @file{configure.in} by a preprocessor. That approach also offered more
26646 control and flexibility.
26648 I looked briefly into using the Metaconfig package, by Larry Wall,
26649 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26650 reasons. The @command{Configure} scripts it produces are interactive,
26651 which I find quite inconvenient; I didn't like the ways it checked for
26652 some features (such as library functions); I didn't know that it was
26653 still being maintained, and the @command{Configure} scripts I had
26654 seen didn't work on many modern systems (such as System V R4 and NeXT);
26655 it wasn't flexible in what it could do in response to a feature's
26656 presence or absence; I found it confusing to learn; and it was too big
26657 and complex for my needs (I didn't realize then how much Autoconf would
26658 eventually have to grow).
26660 I considered using Perl to generate my style of @command{configure}
26661 scripts, but decided that M4 was better suited to the job of simple
26662 textual substitutions: it gets in the way less, because output is
26663 implicit. Plus, everyone already has it. (Initially I didn't rely on
26664 the GNU extensions to M4.) Also, some of my friends at the
26665 University of Maryland had recently been putting M4 front ends on
26666 several programs, including @code{tvtwm}, and I was interested in trying
26667 out a new language.
26672 Since my @command{configure} scripts determine the system's capabilities
26673 automatically, with no interactive user intervention, I decided to call
26674 the program that generates them Autoconfig. But with a version number
26675 tacked on, that name would be too long for old Unix file systems,
26676 so I shortened it to Autoconf.
26678 In the fall of 1991 I called together a group of fellow questers after
26679 the Holy Grail of portability (er, that is, alpha testers) to give me
26680 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26681 and continued to add features and improve the techniques used in the
26682 checks. Prominent among the testers were François Pinard, who came up
26683 with the idea of making an Autoconf shell script to run M4
26684 and check for unresolved macro calls; Richard Pixley, who suggested
26685 running the compiler instead of searching the file system to find
26686 include files and symbols, for more accurate results; Karl Berry, who
26687 got Autoconf to configure @TeX{} and added the macro index to the
26688 documentation; and Ian Lance Taylor, who added support for creating a C
26689 header file as an alternative to putting @option{-D} options in a
26690 makefile, so he could use Autoconf for his UUCP package.
26691 The alpha testers cheerfully adjusted their files again and again as the
26692 names and calling conventions of the Autoconf macros changed from
26693 release to release. They all contributed many specific checks, great
26694 ideas, and bug fixes.
26699 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26700 and converted many GNU packages to use it. I was surprised by how
26701 positive the reaction to it was. More people started using it than I
26702 could keep track of, including people working on software that wasn't
26703 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26704 Autoconf continued to improve rapidly, as many people using the
26705 @command{configure} scripts reported problems they encountered.
26707 Autoconf turned out to be a good torture test for M4 implementations.
26708 Unix M4 started to dump core because of the length of the
26709 macros that Autoconf defined, and several bugs showed up in GNU
26710 M4 as well. Eventually, we realized that we needed to use some
26711 features that only GNU M4 has. 4.3BSD M4, in
26712 particular, has an impoverished set of builtin macros; the System V
26713 version is better, but still doesn't provide everything we need.
26715 More development occurred as people put Autoconf under more stresses
26716 (and to uses I hadn't anticipated). Karl Berry added checks for X11.
26717 david zuhn contributed C++ support. François Pinard made it diagnose
26718 invalid arguments. Jim Blandy bravely coerced it into configuring
26719 GNU Emacs, laying the groundwork for several later improvements.
26720 Roland McGrath got it to configure the GNU C Library, wrote the
26721 @command{autoheader} script to automate the creation of C header file
26722 templates, and added a @option{--verbose} option to @command{configure}.
26723 Noah Friedman added the @option{--autoconf-dir} option and
26724 @code{AC_MACRODIR} environment variable. (He also coined the term
26725 @dfn{autoconfiscate} to mean ``adapt a software package to use
26726 Autoconf''.) Roland and Noah improved the quoting protection in
26727 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26728 dealing with portability problems from February through June, 1993.
26731 @section Deuteronomy
26733 A long wish list for major features had accumulated, and the effect of
26734 several years of patching by various people had left some residual
26735 cruft. In April 1994, while working for Cygnus Support, I began a major
26736 revision of Autoconf. I added most of the features of the Cygnus
26737 @command{configure} that Autoconf had lacked, largely by adapting the
26738 relevant parts of Cygnus @command{configure} with the help of david zuhn
26739 and Ken Raeburn. These features include support for using
26740 @file{config.sub}, @file{config.guess}, @option{--host}, and
26741 @option{--target}; making links to files; and running @command{configure}
26742 scripts in subdirectories. Adding these features enabled Ken to convert
26743 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26746 I added more features in response to other peoples' requests. Many
26747 people had asked for @command{configure} scripts to share the results of
26748 the checks between runs, because (particularly when configuring a large
26749 source tree, like Cygnus does) they were frustratingly slow. Mike
26750 Haertel suggested adding site-specific initialization scripts. People
26751 distributing software that had to unpack on MS-DOS asked for a way to
26752 override the @file{.in} extension on the file names, which produced file
26753 names like @file{config.h.in} containing two dots. Jim Avera did an
26754 extensive examination of the problems with quoting in @code{AC_DEFINE}
26755 and @code{AC_SUBST}; his insights led to significant improvements.
26756 Richard Stallman asked that compiler output be sent to @file{config.log}
26757 instead of @file{/dev/null}, to help people debug the Emacs
26758 @command{configure} script.
26760 I made some other changes because of my dissatisfaction with the quality
26761 of the program. I made the messages showing results of the checks less
26762 ambiguous, always printing a result. I regularized the names of the
26763 macros and cleaned up coding style inconsistencies. I added some
26764 auxiliary utilities that I had developed to help convert source code
26765 packages to use Autoconf. With the help of François Pinard, I made
26766 the macros not interrupt each others' messages. (That feature revealed
26767 some performance bottlenecks in GNU M4, which he hastily
26768 corrected!) I reorganized the documentation around problems people want
26769 to solve. And I began a test suite, because experience had shown that
26770 Autoconf has a pronounced tendency to regress when we change it.
26772 Again, several alpha testers gave invaluable feedback, especially
26773 François Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26776 Finally, version 2.0 was ready. And there was much rejoicing. (And I
26777 have free time again. I think. Yeah, right.)
26780 @c ========================================================== Appendices
26783 @node GNU Free Documentation License
26784 @appendix GNU Free Documentation License
26792 * Environment Variable Index:: Index of environment variables used
26793 * Output Variable Index:: Index of variables set in output files
26794 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
26795 * Cache Variable Index:: Index of documented cache variables
26796 * Autoconf Macro Index:: Index of Autoconf macros
26797 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
26798 * Autotest Macro Index:: Index of Autotest macros
26799 * Program & Function Index:: Index of those with portability problems
26800 * Concept Index:: General index
26803 @node Environment Variable Index
26804 @appendixsec Environment Variable Index
26806 This is an alphabetical list of the environment variables that might
26807 influence Autoconf checks.
26811 @node Output Variable Index
26812 @appendixsec Output Variable Index
26814 This is an alphabetical list of the variables that Autoconf can
26815 substitute into files that it creates, typically one or more
26816 makefiles. @xref{Setting Output Variables}, for more information
26817 on how this is done.
26821 @node Preprocessor Symbol Index
26822 @appendixsec Preprocessor Symbol Index
26824 This is an alphabetical list of the C preprocessor symbols that the
26825 Autoconf macros define. To work with Autoconf, C source code needs to
26826 use these names in @code{#if} or @code{#ifdef} directives.
26830 @node Cache Variable Index
26831 @appendixsec Cache Variable Index
26833 This is an alphabetical list of documented cache variables used
26834 by macros defined in Autoconf. Autoconf macros may use additional cache
26835 variables internally.
26836 @ifset shortindexflag
26837 To make the list easier to use, the variables are listed without their
26838 preceding @samp{ac_cv_}.
26843 @node Autoconf Macro Index
26844 @appendixsec Autoconf Macro Index
26846 This is an alphabetical list of the Autoconf macros.
26847 @ifset shortindexflag
26848 To make the list easier to use, the macros are listed without their
26849 preceding @samp{AC_}.
26854 @node M4 Macro Index
26855 @appendixsec M4 Macro Index
26857 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26858 @ifset shortindexflag
26859 To make the list easier to use, the macros are listed without their
26860 preceding @samp{m4_} or @samp{AS_}. The prefix is @samp{m4_} for
26861 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26867 @node Autotest Macro Index
26868 @appendixsec Autotest Macro Index
26870 This is an alphabetical list of the Autotest macros.
26871 @ifset shortindexflag
26872 To make the list easier to use, the macros are listed without their
26873 preceding @samp{AT_}.
26878 @node Program & Function Index
26879 @appendixsec Program and Function Index
26881 This is an alphabetical list of the programs and functions whose
26882 portability is discussed in this document.
26886 @node Concept Index
26887 @appendixsec Concept Index
26889 This is an alphabetical list of the files, tools, and concepts
26890 introduced in this document.
26896 @c LocalWords: texinfo setfilename autoconf texi settitle setchapternewpage
26897 @c LocalWords: setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26898 @c LocalWords: makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26899 @c LocalWords: shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26900 @c LocalWords: asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26901 @c LocalWords: msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26902 @c LocalWords: direntry autoscan autoreconf autoheader autoupdate config FDs
26903 @c LocalWords: testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26904 @c LocalWords: insertcopying Autoconf's detailmenu Automake Libtool POSIX ois
26905 @c LocalWords: Systemology Checkpointing Changequote INTERCAL changequote dfn
26906 @c LocalWords: Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26907 @c LocalWords: LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26908 @c LocalWords: distclean uninstall noindent versioning Tromey dir vr
26909 @c LocalWords: SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26910 @c LocalWords: evindex automake Gettext autopoint gettext symlink libtoolize
26911 @c LocalWords: defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26912 @c LocalWords: SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26913 @c LocalWords: builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26914 @c LocalWords: CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26915 @c LocalWords: datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26916 @c LocalWords: includedir infodir libexecdir localedir localstatedir mandir
26917 @c LocalWords: oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26918 @c LocalWords: sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26919 @c LocalWords: undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26920 @c LocalWords: PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26921 @c LocalWords: inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26922 @c LocalWords: LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26923 @c LocalWords: inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26924 @c LocalWords: isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26925 @c LocalWords: ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26926 @c LocalWords: snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26927 @c LocalWords: strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26928 @c LocalWords: PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26929 @c LocalWords: closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26930 @c LocalWords: largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26931 @c LocalWords: SETGID getloadavg nlist GETMNTENT irix acxindex autom
26932 @c LocalWords: getmntent UnixWare GETPGRP getpgid getpgrp POSIX's pid LSTAT
26933 @c LocalWords: lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26934 @c LocalWords: localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26935 @c LocalWords: SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26936 @c LocalWords: STRTOD strtod DECL STRFTIME strftime UTIME utime VPRINTF
26937 @c LocalWords: DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26938 @c LocalWords: linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26939 @c LocalWords: NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26940 @c LocalWords: inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26941 @c LocalWords: STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm te
26942 @c LocalWords: ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26943 @c LocalWords: WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26944 @c LocalWords: DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26945 @c LocalWords: passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26946 @c LocalWords: gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26947 @c LocalWords: ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26948 @c LocalWords: varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26949 @c LocalWords: const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26950 @c LocalWords: xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26951 @c LocalWords: ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26952 @c LocalWords: fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26953 @c LocalWords: statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26954 @c LocalWords: GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26955 @c LocalWords: changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26956 @c LocalWords: Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26957 @c LocalWords: bregexp Overquote overquotation meisch maisch meische maische
26958 @c LocalWords: miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26959 @c LocalWords: EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26960 @c LocalWords: pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26961 @c LocalWords: drivespec POSIXy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26962 @c LocalWords: yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26963 @c LocalWords: CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26964 @c LocalWords: MAILPATH scanset arg NetBSD Almquist printf expr cp pR
26965 @c LocalWords: Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM url fc
26966 @c LocalWords: sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc ing FP
26967 @c LocalWords: mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26968 @c LocalWords: fooXXXXXX Unicos utimes hpux hppa unescaped SUBST'ed
26969 @c LocalWords: pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26970 @c LocalWords: cpu wildcards rpcc rdtsc powerpc readline
26971 @c LocalWords: withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26972 @c LocalWords: cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26973 @c LocalWords: lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26974 @c LocalWords: intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26975 @c LocalWords: fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26976 @c LocalWords: ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26977 @c LocalWords: installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26978 @c LocalWords: DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26979 @c LocalWords: Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26980 @c LocalWords: autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26981 @c LocalWords: printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26982 @c LocalWords: VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26983 @c LocalWords: GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26984 @c LocalWords: esyscmd len maketemp pushdef substr syscmd sysval translit txt
26985 @c LocalWords: sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26986 @c LocalWords: Dynix basename aname cname macroexpands xno xcheck iso
26987 @c LocalWords: LIBREADLINE lreadline lncurses libreadline vrindex SYS
26988 @c LocalWords: syncodeindex define'd caindex CAindex MacKenzie DIRS
26989 @c LocalWords: Runtime runtime Submakes submakes MAKEFLAGS whitespace
26990 @c LocalWords: Timestamps Unportability Canonicalizing stdckdint dirN
26991 @c LocalWords: acinclude AMFLAGS LIBS OBJCXXFLAGS GOFLAGS runstatedir
26992 @c LocalWords: metacharacter EXPENSIVEP errno setjmp wctype sys mawk
26993 @c LocalWords: nawk ggrep egrep gegrep fgrep gfgrep LEX lex yytext nm
26994 @c LocalWords: yywrap xflex lexyy YFLAGS yacc divnum libs fuindex ffs
26995 @c LocalWords: environ sigaction extern ftello nonnull STRTOLD LLONG
26996 @c LocalWords: strtold vfprintf ULLONG strcasecmp strncasecmp MSVC th
26997 @c LocalWords: NDEBUG INO libc ISDIR ISREG Tektronix Amdahl ino
26998 @c LocalWords: typedef pxref fileblocks submembers INTMAX intmax UINT
26999 @c LocalWords: INTPTR intptr SSIZE ssize uint UINTPTR uintptr OPENMP
27000 @c LocalWords: openmp OpenMP omp Alignas Alignof Noreturn UTF vals gl
27001 @c LocalWords: offsetof VARARRAYS VLA CCC stdcxx nullptr
27002 @c LocalWords: constexpr decltype unicode fstreams iostreams iomanip
27003 @c LocalWords: stringstreams GXX OBJCPP OBJCXX objcxx GOBJCXX erlc tx
27004 @c LocalWords: OBJCXXCPP FIXEDFORM GFC argc argv shellvar fpp MODEXT
27005 @c LocalWords: freeform fixedform MODINC MODOUT gccgo GOC xmkmf fseek
27006 @c LocalWords: interpval ftell Interix macOS PTHREAD NonStop XOPEN xc
27007 @c LocalWords: IEC ATTRIBS BFP DFP O'Donell Sebor ERTS Erlang's erts
27008 @c LocalWords: erlang Wundef scalable USG NOTMAKE DOUCH
27009 @c LocalWords: IVE changesyntax ifnotinfo oline num cfg debugfile cdr
27010 @c LocalWords: debugmode traceoff traceon patsubst dumpdefs ifelse aa
27011 @c LocalWords: mkstemp undivert lifo errprintn BINSH sanitization bcd
27012 @c LocalWords: cleardivert bmatch bpatsubsts subst cond nblank ifval
27013 @c LocalWords: ifblank ifnblank ifvaln fputc fgetc argn mapall dvarv
27014 @c LocalWords: shiftn abcd elt noquote mkargs joinall SHA prereq dup
27015 @c LocalWords: listc setb seta ARITH HNUM xcurly xoccupied
27016 @c LocalWords: TESTA TESTB TESTC hoc xpg xxyzzyz dtksh nosuch fifos
27017 @c LocalWords: fifo Stardent sig WIF WIFSIGNALED SIGQUIT tty perl ret
27018 @c LocalWords: SIGINT NUL SFN PRN aeiou MSYS SIGTERM xhi arith UWIN
27019 @c LocalWords: CLICOLOR FPATH POSIXLY Shellshock CVE doit ec ci
27020 @c LocalWords: notreached cim nc ACL faccessat Alexandre getline sqrt
27021 @c LocalWords: CONVFMT FS OFMT CDS chgrp futimens utimensat oo esc od
27022 @c LocalWords: ownerships mape readdir mkfifo mknod testsuites XSI rf
27023 @c LocalWords: bcdox hexdump filelist rmdir flushleft busybox nl HAZy
27024 @c LocalWords: ABCDEFGHIJKLMNOPQRSTUVWXYZ Fantazy FAntAZy adc unix xb
27025 @c LocalWords: SUBMAKEFLAGS ehBc ehB hBc hvB dmake hostname nlinit xf
27026 @c LocalWords: DCOMMENT bart pathnames ifhtml randx
27027 @c LocalWords: sumc hic ic fwrapv ftrapv SIGFPE memset fmudflap ctime
27028 @c LocalWords: asctime lvalues lvalue Multithreaded decstation gdb na
27029 @c LocalWords: enableval lesskey FHS superset waitpid libfoo cposix
27030 @c LocalWords: mem RESTARTABLE bzero DejaGNU EUNIT subfile optarg ive
27031 @c LocalWords: nolog expout experr erlflags EUnit testme eunit myprog
27032 @c LocalWords: configmake vx bashdb tvtwm questers UUCP McGrath
27033 @c LocalWords: ispell
27034 @c Local Variables:
27037 @c ispell-local-dictionary: "american"
27038 @c indent-tabs-mode: nil
27039 @c whitespace-check-buffer-indent: nil